A Better NSLog

I looked a bit today at improving the way I use NSLog() and wanted to share my findings here. Recently, I’ve had to use logging as a method of debugging while writing a screen saver, which has been unfortunate. However, I’ve been able to improve it using a #define in my code, inspired by the following sites:

  • The Big Bucket Blog just recently published a blog post which makes available a few custom BBTrace functions. These functions were a great starting point, but I wanted something more compact and that didn’t require adding extra files to my projects.
  • In the comments of the same blog post, Gus Mueller discusses his solution: a simpler #define within an ifdef block that removes logging in Release builds. This is great, but I don’t really need to worry about logging showing up in public builds since I tend to remove all of my logging before committing code to my VCS. Also, I didn’t want to have to add any flags in the target settings of my projects.
  • The Lap Cap Software Blog discusses logging in Leopard, with the goal of removing the log messages from the Console. Again, this isn’t important to me, but the interesting use of arguments to his JJLog() function are what helped me. Also, the idea of adding this code to the .pch file in any project was exactly what I was looking for.

So, after looking at these different options and deciding what information I’m looking for, I came up with the following directive:

#define LRDebug(...) NSLog(@"%s (%d) \n\t %@", __PRETTY_FUNCTION__, __LINE__, [NSString stringWithFormat:__VA_ARGS__])

With this, I’m able to send LRDebug() arguments exactly as NSLog() handles them, using a formatted string. Also, I tried to get the most readable logging I could, so I added the line break and tab after the function and line number. So, some code could call LRDebug(@"The path is: %@", path) and the log would read:

-[Controller awakeFromNib:] (23)
    The path is: /Applications/Mail.app

Perfect!



Comments are closed.
You can follow any responses to this entry through the RSS 2.0 feed. Responses are currently closed, but you can trackback from your own site.

:: RSS Feed :: Archive :: Categories :: Admin