How to disable os_log debug messages, for certain categories or subsystems?

Viewed 544

I'm using the unified logging API in my iOS app.

import os
private let log = OSLog(subsystem: "", category: "ThisComponent")
...
os_log(.debug, log:log, "Blah blah blah: %@", str)

Those debug log calls show up in the Xcode console when running my app. Once I'm no longer focused on a particular component, I don't want to see its flood of debug level log messages. Is there a way to disable them with an environment variable or something like that? Or do I need to change the code by either commenting them out, or defining my own Bool vars and adding if checks:

if isDebugLogging {
    os_log(.debug, log:log, ...)
}

The docs mention being able to do this for macOS, but I'm specifically asking about iOS.

I don't want to shut it all off. For this to be useful I need a way to shut it off by subsystem or category.

1 Answers

You are applying os_log by specifying some global OSLog object. Just replace that object by OSLog.disabled, and now messages sent through it won't go anywhere.

Example:

let _activeLog = OSLog(subsystem: "hey", category: "ho")
let _inactiveLog = OSLog.disabled
var heyHoEnabled = true
var myLog : OSLog { heyHoEnabled ? _activeLog : _inactiveLog }

So now:

    os_log(.debug, log: myLog, "hey") // logged
    os_log(.debug, log: myLog, "ho") // logged
    self.heyHoEnabled = false
    os_log(.debug, log: myLog, "hey nonny no") // not logged

But let's say you still want to send the messages; you just don't to see them. There is no way to say, at the console level, "do not show me certain messages". You can filter the console, but only by what you want, not what you don't want.

By the way, the fact that os_log messages go into the Xcode console is a secondary feature. The primary place they appear is the Console application. And the Console messages can be filtered so as to include only the subsystems or categories you want. This is a very powerful filter, much more powerful and precise than the Xcode console.

So if all of your console messages are os_log messages, with different subsystems or categories, then you can use the Console application to filter in very powerful ways.

Related