如何手动删除 Cocoalumberjack 日志

How to manually remove Cocoalumberjack log

我正在使用 CocoaLumberjack V2.4 将日志保存到文件中。

这是设置保存日志到文件的默认代码:

    DDFileLogger *fileLogger = [[DDFileLogger alloc] init]; // File Logger
    fileLogger.rollingFrequency = 60 * 60 * 24; // 24 hour rolling
    fileLogger.logFileManager.maximumNumberOfLogFiles = 7;
    [DDLog addLogger:fileLogger];

日志保存在默认位置:/AppData/Library/Caches/Logs/

我想实现一个 API 来手动删除保存的日志。我检查他们有 Manually clear logs 作为未解决的问题。有人有建议吗?

这应该适合你:

[fileLogger rollLogFileWithCompletionBlock: ^{
    for (NSString *filename in fileLogger.logFileManager.sortedLogFilePaths) {
    [[NSFileManager defaultManager] removeItemAtPath:filename error:nil];
    }
}];

Swift 答案:

 fileLogger.rollLogFile(withCompletion: {
            for filename: String in self.fileLogger.logFileManager.sortedLogFilePaths {
                do {
                    try FileManager.default.removeItem(atPath: filename)
                } catch {
                    print(error.localizedDescription)
                }
            }
        })

在 Swift 试试这个。

func clearLogs(){
    let logHelper = LogHelper(subsystem: "Logs", category: "Clear")

    logHelper.i("Clearing logs...")

    for logger in DDLog.allLoggers {
        if let fileLogger = logger as? DDFileLogger {
            fileLogger.rollLogFile{
                for path in fileLogger.logFileManager.sortedLogFilePaths {
                    let fileURL = URL(fileURLWithPath: path)

                    logHelper.i("\(fileURL)")
                    do {
                        try FileManager.default.removeItem(at: fileURL)
                        logHelper.i("Done!")
                    }
                    catch {
                        logHelper.e(error.localizedDescription)
                    }
                }
            }
        }
    }
}