New App - OSLog Console Logger

Leveraging OSLog in your console

An updated version of the original console log post, this time, using Apple’s OSLog instead of a custom enum.

Table Of Contents:

OSLog

OSLog is Apple’s unified logging system. It’s really simple to use, and it allows a lot of customization in the console.

It’s fast and you don’t need to worry about not logging in Release mode.

Logger as Dependency

Using the approach from the Centralized Dependencies post, we can add the Logger to the World struct:

import OSLog

struct World {
    // ...
    var logger: Logger { Logger(subsystem: "your.app.bundleId", category: "PackageName") }
}

Usage

Then, we can just use it from anywhere in our package:

Current.logger.debug("Something to debug")

Levels

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack {
            Button("Debug") { Current.logger.debug("Debug") }
            Button("Info") { Current.logger.info("Info") }
            Button("Notice") { Current.logger.notice("Notice") }
            Button("Error") { Current.logger.error("Error") }
            Button("Critical") { Current.logger.critical("Critical") }
        }
        .padding()
    }
}

In the Console

In Xcode’s console, you can adjust the metadata you want to see in the logs:

metadata

logs

You can also go directly to the line of code that produced the log:

jump-to-line

The filters are also great:

filters

Privacy

In release mode, all interpolated strings will be hidden by default. You can override this using the privacy parameter:

Current.logger.debug("Debug: \(userId, privacy: .public)")

I think it’s a pretty straight forward way to log information to the console. It’s really useful if you have multiple packages to filter the logs of just a small subset of modules.


Related Articles

New App - OSLog Console Logger | manu.show
Tags: iOS
Share: X (Twitter) LinkedIn