usage-official-swift-log

2 minute read Published: 2020-01-06

Apple의 official swift-log package를 이용하여 os unified logging를 사용하는 방법

Configuration

swift-log의 oslog backend 패키지를 Package.swift에 추가

dependencies: [
        .package(url: "https://github.com/chrisaljoudi/swift-log-oslog.git", from: "0.2.1")
    ],
targets: [
    .target(
        name: "VExtensionUtility",
        dependencies: [
            "LoggingOSLog"
        ]
    ),

generate Log class

//
//  Log.swift
//
//  Created by kwanghyun.won` on 2020/01/06.
//

import Logging
import LoggingOSLog

/// Example:
///     Log.setup(subsystem: "com.Vingle.DesignKitDemo", level: .debug)
///     Log.info("setup Log Complete!")
public final class Log {

    public static var `default`: Logger = Logger(label: "com.Vingle.app", factory: LoggingOSLog.init)

    public class func setup(subsystem: String, level: Logger.Level = .debug) {
        self.default = Logger(label: subsystem, factory: LoggingOSLog.init)
        self.default.logLevel = level
    }
}

public extension Log {
    static func trace(_ message: Logger.Message, functionName: String = #function, fileName: String = #file) {
        let className = fileName.extractClassName()
        self.default.trace("\(className):\(functionName) \(message)")
    }

    static func debug(_ message: Logger.Message, functionName: String = #function, fileName: String = #file) {
        let className = fileName.extractClassName()
        self.default.debug("\(className):\(functionName) \(message)")
    }

    static func info(_ message: Logger.Message, functionName: String = #function, fileName: String = #file) {
        let className = fileName.extractClassName()
        self.default.info("\(className):\(functionName) \(message)")
    }

    static func notice(_ message: Logger.Message, functionName: String = #function, fileName: String = #file) {
        let className = fileName.extractClassName()
        self.default.notice("\(className):\(functionName) \(message)")
    }

    static func warning(_ message: Logger.Message, functionName: String = #function, fileName: String = #file) {
        let className = fileName.extractClassName()
        self.default.warning("\(className):\(functionName) \(message)")
    }

    static func error(_ message: Logger.Message, functionName: String = #function, fileName: String = #file) {
        let className = fileName.extractClassName()
        self.default.error("\(className):\(functionName) \(message)")
    }

    static func critical(_ message: Logger.Message, functionName: String = #function, fileName: String = #file) {
        let className = fileName.extractClassName()
        self.default.critical("\(className):\(functionName) \(message)")
    }
}

usage

Log.setup(subsystem: "com.Vingle.DesignKitDemo", level: .debug)

Log.debug(" debug message (variable)")