October 30, 2010 0

Better NSLog – Adding function name / line number to NSLog

By admin in Uncategorized

When tracking down a bug, the most useful way to start checking things is to NSLog something. I’m a heavy user of breakpoints and the debugger. I can’t live without it, and it’s saved me countless hours. However I usually see if i can NSLog something first perhaps the problem was an obvious one.

A problem that frequently occurs is that when trying to track down a bug, you end up with many NSLog statements in the console and it’s difficult to know which is which. Often you’ll see coders start adding things like “>>>” or “#”, to differentiate this NEW NSLog statement from the ones already showing up.

An easy solution for this, is to use a better logging function one that can tell you the function from which it was called, and the line number.
The compiler has certain special variables you can use that give you this information. With that knowledge, creating a macro for a better log function becomes very simple.

#define VERBOSE_DEBUG_ENABLED_DEBUG 1 // Set to 0 to turn off
#if !defined(VERBOSE_DEBUG_ENABLED) || VERBOSE_DEBUG_ENABLED == 0 
#define LOGVERBOSE(...) do{}while(0)
#else
#define LOGVERBOSE(__FORMAT__, ...) NSLog(@"%s-Line: %d->%@", __func__, __LINE__, [NSString stringWithFormat:__FORMAT__, __VA_ARGS__])
#endif

Here we are using the special compiler directives (i’m not sure what their proper terms are), __func__, and __LINE__ to create a new NSLog statement that then uses, stringWithFormat: to wrap the user’s log call so that it behaves exactly like NSLog.

In practice it is used like this

#include SOME_HEADER_FILE_WITH_ABOVE_CODE
...
LOGVERBOSE(@"someVar: %0.2f", someVar);
// Outputs
// -[SomeViewControllerSubclass myFunction:]-Line:32->someVar: 4.34

That’s all there is to it. Very useful.

Tags:

Leave a Reply

Powered by WP Hashcash

Spam protection by WP Captcha-Free