Apple文档说,它提供了一种在子系统下定义类别的方法,用于过滤特定于该类别的日志(https://developer.apple.com/documentation/os/1643744-os_log_create?language=objc(。我查找了可可伐木工人库,但似乎没有办法创建子类别。我们可以使用任何替代方案与可可伐木工人库来实现相同的目标吗?
可以添加 Cocoa Lumberjack os_log中使用的类别和子系统。您可以添加子系统和类别,如以下示例所示:
/// Initialization
for category in LoggerCategory.allCases {
let logger = DDOSLogger.init(subsystem: "com.yourname", category: category.rawValue)
logger.logFormatter = CustomLoggingFormatter(category: category)
DDLog.add(logger)
}
enum LoggerCategory: String, CaseIterable {
case test
var index: Int {
return Self.allCases.firstIndex(of: self)!
}
}
/// Custom logging formatter that filters messages by the category that is provided in the context
class CustomLoggingFormatter: NSObject, DDLogFormatter {
let category: LoggerCategory
/// Intializer for custom logger that filters out messages with the provided category
/// - Parameter category: Category that will be filtered (shown for provided category)
init(category: LoggerCategory) {
self.category = category
}
func format(message logMessage: DDLogMessage) -> String? {
guard logMessage.context == category.index else { return nil }
return "(logMessage.message)"
}
}
// Usage:
DDLogWarn("Your message", context: 1) // context for filter
// Output in console
2020-12-16 16:44:17.899062+0100 App[1234:1234] [test] Your message
源,请参阅合并请求和讨论