Leaving logging statements in production code

I’ve written in the past about how I think that leaving logging code in production or release builds is bad practice. While I have no objections to being able to turn debug logging on or off to help troubleshoot problems in the field, it shouldn’t be on by default. Recently I’ve read conflicting views about leaving NSLog statements in code. One really good solution is:

 


#ifdef DEBUG_MODE
#define DebugLog( s, ... ) NSLog( @"%s %@:(%d) %@", __PRETTY_FUNCTION__,\
[[NSString stringWithUTF8String:__FILE__] lastPathComponent], __LINE__,\
[NSString stringWithFormat:(s), ##__VA_ARGS__] )
#else
#define DebugLog( s, ... )
#endif

(I’ve modified the solution a little.)

Then in Xcode’s build settings, add a preprocessor macro for DEBUG_MODE. Presto, NSLog statements never make it into shipping code. If you need to turn the logging on and off, I like to write the statements out to a file so that they don’t pollute Console and it makes it easier for users to send me logs. Furthermore, I’ve seen NSLog cause crashes because the developer passed the wrong arguments or did something like NSLog(@”test: %d, self). This type of bug should be fixed, but using the above logging would prevent the crash in production code.

 

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.