Use OSLog to replace print in swift [MacOS App]

Estimated read time 2 min read

OSLogIt is a new framework introduced by Apple in macOS 10.15 (Catalina) and iOS 15 for recording system logs. It provides a modern way to log applications and integrates very well with the syslog service.

There are 2 common patterns used in SwiftUI applications:

Property Wrapper

import os.log

@propertyWrapper
struct AppLog {
    private let logger: Logger
    
    init(subsystem: String = "com.example.MyApp", category: String = "defaultCategory") {
        self.logger = Logger(subsystem: subsystem, category: category)
    }
    
    var wrappedValue: Logger {
        return logger
    }
}


struct MyViewModel {
    @AppLog(subsystem: "com.example.MyApp", category: "MyCategory")
    private var logger
    
    func doSomething() {
        // 记录日志消息
        logger.log("This is a log message")
    }
}


environment variables

//  applogger.swift
import Foundation
import SwiftUI
import os.log


private struct LoggerEnvironmentKey: EnvironmentKey {
    static let defaultValue: Logger = Logger(subsystem: subsystem, category: "main")
}

extension EnvironmentValues {
    var logger : Logger {
        get { self[LoggerEnvironmentKey.self] }
        set { self[LoggerEnvironmentKey.self] = newValue }
    }
}

// App.swift
 Settings {
            SettingsView()
        }
        .environment(\.logger, logger)


// someView.swift

import SwiftUI
import os.log
struct ContentView: View {
    @Environment(\.logger) private var logger: Logger // 访问共享日志器

    var body: some View {
        Text("Hello, World!")
            .onAppear {
                logger.info("ContentView appeared")
            }
    }
}

Summarize

Both methods are very convenient, but the first one is recommended. The first one does not need to introduce OSLog every time. You can set the default value and use parameters to distinguish it when you need to distinguish it.

You May Also Like

More From Author

+ There are no comments

Add yours