Created
November 29, 2020 16:12
-
-
Save gavrilaf/325fa8d605026066cd6eee7fc656bc12 to your computer and use it in GitHub Desktop.
Revisions
-
gavrilaf created this gist
Nov 29, 2020 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,80 @@ import Foundation import os.log // MARK:- protocol LogHandler { func debug(_ msg: String, _ params: [String: Any]) func info(_ msg: String, _ params: [String: Any]) func error(_ msg: String, _ params: [String: Any]) func fatal(_ msg: String, _ params: [String: Any]) } // MARK:- struct Log { enum P { static let err = "error" static let fn = "fn" static let task = "task" static let latency = "latency" } static func error(_ msg: String, _ err: Error, _ params: [String: Any] = [:], _ fn: String = #function) { let newParams = [P.err: err, P.fn: fn].merging(params) { (p, _) in p } handler.error(msg, newParams) } static func debug(_ msg: String, _ params: [String: Any]) { handler.debug(msg, params) } static func info(_ msg: String, _ params: [String: Any]) { handler.info(msg, params) } static func fatal(_ msg: String, _ params: [String: Any]) { handler.fatal(msg, params) } // MARK: - static let app = Bundle.main.bundleIdentifier! static var handler = DefaultLogHandler(OSLog(subsystem: app, category: "app")) } // MARK:- final class DefaultLogHandler: LogHandler { init(_ log: OSLog) { self.log = log } func debug(_ msg: String, _ params: [String: Any]) { let s = format(msg: msg, with: params) os_log("%@", log: log, type: .debug, s) } func info(_ msg: String, _ params: [String: Any]) { let s = format(msg: msg, with: params) os_log("%@", log: log, type: .info, s) } func error(_ msg: String, _ params: [String: Any]) { let s = format(msg: msg, with: params) os_log("%@", log: log, type: .error, s) } func fatal(_ msg: String, _ params: [String: Any]) { let s = format(msg: msg, with: params) os_log("fatal: %@", log: log, type: .error, s) fatalError(s) } // MARK:- private func format(msg: String, with params: [String: Any]) -> String { return params.isEmpty ? msg : "\(msg); \(params)" } private let log: OSLog }