Logging in Cocoa

There are a ton of ways and frameworks for logging in your project. At the following I will describe the way it works for me.

For me it’s not so important to have multiple loggers, meaning I can log to a file and the console simultaneously. If you look for such a solution, I recommend to look in the CocoaLumberjack or the NSLogger framework.

My focus is: Log information to the console in a simple way, without any extra dependences and configurable for the debug or the release setting.

My preferred way to get this, is to use macros. The macros are placed at the end of the Prefix.pch file of your project and looks like the following:

#ifdef DEBUG
#define DLog(...) NSLog(@"%s(%p) %@", __PRETTY_FUNCTION__, self, [NSString stringWithFormat:__VA_ARGS__])
#define DCLog(...) NSLog(@"%@", [NSString stringWithFormat:__VA_ARGS__])
#define ALog(...) { NSLog(@"%s(%p) %@", __PRETTY_FUNCTION__, self, [NSString stringWithFormat:__VA_ARGS__]);[[NSAssertionHandler currentHandler] handleFailureInFunction:[NSString stringWithCString:__PRETTY_FUNCTION__ encoding:NSUTF8StringEncoding] file:[NSString stringWithCString:__FILE__ encoding:NSUTF8StringEncoding] lineNumber:__LINE__ description:__VA_ARGS__];}
#else
#define DLog(...) do { } while (0)
#define DCLog(...) do { } while (0)
#ifndef NS_BLOCK_ASSERTIONS
#define NS_BLOCK_ASSERTIONS
#endif
#define ALog(...) NSLog(@"%s(%p) %@", __PRETTY_FUNCTION__, self, [NSString stringWithFormat:__VA_ARGS__])
#endif
#define ZAssert(condition, ...) do { if (!(condition)) { ALog(__VA_ARGS__); }} while(0)

The basic idea of it is, if we run the code in debug mode and use DLog or DCLog we want to log anything to the console, otherwise if the user runs the code, nothing should be logged. Furthermore if you would like to log anytime to the console, regardless of whether you run the code in debug mode or not, you can use the NSLog macro as usually.

For a more detailed description of the macros I would like to recommend you to read My current prefix.ch file from Marcus Zarra that showed me this way to log.

The last thing we have to do is to define the DEBUG variable in the project settings:

Since Xcode 4.3 it seems like, if you start a new project, the DEBUG variable will be the right value by default, so you have nothing to do. Otherwise just set it by hand.