Better logging in Objective-C

October 27, 2008

If you’re an experienced Objective-C developer, chances are you’ve at least heard of spicing up your log statements with FILE and LINE. Here’s one method I wrote last night that includes variable arguments similar to NSLog(). To use it, just stick this line in your prefix header file:

 #define DebugLog( s, ... ) NSLog( @"<%p %@:(%d)> %@", self, [[NSString stringWithUTF8String:__FILE__] lastPathComponent], __LINE__, [NSString stringWithFormat:(s), ##__VA_ARGS__] )

The great thing about the preprocessor #define is that you can build all sorts of things into the DebugLog() function. For example, you could set it up so that the code is only included when you define a variable like BETA_VERSION in your code, or you could send the message to a custom logging class that writes to your own log file or database.

Marc Charbonneau is a mobile software engineer in Portland, OR. Want to reply to this article? Get in touch on Twitter @mbcharbonneau.