Swift OSLog、Extension追加、欲しいログ機能にしてみる

以前の記事「Swift SwiftLog、Extension追加、欲しいログ機能にしてみる」のOSLog版。

Extension

コード

import OSLog

extension Logger {
    static var level = OSLogType.info
    
    init(label: String) {
        self.init(subsystem: "", category: label)
    }
    
    func debug(_ message: String = "" , function: String = #function, line: Int = #line) {
        self.log(level: .debug, "[\(function):\(line)] \(message)")
    }

    func info(_ message: String = "" , function: String = #function, line: Int = #line) {
        self.log(level: .info, "[\(function):\(line)] \(message)")
    }
    
    func error(_ message: String = "" , function: String = #function, line: Int = #line) {
        self.log(level: .error, "[\(function):\(line)] \(message)")
    }

    func fault(_ message: String = "" , function: String = #function, line: Int = #line) {
        self.log(level: .fault, "[\(function):\(line)] \(message)")
    }
}

使用例

コード

import UIKit
import OSLog

class MainViewController: UIViewController {
    private let logger = Logger(label: #function)

    override func viewDidLoad() {
        logger.info("start")
        super.viewDidLoad()
    }
:
:
:

出力

2021-01-17 08:04:08.962712+0900 Books[56726:7859172] [MainViewController] [viewDidLoad():21] start

Swift

Posted by shi-n