A handy logging macro for Cocoa

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.

Advertisement

About Tony Ingraldi
Majesty Software was founded in 2007 by Tony Ingraldi where he spends his time as a consultant and an independent software developer.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.