How to use NSLog and print only for debugging?

Why NSLog and print are dangerous?

Using NSLog and print are very popular logging mechanisms in iOS applications. However, in most cases logging to standard output is useful only for debugging applications and is useless in the released application. Moreover, logging too much information in the release mode of the application might become a security risk, if it reveals API endpoints or usernames. That’s why it’s always a good idea to remove sensitive NSLogs and prints before releasing the app.

One possible solution

To make the process easier it’s a good idea to use NSLog preprocessor macros to differentiate between DebugLog and ReleaseLog:

The defined macros can both use a different function, which decides about the logging:

What’s about Swift?

Solving the same problem is much easier in Swift. One possible solution is to redefine the printing method and add additional method for release log.

Swift also has the debugPrint method, but its name is misleading. DebugPrint will print in both release and debug modes of the application. According to documentation debugPrint just uses better output format:

How to define the “DEBUG” flag?

As you can see, custom implementations of NSLog and print assume existence of the DEBUG flag. The debug flag can be easily defined in the Xcode project settings:

Go to Project settings -> Preprocessor macros -> Debug

Enter DEBUG=1 to the Debug section

Xcode might generate DEBUG=1 flag automatically based on the version.

NSLog

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *

*