4

我在我的项目中使用 CocoaLumberjack。我需要将日志文件的名称更改为我的自定义文件名。

NSString * applicationDocumentsDirectory = [[[[NSFileManager defaultManager]
                                              URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject] path];
DDLogFileManagerDefault *documentsFileManager = [[DDLogFileManagerDefault alloc]
                                                 initWithLogsDirectory:applicationDocumentsDirectory];

DDFileLogger *fileLogger = [[DDFileLogger alloc]
                            initWithLogFileManager:documentsFileManager];    
// Configure File Logger
[fileLogger setMaximumFileSize:(1024 * 1024)];
[fileLogger setRollingFrequency:(3600.0 * 24.0)];
[[fileLogger logFileManager] setMaximumNumberOfLogFiles:1];
[DDLog addLogger:fileLogger];

通过上面的代码,我已将目录更改为 Documents。但现在我也需要更改日志文件名。我怎样才能做到这一点?可能吗?

4

2 回答 2

6

虽然我认为我的回复可能为时已晚,但请在下面找到我的解决方案:

1) 继承 DDLogFileManagerDefault 并覆盖方法:newLogFileName 和 isLogFile

#import "DDFileLogger.h"

@interface BaseLogFileManager : DDLogFileManagerDefault

@end

#import "BaseLogFileManager.h"

@implementation BaseLogFileManager

-(NSString *)newLogFileName {
    NSString *appName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleIdentifier"];
    NSString *timeStamp = [self getTimestamp];

    return [NSString stringWithFormat:@"%@%@.log", appName, timeStamp];
}

-(BOOL)isLogFile:(NSString *)fileName {
    return NO;
}

-(NSString *)getTimestamp {
    static dispatch_once_t onceToken;
    static NSDateFormatter *dateFormatter;
    dispatch_once(&onceToken, ^{
        dateFormatter = [NSDateFormatter new];
        [dateFormatter setDateFormat:@"YYYY.MM.dd-HH.mm.ss"];
    });

    return [dateFormatter stringFromDate:NSDate.date];
}

@end

2) 在 AppDelegate 中,更改以下行:

DDLogFileManagerDefault *documentsFileManager = [[DDLogFileManagerDefault alloc] initWithLogsDirectory:applicationDocumentsDirectory];

至:

DDLogFileManagerDefault *documentsFileManager = [[BaseLogFileManager alloc] initWithLogsDirectory:applicationDocumentsDirectory];
于 2014-08-26T18:02:14.923 回答
0

newLogFileName 和 isLogFile 方法可用于实现任务

于 2017-01-10T18:20:50.927 回答