Ever needed to see more context surrounding your NSLog statement to help you debug in the console? Me too. In fact, some people have written entire classes and kindly shared them with us on the internet. Personally, I don’t think an entire class is necessary for this simple task, so I wrote a single preprocessor macro for the job. Here you go!
#define DetailedLog(str, args...) NSLog\
(@"\n-------------\nBetter Log\n%s:%d\n%@\n[%s]\n\n[%@]\n-------------\n",\
strrchr(__FILE__, '/'), __LINE__, self, sel_getName(_cmd),\
[NSString stringWithFormat:str , ## args ] )
Let’s break it down for a second and see what it’s doing:
Firstly, you’ll notice a lot of newlines and pseudo-separators inside the constant string; that’s just to make it easier for me to read all the info at a quick glance. Feel free to change the format to fit your style better, it’s fairly straightforward.
Next you see strrchr(__FILE__, '/') which takes the current file that the log statement is being executed in, and returns a char* of the last file component. Notice that FILE is a special symbol used by our compiler to allow us to know what file we’re currently in, via a handy C string. Sure, we could turn it into an NSString and use -lastPathComponent, but this is just as good (for me anyway).
After this is self, which is self-explanatory. After self, however, is sel_getName(_cmd) which gets a handle on the SEL (selector) of the currently-executing method, and turns it into a C string as well.
Lastly, you’ll notice [NSString stringWithFormat:str , ## args ] which is the exact original string that would have been printed out had you simply used NSLog().
When it’s used with @”Hello World” inside my method -performAction:, this is what the output looks like:
-------------
Better Log
/SDAccountController.m:97
<SDAccountController: 0x2a4c30>
[performAction:]
[Hello world]
-------------
So, hopefully someone will find good use for this, and maybe you’ve even learned a thing or two today that will help you in your future endeavors. Hoorah!
Update:
Thanks to a source who shall remain anonymous, this function was improved to work in functions as well as methods. Thanks tomasf!
#define DetailedLog(str, args...)\
NSLog(@"\n-------------\nBetter Log\n%s:%d\n%s\n\n[%@]\n-------------\n",\
strrchr(__FILE__, '/'), __LINE__, __PRETTY_FUNCTION__,\
[NSString stringWithFormat:str , ## args ] )
This replaces both self and SEL and instead will print out -[SDAccountController performAction:] which is just as informative, but sexier. Here’s the full output after this addition:
-------------
Better Log
/SDAccountController.m:133
-[SDAccountController performAction:]
[foo]
-------------
Enjoy.


