How to filter console output in Xcode

ArtFeel picture ArtFeel · Oct 26, 2011 · Viewed 14.4k times · Source

In my iOS project, I use one 3rd-party library, which is is incredible spamming into the console output. Can I apply any filtering to debug output.

Answer

Jano picture Jano · Oct 26, 2011

If the library is using NSLog you can redefine it and discard the log message when it comes from the library. Example code:

#define NSLog(args...) [[Logger singleton] debugWithLevel:kDebug line:__LINE__ funcName:__PRETTY_FUNCTION__ message:args];

// poor man's nslog
@interface Logger : NSObject

typedef enum {
    kTrace=0, kDebug=1, kInfo=2, kWarn=3, kError=4, KSilent=5
} LoggerLevel;


// ...

@implementation Logger

+(Logger *)singleton {
    static dispatch_once_t pred;
    static Logger *shared = nil;
    dispatch_once(&pred, ^{
        shared = [[Logger alloc] init];
        shared.logThreshold = kTrace;
    });
    return shared;
}
-(void) debugWithLevel:(LoggerLevel)level 
                  line:(int)line 
              funcName:(const char *)funcName 
               message:(NSString *)msg, ... {

    va_list ap;         
    va_start (ap, msg); 
    msg = [[[NSString alloc] initWithFormat:msg arguments:ap] autorelease];
    va_end (ap);        

     msg = [NSString stringWithFormat:@"%s %50s:%3d - %@", levelName[level], funcName, line, msg];

    // ... filter by class name ...

    fprintf(stdout,"%s\n", [msg UTF8String]);
}
@end

Note that funcName contains the classname and method sending the message. If the library is a good citizen and has classes that start with a prefix, discard the output if the className starts with that. Otherwise you have to load a list of classes from that library and check them before the fprintf line.

This of course, doesn't duplicate the log to syslogd like NSLog does, but who cares. :P