Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Extended logger for swift-log library (https://github.com/apple/swift-log)
//
// LabeledStreamLogHandler.swift
// WishBag
//
// Created by ultraon on 15/12/19.
// Copyright © 2019 ultraon. All rights reserved.
//
import Foundation
import Logging
import Then
let DBG: Bool = true
extension Logger: Then {}
/// Creates an instance of `Logger`.
/// - Parameters:
/// - label: a label will be used to add label/tag into log message.
/// - showLine: if `true` will add a code line number.
///
/// Usage:
/// ```swift
/// private let LOG = logger("")
///
/// struct MyStruct {
/// func myFunc() {
/// LOG.debug("My log message.")
/// }
/// }
/// ```
func logger(_ label: String, _ showLine: Bool = false) -> Logger {
return Logger(label: label, factory: { LabeledStreamLogHandler($0, showLine) }).with {
$0.logLevel = DBG ? .debug : .info
}
}
private struct LabeledStreamLogHandler: LogHandler {
private var delegate: LogHandler
private let label: String
private let showLine: Bool
init(_ label: String, _ delegate: LogHandler, _ showLine: Bool = false) {
self.label = label
self.delegate = delegate
self.showLine = showLine
}
init(_ label: String, _ showLine: Bool = false) {
self.init(label, StreamLogHandler.standardOutput(label: label), showLine)
}
func log(level: Logger.Level, message: Logger.Message, metadata: Logger.Metadata?, file: String, function: String, line: UInt) {
delegate.log(level: level, message: "\(label):\(showLine ? " L-\(line):" : "") \(message)", metadata: metadata, file: file, function: function, line: line)
}
subscript(metadataKey key: String) -> Logger.Metadata.Value? {
get {
return delegate[metadataKey: key]
}
set {
delegate[metadataKey: key] = newValue
}
}
var metadata: Logger.Metadata {
get {
return delegate.metadata
}
set {
delegate.metadata = newValue
}
}
var logLevel: Logger.Level {
get {
return delegate.logLevel
}
set {
delegate.logLevel = newValue
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.