A handy logging macro for Cocoa
May 12, 2010 Leave a Comment
When developing software, I tend to use both logging and the debugger to gain insight into application behavior. When it comes to logging, I wanted a way to embed log statements in my code that wouldn’t impact release builds of my applications.
While there are clones of Log4J out there for Objective-C, I wanted to keep things simple. What I’ve come up with is a macro that I place in an application’s _prefix.pch file:
#ifdef DEBUG #define DLog(format, ...) NSLog([@"%s " stringByAppendingString:format], __FUNCTION__, ##__VA_ARGS__) #else #define DLog(...) #endif
Then I place DLog() statements in my code where desired. For example, if I place DLog(“Hello”) in the initialize method of AppController, the output would appear as follows:
2010-05-12 06:21:35.627 AppName[28401:a0f] +[AppController initialize] Hello
Note that the location of the log statement is embedded in the output. To have the DLog macro enabled for your debug builds, you’ll need to define the DEBUG preprocessor macro in your build settings.
