Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to use OSLog and OSLogStore in Swift #970

Open
onmyway133 opened this issue Feb 8, 2024 · 0 comments
Open

How to use OSLog and OSLogStore in Swift #970

onmyway133 opened this issue Feb 8, 2024 · 0 comments
Labels

Comments

@onmyway133
Copy link
Owner

onmyway133 commented Feb 8, 2024

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"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant