With iOS unified logging, why should an app write diagnostics with Logger(subsystem:category:) instead of print, and what do subsystem and category add?
answer
- structured entries, not stdout text
- who wrote it, how serious
- reverse-DNS subsystem, per-feature category
- dynamic strings hidden by default
- Logger arrived in iOS 14
basics
~20 sLogger writes each message into the unified logging system with a level, a subsystem and a category, so it can be filtered, kept by severity and redacted for privacy. print emits plain text with none of that.
solid answer
~40 s`print` writes plain text to standard output: no level, no owner, no redaction, nothing support can filter later. `Logger`, in the `os` module since iOS 14, records each message in the unified logging system, which keeps it in memory and, depending on the level, in an on-disk store you read later with Console or the `log` tool. `Logger(subsystem:category:)` tags every line: the subsystem names the app or a large area in reverse-DNS form (usually the bundle ID), the category names a feature such as `dock-checkin`, and both become filters. You pick a level per call (`debug`, `info`, `notice`, `error`, `fault`), and interpolated dynamic strings are redacted unless you mark them `.public`. Declare loggers once as static constants.
code
swift · 13 linesimport os
extension Logger {
private static let subsystem = "com.example.boatrental"
static let dockCheckIn = Logger(subsystem: subsystem, category: "dock-checkin")
static let bluetooth = Logger(subsystem: subsystem, category: "bluetooth")
}
func startCheckIn(dockNumber: Int, boatName: String) {
Logger.dockCheckIn.notice("Check-in started at dock \(dockNumber)")
Logger.dockCheckIn.info("Boat \(boatName, privacy: .public) selected")
Logger.bluetooth.debug("Scanning for the dock lock")
}go deeper
Recall that Logger takes a subsystem and a category, that you choose a level by the method you call, and that print has none of this.
Explain how subsystem and category become filters in Console and the log tool, and why loggers are declared once as static constants.
Show you have read field logs: lines without a subsystem are unfindable, one giant category is noise, and dynamic strings arrive redacted.
Frame logger setup as the start of a team convention: who owns the category list, and how print is kept out of shipping code.
## What `print` gives you, and what it does not `print` writes a line of plain text to the process's standard output. It is handy while the debugger is attached, but the line carries nothing else: no **level** saying how serious it is, no **subsystem** or **category** naming which part of the app wrote it, and no **privacy** handling for the values inside it. A support engineer cannot later ask for "only the dock check-in lines at error level", because `print` never recorded those facts. ## What `Logger` records `Logger` is a struct in Apple's `os` module, available from iOS 14. It writes into the **unified logging system**, which keeps log data in memory and in an on-disk store instead of a text file. Every message carries: - a **level**, chosen by the method you call: `debug`, `info`, `notice`, `error` or `fault`; - the logger's **subsystem** and **category**; - the message text, where each interpolated value has a **privacy** option (dynamic strings are redacted by default); - metadata the system adds itself, such as the timestamp, process and thread. The store is binary and compressed, so you read it with tools: the Console app, the `log` command-line tool on a Mac, Xcode's debug console, or the OSLog framework from code. ## Subsystem and category `Logger(subsystem:category:)` stamps both strings on every message the logger writes. - **Subsystem**: a large functional area in reverse-DNS form. Apple's `Logger` documentation says you typically use the app's bundle ID, for example `com.example.boatrental`. - **Category**: a component inside that subsystem, such as `dock-checkin`, `bluetooth` or `payments`. Any naming scheme works; consistency is what makes it useful. Both become filters. With the `log` tool, a predicate such as `subsystem == "com.example.boatrental" && category == "bluetooth"` keeps one feature's lines and drops thousands of system messages; the `log` man page advises giving the subsystem whenever you filter by category. | | `print` | `Logger` | |---|---|---| | Severity | none | debug, info, notice, error, fault | | Owner tags | none | subsystem and category | | Privacy | value printed as-is | dynamic strings redacted unless marked | | Later reading | unstructured text only | Console, `log`, OSLogStore, filterable | ## Create loggers once The log objects behind a logger are kept per subsystem and category pair, and Apple's `os_log` header says they are never deallocated, so creating them per operation is inappropriate. Declare loggers once as static constants, usually in one extension: ```swift import os extension Logger { private static let subsystem = "com.example.boatrental" static let dockCheckIn = Logger(subsystem: subsystem, category: "dock-checkin") static let bluetooth = Logger(subsystem: subsystem, category: "bluetooth") } func startCheckIn(dockNumber: Int, boatName: String) { Logger.dockCheckIn.notice("Check-in started at dock \(dockNumber)") Logger.dockCheckIn.info("Boat \(boatName, privacy: .public) selected") Logger.bluetooth.debug("Scanning for the dock lock") } ``` `Logger` conforms to `Sendable`, so a `static let` can be used from any thread or task. ## Common mistakes 1. **Passing a `String` variable as the whole message.** `logger.error(message)` does not compile: the methods take an `OSLogMessage`, which the compiler builds from a string literal and its interpolations. Write `logger.error("Unlock failed: \(message)")` instead. 2. **Calling `Logger()` everywhere.** The no-argument initializer writes to the default subsystem, so your lines carry nothing of yours to filter on. 3. **One category for the whole app.** A filter then returns everything or nothing. 4. **Marking every value `.public` to "see it".** That switches off redaction for user data; choose privacy value by value. ## Reading the lines back Writing well-tagged lines pays off when someone reads them: - In the **Console app**, search on the subsystem or category to narrow the messages, including those in a collected archive, to one feature. - On a Mac, `log stream --predicate 'subsystem == "com.example.boatrental"'` follows matching lines live on that Mac, and `log collect --device` pulls a connected iPhone's logs into an archive for later. - Inside the app, the OSLog framework's `OSLogStore` (iOS 15) reads back the current process's own entries. `print` output carries no subsystem, category or level for any of these filters to match. ## Before iOS 14 Older code calls the C-level `os_log` functions with an `OSLog` object made by `OSLog(subsystem:category:)`. `Logger(_:)` wraps such an object, so old and new code can write to the same subsystem and category during a migration.
- Why does logger.error(message) fail to compile when message is a String variable?Logger's methods take an `OSLogMessage`, which the compiler builds from a string literal and its interpolations; a `String` value does not convert to it. Write `logger.error("Unlock failed: \(message)")` so the static text stays fixed and the dynamic part becomes an interpolated argument with its own privacy option.
- What happens if you create the logger with Logger() and no arguments?It writes to the default subsystem. The messages still reach the unified log, but with no subsystem or category of yours, so a predicate cannot separate them from everything else the process and the system log. Fine for a quick experiment; production code should name both.
- How did apps log before Logger existed, and can the two styles share a log?They called the C-level `os_log` functions with an `OSLog` object created by `OSLog(subsystem:category:)`, using format specifiers such as `%{public}@` for privacy. `Logger(_:)` wraps an existing `OSLog`, so new Swift code and older code can write to the same subsystem and category.
- print lines carry a level and category you can filter on later
- Creating a new Logger inside every function call is the recommended pattern
- One category for the whole app loses nothing when filtering
- Logger shows every interpolated string in plain text by default
- Writing to the device log needs a third-party logging library