Episode #61

Cocoa Lumberjack

10 minutes
Published on April 4, 2013

This video is only available to subscribers. Get access to this video and 572 others.

In this episode we take a look at a fast & flexible alternative logging framework for iOS called Cocoa Lumberjack. We take a look at the various loggers that are available and how to write logs to a file.

Episode Links

Setting up logs

Define a static integer somewhere in your application that is accessible to every file. I put this in Logging.h which was added to the Prefix.pch file in order to have it included everywhere.

#import "DDLog.h"
static const int ddLogLevel = LOG_LEVEL_VERBOSE;

Next, I set up the various loggers we want to use in the app delegate:

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

- (void)setupLogging {
    [DDLog addLogger:[DDTTYLogger sharedInstance]];
    [DDLog addLogger:[DDASLLogger sharedInstance]];

    DDFileLogger *fileLogger = [[DDFileLogger alloc] init];
    [fileLogger setRollingFrequency:60 * 60 * 24];   // roll every day
    [fileLogger setMaximumFileSize:1024 * 1024 * 2]; // max 2mb file size
    [fileLogger.logFileManager setMaximumNumberOfLogFiles:7];

    [DDLog addLogger:fileLogger];

    DDLogVerbose(@"Logging is setup (\"%@\")", [fileLogger.logFileManager logsDirectory]);
}

Making NSLog use Cocoa Lumberjack

If you want to convert all of your NSLog statements to use Cocoa Lumberjack, then simply re-define it as the appropriate log level macro:

// Logging.h

#define NSLog DDLogInfo

Conditionally hiding logs for Release builds

#if DEBUG
static const int ddLogLevel = LOG_LEVEL_VERBOSE;
#else
static const int ddLogLevel = LOG_LEVEL_WARN;
#endif

If you want to make this setting dynamic, perhaps even allowing a toggle setting within the application, then you can make this static variable not a const. Just keep in mind that with a const variable the compiler can optimize out the macros that won't be logged, without it your log statements will still be calls, but nothing will be logged if it's below the current log level setting.