Sunday, December 12, 2010

Global log level control with cocoalumberjack

I started playing around with cocoalumberjack on the iPad to record user interactions and usage with the DDFileLogger.   The need to have a global log level became necessary otherwise I would have to assign ddLogLevel in every class.  

static const int ddLogLevel = LOG_LEVEL_VERBOSE;

The cocoalumberjack instructions mentions this feature, but doesn't supply details on the implementation.

I am not 100% sure if this is correct way but it works well enough.

Create a class and create a global ddLogLevel constant and set your required logging level.

Constant.h
extern int const ddLogLevel;

Constant.m
#import "Constants.h"
#import "DDLog.h"

int const ddLogLevel = LOG_LEVEL_VERBOSE;

Configure your logger.

#import "DDLog.h"
#import "DDASLLogger.h"
#import "DDTTYLogger.h"
#import "DDFileLogger.h"

...

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
 
 [DDLog addLogger:[DDASLLogger sharedInstance]];
 [DDLog addLogger:[DDTTYLogger sharedInstance]];
 
 DDFileLogger *fileLogger = [[DDFileLogger alloc] init]; 
 [DDLog addLogger:fileLogger];
 [fileLogger release];

...


To use this now simple import your class.

#import "DDLog.h"
#import "Constants.h"

...

- (void)someMethod {
 DDLogVerbose(@"Log this message");
}

2 comments:

  1. One small improvement... Add #import "DDLog.h" to your Constants.h, so you don't need to add it to every file.

    ReplyDelete
  2. Additionally, for XCode 4, this is also useful (to auto set the level for debug vs. release build)

    #ifdef DEBUG
    int const ddLogLevel = LOG_LEVEL_VERBOSE;
    #else
    int const ddLogLevel = LOG_LEVEL_WARN;
    #endif

    ReplyDelete