Skip to content

Instantly share code, notes, and snippets.

@benvium
Last active August 29, 2015 14:12
Show Gist options
  • Select an option

  • Save benvium/d2246eb9a86e703333a5 to your computer and use it in GitHub Desktop.

Select an option

Save benvium/d2246eb9a86e703333a5 to your computer and use it in GitHub Desktop.
CocoaLumberjack Custom Log Formatter with time, log level, filename, line number, selector and message. The code `DDLogDebug(@"Enabled notification for status characteristic");` will write to the console: `12:19:13:539 V: DeviceConnector.m:101 bt_onConnected: | Enabled notification for status characteristic`
//
// Created by Ben Clayton on 23/12/14.
// Copyright (c) 2014 Calvium Ltd. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import "DDLog.h"
@interface CustomLogFormatter : NSObject<DDLogFormatter>
@property(nonatomic, strong) NSRegularExpression *regex;
- (NSString *)formatLogMessage:(DDLogMessage *)logMessage;
@end
//
// Created by Ben Clayton on 23/12/14.
// Copyright (c) 2014 Calvium Ltd. All rights reserved.
//
#import "CustomLogFormatter.h"
@implementation CustomLogFormatter {
NSDateFormatter *threadUnsafeDateFormatter;
NSRegularExpression *_regex;
}
- (instancetype)init {
self = [super init];
if (self) {
threadUnsafeDateFormatter = [[NSDateFormatter alloc] init];
[threadUnsafeDateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[threadUnsafeDateFormatter setDateFormat:@"HH:mm:ss:SSS"];
_regex = [NSRegularExpression regularExpressionWithPattern:@".?\\[.+? (.+?)\\]"
options:NSRegularExpressionCaseInsensitive
error:nil];
}
return self;
}
- (NSString *)formatLogMessage:(DDLogMessage *)logMessage {
NSString *fileName = [logMessage->_file lastPathComponent];
NSString *level;
switch (logMessage->_level) {
case DDLogLevelError:
level = @"E:";
break;
case DDLogLevelWarning:
level = @"W:";
break;
case DDLogLevelInfo:
level = @"I:";
break;
case DDLogLevelDebug:
level = @"D:";
break;
case DDLogLevelVerbose:
level = @"V:";
break;
default:
level = @"";
}
NSString *function = logMessage->_function;
NSArray *array = [_regex matchesInString:function options:0 range:NSMakeRange(0, function.length)];
if (array.count==1) {
NSTextCheckingResult *res = array[0];
if (res.numberOfRanges>1) {
function = [function substringWithRange:[res rangeAtIndex:1]];
}
}
return [NSString stringWithFormat:@"%@ %@ %@:%d %@ | %@",
[threadUnsafeDateFormatter stringFromDate:(logMessage->_timestamp)],
level,
fileName,
logMessage->_line,
function,
logMessage->_message];
}
@end
// E.g. in your applicationDidFinishLaunching...
DDTTYLogger *logger = [DDTTYLogger sharedInstance];
logger.logFormatter = [[CustomLogFormatter alloc] init];
[DDLog addLogger:logger];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment