Improved Logging

On 25/10/2009, in Development, Source Code, Tips, by Pelaez

This is an improved logging technique I developed in the last couple of days. It’s not to debug an specific problem, but to get a general idea of where your bug is, and if there are no bugs, to know the stack of methods called.

It’s quite simple, but it does require some work to implement. If you have a big project, it could take some time to implement.

Instructions:

First, get this class, and add it to your project.

Then, in your prefix file, add the following lines:

1
2
3
4
5
#import "KPLogHelper.h"
#define  LOG_IN NSLog(@"XX:%@ %s",[KPLogHelper indent:1], __PRETTY_FUNCTION__);
#define LOG_OUT NSLog(@"XX:%@ %s",[KPLogHelper indent:-1], __PRETTY_FUNCTION__);
#define  LOG_NO NSLog(@"XX:%@ %s",[KPLogHelper indent:0], __PRETTY_FUNCTION__);
#define  LOG(x) NSLog(@"iPC:%@ %@", [KPLogHelper indent:0], x);

The XX should be two characters to filter your logs, it’s not necesary, but it’s useful. You can find more about that here.

And finally, at the beginning of every method you want to log, add LOG_IN, at the end of the method, and before any returns, add LOG_OUT.

If it’s a really small method and you don’t want to know where it starts and when it ends, but only when it happened, just add LOG_NO.

If you want to log with a custom string while respecting the indent level LOG(NSString *here).

The result in the log will be a message when the method is called with an indent level, and the methods that are called before it ends will have an indentation level greater by one, then the indentation level will be reduced by one when the method ends.

It will look something like:

1
2
3
4
5
>>> Method 1 signature //When the first method begins: LOG_IN
>>>>>> Method 2 signature //When the second method is called by the 1st: LOG_ING
====== Method 3 signature //When the 3rd method is called by 2nd: LOG_NO
<<<<<< Method 2 Signature //When the second method returns: LOG_OUT
<<< Method 2 signature //When the first method returns: LOG_OUT

To stop showing the log, just comment the methods so it looks like this:

1
#define  LOG_IN //NSLog(@"XX:%@ %s",[KPLogHelper indent:1], __PRETTY_FUNCTION__);

NOTE: Make sure you disable this logging before releasing you app, as it’s a little heavier than the standard logging (due to the calculations to make the indent) and will slow down your app.

Tagged with:  

Leave a Reply