42 lines
1.7 KiB
Swift
42 lines
1.7 KiB
Swift
import Foundation
|
|
import os
|
|
|
|
public enum LogLevel: String, Sendable, Comparable {
|
|
case debug, info, warn, error
|
|
|
|
private var rank: Int { [.debug: 0, .info: 1, .warn: 2, .error: 3][self] ?? 0 }
|
|
public static func < (lhs: LogLevel, rhs: LogLevel) -> Bool { lhs.rank < rhs.rank }
|
|
}
|
|
|
|
/// A destination besides the unified log, such as `FileLogger`.
|
|
public protocol LogSink: Sendable {
|
|
func write(level: LogLevel, scope: String, message: String)
|
|
}
|
|
|
|
public enum Log {
|
|
private static let logger = Logger(subsystem: "nl.blijnder.helder", category: "app")
|
|
private static let sinkBox = OSAllocatedUnfairLock<LogSink?>(initialState: nil)
|
|
|
|
/// Installs the extra sink; nil removes it.
|
|
public static func setSink(_ sink: LogSink?) {
|
|
sinkBox.withLock { $0 = sink }
|
|
}
|
|
|
|
public static func debug(_ scope: String, _ message: String) { write(.debug, scope, message) }
|
|
public static func info(_ scope: String, _ message: String) { write(.info, scope, message) }
|
|
public static func warn(_ scope: String, _ message: String) { write(.warn, scope, message) }
|
|
public static func error(_ scope: String, _ message: String) { write(.error, scope, message) }
|
|
|
|
private static func write(_ level: LogLevel, _ scope: String, _ message: String) {
|
|
let line = "[\(scope)] \(message)"
|
|
switch level {
|
|
case .debug: logger.debug("\(line, privacy: .public)")
|
|
// Notice, not info: the unified log only persists notice and above.
|
|
case .info: logger.notice("\(line, privacy: .public)")
|
|
case .warn: logger.warning("\(line, privacy: .public)")
|
|
case .error: logger.error("\(line, privacy: .public)")
|
|
}
|
|
sinkBox.withLock { $0 }?.write(level: level, scope: scope, message: message)
|
|
}
|
|
}
|