CocoaLumberjack FileLogger记录到多个文件

jun*_*orb 8 logging objective-c lumberjack

我正在使用这个CocoaLumberjack框架来记录Objective-C设计中的所有消息.现在我想将所有错误记录到一个文件,将所有其他消息记录到另一个文件.我知道我可以使用格式化程序来过滤这些信息.我在AppDelegate中创建了两个DDFileLogger实例,但是这两个记录器一直写入同一个文件.我想知道是否有一种方法可以指定日志记录目的地,以便两个记录器写入两个不同的文件.

Kab*_*dam 7

实现这一目标的关键是使用自己的DDLogFileManager设置每个DDFileLogger,每个DDFFileManager都有单独的日志目录路径.DDLogFileManager使用日志目录路径来确定要记录到哪个文件,因此如果您有两个指向同一目录,它们将记录到同一个日志文件.所以关键是为每个日志使用单独的目录.

对于两种不同的日志类型:"一个"和"两个":

// Set the base log directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *baseDir = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
NSString *logsDirectory = [baseDir stringByAppendingPathComponent:@"Logs"];

// set up file logger One to log to subdirectory "One"
DDLogFileManagerDefault *fileManagerOne = [[DDLogFileManagerDefault alloc] initWithLogsDirectory:[logsDirectory stringByAppendingPathComponent:@"One"]];
DDFileLogger *loggerOne = [[DDFileLogger alloc] fileManagerOne];

// Use the filter formatter to make sure only "One" logs go to the "One" log files
ContextWhitelistFilterLogFormatter *formatterOne = [[ContextWhitelistFilterLogFormatter alloc] init];
[formatterOne addToWhitelist:LOG_CONTEXT_ONE];
[loggerOne formatterOne];

[DDLog loggerOne];

    // set up file logger Two to log to subdirectory "Two"
DDLogFileManagerDefault *fileManagerTwo = [[DDLogFileManagerDefault alloc] initWithLogsDirectory:[logsDirectory stringByAppendingPathComponent:@"Two"]];
DDFileLogger *loggerTwo = [[DDFileLogger alloc] fileManagerTwo];

// Use the filter formatter to make sure only "Two" logs go to the "Two" log files
ContextWhitelistFilterLogFormatter *formatterTwo = [[ContextWhitelistFilterLogFormatter alloc] init];
[formatterTwo addToWhitelist:LOG_CONTEXT_TWO];
[loggerTwo formatterTwo];

[DDLog loggerTwo];
Run Code Online (Sandbox Code Playgroud)

那么你当然还需要定义宏来进行日志记录:

#define LOG_CONTEXT_ONE    1
#define LOG_CONTEXT_TWO    2

#define LogOne(frmt, ...) SYNC_LOG_OBJC_MACRO(0, 0, LOG_CONTEXT_ONE, frmt, ##__VA_ARGS__)
#define LogTwo(frmt, ...) SYNC_LOG_OBJC_MACRO(0, 0, LOG_CONTEXT_TWO, frmt, ##__VA_ARGS__)
Run Code Online (Sandbox Code Playgroud)

这对我有用.