此discussion中提供了另一種解決方案。它目前適用於我,我正在試驗它。
你必須定義
var logPrefix = ""
var logLevel = DDLogLevel.Debug
採用UnitDDLoggable
它允許一個簡單的寫:
DDLogWarn("Danger, Will Robinson"
爲SWIFT 2.3的代碼:
import CocoaLumberjackSwift
/// Base protocol for unit specific logging. Generally you won't implement this protocol directly, you will
/// implement one of the protocols that inherit from it
protocol UnitLoggable {
/// Prefix to append to each log line, should include a trailing space to separate it from the log message
var logPrefix:String { get }
}
/// Implment this protocol to use CocoaLumberjack logging with the level controlable at the file level
protocol UnitDDLoggable : UnitLoggable {
/// Lumberjack log level to use for this code unit, Lumberjack log calls in this unit will use this level
/// not the default log level, to use the shared lumberjack level this property should return defaultDebugLevel
var logLevel:DDLogLevel { get }
}
extension UnitDDLoggable {
final func DDLogDebug(@autoclosure logText:() -> String, context: Int = 0, file: StaticString = #file, function: StaticString = #function, line: UInt = #line, tag: AnyObject? = nil, asynchronous async: Bool = true) {
SwiftLogMacro(async, level: logLevel, flag: .Debug, context: context, file: file, function: function, line: line, tag: tag, string: logPrefix + logText())
}
final func DDLogInfo(@autoclosure logText:() -> String, context: Int = 0, file: StaticString = #file, function: StaticString = #function, line: UInt = #line, tag: AnyObject? = nil, asynchronous async: Bool = true) {
SwiftLogMacro(async, level: logLevel, flag: .Info, context: context, file: file, function: function, line: line, tag: tag, string: logPrefix + logText())
}
final func DDLogWarn(@autoclosure logText:() -> String, context: Int = 0, file: StaticString = #file, function: StaticString = #function, line: UInt = #line, tag: AnyObject? = nil, asynchronous async: Bool = true) {
SwiftLogMacro(async, level: logLevel, flag: .Warning, context: context, file: file, function: function, line: line, tag: tag, string: logPrefix + logText())
}
final func DDLogVerbose(@autoclosure logText:() -> String, context: Int = 0, file: StaticString = #file, function: StaticString = #function, line: UInt = #line, tag: AnyObject? = nil, asynchronous async: Bool = true) {
SwiftLogMacro(async, level: logLevel, flag: .Verbose, context: context, file: file, function: function, line: line, tag: tag, string: logPrefix + logText())
}
final func DDLogError(@autoclosure logText:() -> String,context: Int = 0, file: StaticString = #file, function: StaticString = #function, line: UInt = #line, tag: AnyObject? = nil, asynchronous async: Bool = false) {
SwiftLogMacro(async, level: logLevel, flag: .Error, context: context, file: file, function: function, line: line, tag: tag, string: logPrefix + logText())
}
}