OSLog

OSLog

920 发布: 2025/1/8 17:02 本文总阅读量

OSLog

使用示例

debug.log("===>111", ["id": 1, "name": "xiaoming"], ["id": 2, "name": "xiaoli"], type: .error)
debug.log("===>222", ["id": 111, "name": "xiaoli"], type: .debug)
debug.log("===>333", ["id": 222, "name": "xiaoli"])
debug.log("===>555\(["id": 222, "name": "xiaoli"])")
debug.log("===>666", [10, 9, 8, 7, 6])
debug.log("===>777", JSON([10, 9, 8, 7, 6]))

源码

import os.log
import OSLog
import SwiftyJSON

class debug {
    /// 单例
    static let shared: Logger = {
        // 先定义instance为可选类型
        var instance: Logger?
        let queue = DispatchQueue(label: "com.oslog.singleton")
        queue.sync {
            // 在闭包内安全地初始化instance
            instance = Logger(subsystem: Bundle.main.bundleIdentifier ?? "", category: "custom-os-log")
        }
        // 使用可选绑定确保instance有值后再返回,如果没有值会触发运行时错误,不过在正常逻辑下不会出现这种情况,因为闭包内会进行初始化
        guard let unwrappedInstance = instance else {
            fatalError("Singleton instance not initialized")
        }
        return unwrappedInstance
    }()

    /// 日志输出
    /// - Parameters:
    ///   - items: 约定:当items只有一个对象时默认是打印数据,超过一个对象时默认第一个对象时标识符
    ///     items -> Examples
    /// ========
    ///     debug.log([1, 2, 3, 4, 5])
    ///     debug.log("===>flag", ["id": 1, "name": "xiaoming"], ["id": 2, "name": "xiaoli"], type: .debug)
    /// ========
    ///   - type: 类型,参考 OutputType
    ///   - file: 用于输出文件名称
    ///   - line: 用于输出代码行号
    static func log(_ items: Any..., type: OSLogType = .debug, file: String = #file, line: Int = #line) {
        //
        let dateFormate = DateFormatter()
        dateFormate.dateFormat = "yy-MM-dd HH:mm:ss.SSS"
        let curT = Date()
        let stringOfDate = dateFormate.string(from: curT)
        //
        var fileName = (file as NSString).lastPathComponent
        fileName = fileName.replacingOccurrences(of: ".swift", with: "")
        //
        var logStr = "\(stringOfDate) \(fileName)【line:\(line)】"
        let separator = "\n"
        var raws = items
        if items.count > 1 {
            let first = "\(JSON(items[0]))"
            logStr += first
            logStr += separator
            raws = Array(items.dropFirst())
        } else {
            logStr += separator
        }
        logStr += raws.map { "\(JSON($0))" }.joined(separator: separator)
        shared.log(level: type, "\(logStr)")
    }
}