Thursday, September 9, 2010

NSLog tricks: Log only in Debug mode. Add Function name, Line num

It is a common requirement to log certain statements only in the Debug mode, while needing to avoid them in the release mode. Of course, one option is to have statements like this everywhere:

#ifdef DEBUGGING
NSLog(@"Data: point.x = %f, point.y = %f", point.x, point.y);
#endif
And define DEBUGGING somewhere in the header file. However, this can get very verbose. 
A better option is to use Macros. In project_Prefix.pch file, include: 

#ifdef DEBUGGING
# define DBLog(fmt,...) NSLog(@"%@",[NSString stringWithFormat:(fmt), ##__VA_ARGS__]);
#else
# define DBLog(...)
#endif 
Also, you can include, in "Edit Active Target" -> "Build" -> (Select Debug Config) -> "Other C/C++ Flags", write:

-DDEBUGGING 

This automatically defines DEBUGGING flag in Debug mode. Leave it blank for the Release mode.  

Now, you can use DBLog instead of NSLog: 

DBLog(@"Data: point.x = %f, point.y = %f", point.x, point.y);

This will automatically print statements in the Debug mode, and not print the statements in the Release mode! 

(Alternatively, you can have a line in the Prefix.pch file:
#define DEBUGGING 
And manually comment it out for Release mode.)

Similarly, if you want you also have function name and line number, there is a nice trick:

#ifdef DEBUGGING#   define DLog(fmt, ...) NSLog((@"Func: %s , Line: %d, " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
#else
#   define DLog(...)
#endif

If you always want to print out regardless of the DEBUGGING SETTING, but with the function name and line number:
#define ALog(fmt, ...) NSLog((@"Func: %s , Line: %d, " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
Hope that helps! Happy iCoding!

1 comments:

  1. # define DBLog(fmt,...) NSLog(@"%@",[NSString stringWithFormat:(fmt), ##__VA_ARGS__]);

    why not just do

    # define DBLog(fmt,...) NSLog((fmt), ##__VA_ARGS__);

    ReplyDelete