onmyway133 / blog

🍁 What you don't know is what you haven't learned
https://onmyway133.com/
MIT License
679 stars 33 forks source link

How to use OSLog and OSLogStore in Swift #970

Open onmyway133 opened 9 months ago

onmyway133 commented 9 months ago

We can use Logger to log and OSLogStore to retrieve logs

import OSLog
import ReuseAcross

final class LogService {
    static let shared = LogService()

    let logger = Logger(
        subsystem: "com.example.myapp",
        category: "Log"
    )

    func export() -> [String] {
        do {
            let store = try OSLogStore(scope: .currentProcessIdentifier)
            let position = store.position(timeIntervalSinceLatestBoot: 1)
            let logs = try store
                .getEntries(at: position)
                .compactMap { $0 as? OSLogEntryLog }
                .filter { $0.subsystem == Bundle.main.bundleIdentifier! }
                .map { "[\($0.date.formatted())] [\($0.category)] \($0.composedMessage)" }

            return logs
        } catch {
            return []
        }
    }
}

Then we call like

LogService.shared.logger.log("a message")

let logs = LogService.shared.export() // ["[8/2/2024, 10:45] [Log] a message"]