Skip to content

Instantly share code, notes, and snippets.

@gavrilaf
Created November 29, 2020 16:12
Show Gist options
  • Select an option

  • Save gavrilaf/325fa8d605026066cd6eee7fc656bc12 to your computer and use it in GitHub Desktop.

Select an option

Save gavrilaf/325fa8d605026066cd6eee7fc656bc12 to your computer and use it in GitHub Desktop.
Logging for Swift (option 2)
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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment