Created
September 20, 2016 14:31
-
-
Save colourful987/17535ecdfda598bd37005684f356601c to your computer and use it in GitHub Desktop.
OPP - Logger
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 面向协议的日志输出 | |
enum LogLevel: Int { | |
case verbose = 1 | |
case debug = 2 | |
case info = 3 | |
case warning = 4 | |
case error = 5 | |
} | |
extension LogLevel: Comparable {} | |
func <(lhs: LogLevel, rhs: LogLevel) -> Bool { | |
return lhs.rawValue < rhs.rawValue | |
} | |
protocol Logger { | |
/// 打印一条日志 | |
/// 类型必须遵循 Logger 协议的必选参数 | |
/// - 注意:Logger 的调用者永远不应该调用此方法 | |
/// 总是调用 log(_:,_:) 方法 | |
func writeLogEntry( | |
logLevel: LogLevel, | |
message: @autoclosure () -> String, | |
file: StaticString, | |
line: Int, | |
function: StaticString) | |
} | |
extension Logger { | |
/// Logger 协议的公开 API | |
/// 只是调用 writeLogEntry(_:,_:,file:,line:,function:) 方法 | |
func log( | |
logLevel: LogLevel, | |
message: @autoclosure () -> String, | |
file: StaticString = #file, | |
line: Int = #line, | |
function: StaticString = #function) | |
{ | |
writeLogEntry(logLevel: logLevel, message: message, | |
file: file, line: line, | |
function: function) | |
} | |
} | |
struct PrintLogger { | |
let minimumLogLevel: LogLevel | |
} | |
extension PrintLogger: Logger { | |
func writeLogEntry( | |
logLevel: LogLevel, | |
message: @autoclosure () -> String, | |
file: StaticString, | |
line: Int, | |
function: StaticString) | |
{ | |
if logLevel >= minimumLogLevel { | |
print("\(logLevel) – \(file):\(line) – \(function) – \(message())") | |
} | |
} | |
} | |
let logger3: Logger = PrintLogger( | |
minimumLogLevel: .verbose) | |
logger3.log(logLevel: .error, message: "An error occurred") // 撒花🎉 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment