Big Bucket Software you like to use
Objective-C Trace statements
May 18th, 2008

Lately, I’ve been trying to avoid calling NSLog directly in my Cocoa applications. I generally use NSLog to trace an application without having to resort to using breakpoints and such. The problem with calling NSLog directly is that it doesn’t automatically give any indication of the current location in the application. I have written two preprocessor definitions that take care of this:

#define BBTrace NSLog(@"%s", __PRETTY_FUNCTION__);

#define BBTraceInfo(s,...) \
{ \
    NSString* info = BBInfoString(s, ##__VA_ARGS__); \
    NSLog(@"%s (%@)", __PRETTY_FUNCTION__, info); \
    [info release]; \
}

The implementation of BBInfoString is as follows:

NSString* BBInfoString(NSString* format, ...)
{
    va_list args;

    va_start(args, format);

    NSString* info =
        [[NSString alloc] initWithFormat:format arguments:args];

    va_end(args);

    return info;
}

The basic usage is:

-(void)func
{
    BBTrace;

    if (isEnabled)
    {
        BBTraceInfo(@"enabled");
    }
}

The output is:

May 18 16:47:29 Machine App[72187]: -[SomeClass func]
May 18 16:47:29 Machine App[72187]: -[SomeClass func] (enabled)

These functions are available for download. Feel free to use them in your own applications.

  • I tend to do something similar. I’ve got a macro named debug, which looks like this:

    #ifdef DEBUG
    #define debug(…) NSLog(__VA_ARGS__)
    #else
    #define debug(…)
    #endif

    And in the target settings for the debug build, I put this in the “other C flags”:
    -DDEBUG

    And then my trace function looks like this:
    debug(@”%s:%d”, __FUNCTION__, __LINE__);

    It prints out something like so:
    -[VPWindowController dealloc]:751

    And I only see messages on my dev builds.

  • […] Big Bucket Blog just recently published a blog post which makes available a few custom BBTrace functions. These […]

  • Is there a way to force NSLog to output to a file instead of the console so that I can segregate all my logs to that file and I wouldn’t have to sort through the logs from other apps?