iOS logging with Logger: Levels, privacy, and reading logs
Contents
Logging in an iOS app comes down to one API: Logger from Apple's os framework, available since iOS 14. Used with a subsystem and category per feature, a deliberate level policy, and explicit privacy markers, it covers most debugging needs on its own.
You need more, such as swift-log or remote collection, only if you ship shared packages or must debug devices you can't touch. If you need extra hands on this kind of work, Netguru's iOS app development team builds native apps in Swift.
iOS logging with Logger: The short answer
Logger from the os framework, available since iOS 14, is the API to use for iOS logging in Swift (Apple: Logger). It writes to the unified logging system, tags every message with a subsystem and category, and redacts interpolated strings in release unless you mark them public.
Four rules cover most apps. Use your bundle identifier as the subsystem and one category per feature. Pick each level for what must persist on the device.
Set privacy explicitly on every interpolated value. Keep print() and NSLog out of shipped code.
Apps that still support iOS 13 need os_log, and server-side Swift code uses apple/swift-log.
For Swift-specific work beyond logging, see our Swift development services.
How do you log with Logger in Swift?
Create one Logger per feature with Logger(subsystem:category:), then call a level method such as info or error with an interpolated message. Define the loggers once as static constants so every call site shares the same subsystem and category. This compiles on iOS 14 and later:
import os
extension Logger {
private static let subsystem = Bundle.main.bundleIdentifier ?? "app"
static let checkout = Logger(subsystem: subsystem, category: "checkout")
}
func finish(orderID: String, total: Double, retries: Int) {
Logger.checkout.info("Order \(orderID, privacy: .public) total \(total, format: .fixed(precision: 2), align: .right(columns: 8))")
Logger.checkout.error("Payment failed, retries \(retries, format: .hex)")
}
The format: argument controls how numbers render, and align: pads values into columns so multi-line output stays readable in Console.app.
Migrating from os_log
The legacy os_log function, introduced in 2016, maps to Logger one to one:
| os_log call | Logger equivalent |
|---|---|
OSLog(subsystem:category:) |
Logger(subsystem:category:) |
os_log(.debug, log: log, ...) |
logger.debug(...) |
os_log(.info, ...) |
logger.info(...) |
os_log(.default, ...) |
logger.notice(...) or logger.log(...) |
os_log(.error, ...) |
logger.error(...) |
os_log(.fault, ...) |
logger.fault(...) |
%.2f and %x |
format: .fixed(precision: 2) and format: .hex |
Why a wrapper breaks attribution
We recommend against wrapping Logger in a custom helper like this:
func log(_ message: String, file: String = #fileID) {
Logger.checkout.info("\(file): \(message)")
}
The unified logging system records where the log call was made, so Console attributes every message to the wrapper's code. The feature that logged disappears from that column. Passing #fileID as a default parameter only puts the file name into the message text, which you then have to read by eye.
The wrapper has a second cost. The message parameter is a String built at runtime, and interpolated strings default to private, so on a device without a debugger attached Console shows <private> where the text should be. Expose the static loggers directly.
Which log level should you use?
Use notice for events you will want after the fact, error for operations that failed, fault for broken invariants, info for supporting context, and debug for development-only detail. Only notice, error, and fault are written to disk by default.
The persistence column is what separates the log levels in practice. Here is each level with a message that fits it:
| Level | Default persistence | Reaches a sysdiagnose | Example message |
|---|---|---|---|
| debug | Not stored unless debug logging is enabled for the subsystem | No, unless enabled beforehand | Cart diff computed, 3 line items changed |
| info | Memory only, not written to disk by default | Not reliably | Checkout view model loaded promo rules |
| notice | Written to disk | Yes | Payment sheet presented |
| error | Written to disk | Yes | Order submission failed, retrying with cached token |
| fault | Written to disk | Yes | Order total negative after discount, state is invalid |
Debug is meant for development only. It should carry everything useful while building and while troubleshooting a specific problem, and it costs very little in release builds, because the system doesn't capture it unless you enable it. Console.app and the Xcode console can show info and debug live, but a tester's sysdiagnose will not contain them.
The practical rule follows from that. If you would want a line in a bug report from a tester's device, log it at notice or above. Keep info for trace-style context that you only need while reproducing.
Reserve fault for states that indicate a bug in your code, such as a violated invariant. A handled network timeout is an error. Logging every failure as fault removes the signal that makes it useful when filtering.
Persistence is also bounded and configurable. The system purges older stored entries as space runs out, and a configuration profile can change what a device keeps (Apple: Generating log messages from your code).
How should you name subsystems and categories?
Use one reverse-DNS subsystem per bundle or module and one category per feature. An app with a payments framework logs under com.acme.app and com.acme.app.payments, with categories such as checkout and refunds. Xcode console filters and Console.app both filter on subsystem and category, so those two fields are your query surface.
import OSLog
extension Logger {
private static let subsystem = Bundle.main.bundleIdentifier ?? "com.acme.app"
static let checkout = Logger(subsystem: subsystem, category: "checkout")
static let onboarding = Logger(subsystem: subsystem, category: "onboarding")
}
Categories multiply when you create one per type (CheckoutViewModel, CheckoutService, CartRepository). Following one user flow then means selecting several categories in Console.app, and every refactor renames them.
In our view, a feature category keeps the whole flow in one filter and survives class renames. Message wording matters as much as naming. Full sentences read well but are hard to filter on specific values. Compare:
- BAD:
user 1234 tapped on the save button on the sign-up view - Better:
tap action=save view=signup
The second form puts a stable key first and key-value pairs after it, so a single search term in Console.app matches every save tap. It also leaves the user identifier out of the message text. If you need an identifier in the log, add it as a separate interpolation with an explicit privacy label.
Why do logs show <private> in release?
Logs show <private> in release because Logger treats interpolated strings and objects as private by default, and the redaction applies whenever no debugger is attached. Numbers and Booleans print in the clear. A String such as an order ID or email does not.
The bug reports as "works in Xcode, useless in TestFlight." With the debugger attached, the Xcode console shows every value, so the redaction only appears once you read logs from a detached device in Console.app, a sysdiagnose, or OSLogStore. The first sign is a log line like Order <private> failed for <private> in a support ticket.
Set the privacy level per interpolation through OSLogPrivacy:
logger.error("Order \(orderID, privacy: .public) failed: \(error.localizedDescription, privacy: .public)")
logger.info("Login for \(email, privacy: .private(mask: .hash))")
The three options behave differently:
| Option | Release output | Use for |
|---|---|---|
| .public | Full value | Error codes, enum names, feature flags, opaque order IDs |
| .private | <private> |
Names, addresses, free text (this is the default for strings) |
.private(mask: .hash) |
Hash of the value | Correlating one user or session across lines without exposing it |
Our rule is to mark a value .public only if you would accept it in a sysdiagnose a customer emails to someone else. Never log tokens, passwords, or Authorization headers at any privacy level. Network interceptors that dump whole headers and bodies are the usual leak.
Treat a hash as pseudonymous, not anonymous. Under the GDPR, pseudonymized data is still personal data (GDPR Recital 26). For development devices, Apple documents a configuration profile that enables private data when you need to see the real values.
Why not print() or NSLog?
print() and NSLog fall short as a logging layer because neither carries a level, a subsystem, a category, or per-value privacy, and Logger from the os framework carries all four. os_log is the older C-style API that Logger wraps, so new Swift code has no reason to call it directly.
The tools side by side:
print() |
NSLog | Logger | |
|---|---|---|---|
| Persistence | None in the unified logging system; visible only in an attached Xcode console | Recorded in the unified logging system | Recorded, with retention set by log level |
| Privacy | None; every value is written in the clear | No per-value control | Per-value OSLogPrivacy markers; interpolated strings redacted in release |
| Filtering | Text search only | Text search only | Subsystem, category, and level in Console.app and Xcode |
| Performance | Synchronous write; string built at the call site | String formatted at the call site | Formatting deferred; compact binary storage |
When each tool is still defensible
- Logger: the default for any code that ships, on iOS 14 and later.
- os_log: the choice for Objective-C files, or when your deployment target is below iOS 14.
print(): acceptable for throwaway output on a local branch, removed before merge.- NSLog: only in legacy code you are not yet touching.
Failure modes and their early signs
print() is synchronous, so a call on the main thread waits for the write to finish. In a scroll handler or a loop over thousands of items, that wait can show up as dropped frames. The early sign is hitches that disappear when the calls are removed.
Logger defers formatting, but the expressions inside an interpolation still run when the call executes. Keep expensive work, such as JSON encoding or String(describing:) on a large model, out of the message. If Time Profiler shows an encoder beneath a log call, that is the cause.
In a tight loop, log one summary per batch with a count and elapsed time. One line per element floods the log store and buries the events you want.
How do you read iOS device logs in Console.app?
Console.app reads iOS device logs by streaming the unified logging system from a connected iPhone, and the search bar narrows that stream by subsystem, category, and message type.

- Connect the device over USB and accept the trust prompt. Select it under Devices in the Console.app sidebar and click Start streaming.
- Open the Action menu and turn on Include Info Messages and Include Debug Messages. Both are off by default, so Logger.info and Logger.debug lines stay hidden until you enable them.
- Type in the search field and pick Subsystem, Category, or Type from the suggestions, for example subsystem:com.example.shop combined with category:checkout. Save the combination as a favorite search.
- Add a Process filter for your app to cut system noise.
Xcode console filters do the same job inside a debug session. In Xcode 15 and later, the debug console can show subsystem, category, and type metadata for each line and filter on them, so you can stay in the IDE while running from a scheme (WWDC23: Debug with structured logging).
A release build streamed without a debugger attached replaces interpolated strings with <private>. A missing value in Console.app usually means the call site needs .public.
How do you get app logs from an iPhone?
Three routes pull app logs off an iPhone: the log collect command from a Mac, a sysdiagnose archive from the device itself, and an OSLogStore export built into the app. They differ in who can trigger them and how much they capture.

| Route | Who triggers it | Captures | Limit |
|---|---|---|---|
| log collect | Developer with a paired Mac | Persisted system-wide log archive | Needs a cable and sudo |
| sysdiagnose | Tester or support, on the device | Logs plus crash reports and system state | Large file, manual sharing |
| OSLogStore export | The app, on user action | Current-process entries only | Requires iOS 15 |
Log collect. With the device connected and trusted, run this on the Mac:
sudo log collect --device --last 30m --output ~/Desktop/device.logarchive
Open the .logarchive in Console.app, or query it with log show --archive. The archive holds only what the system persisted, so expect debug-level messages to be missing. Values without the .public option appear as <private> when no debugger was attached.
Sysdiagnose. Press both volume buttons and the side button together for about a second, and the device vibrates. After several minutes the archive appears under Settings > Privacy & Security > Analytics & Improvements > Analytics Data, ready to share by AirDrop. Apple's Profiles and Logs page documents the procedure, which suits testers who can't use a cable.
OSLogStore export. The app reads its own entries with the .currentProcessIdentifier scope, available from iOS 15, and writes them to a file the user can share:
import OSLog
func exportLogs() throws -> URL {
let store = try OSLogStore(scope: .currentProcessIdentifier)
let lines = try store
.getEntries(at: store.position(date: Date.now.addingTimeInterval(-3600)),
matching: NSPredicate(format: "subsystem == %@", "com.example.app"))
.compactMap { $0 as? OSLogEntryLog }
.map { "\($0.date.ISO8601Format()) [\($0.category)] \($0.composedMessage)" }
let url = FileManager.default.temporaryDirectory
.appendingPathComponent("app-log.txt")
try lines.joined(separator: "\n").write(to: url, atomically: true, encoding: .utf8)
return url
}
The store covers the running process only, so a crash on the previous launch won't appear. Test on a release build to confirm that private interpolations stay redacted before you let users send the file anywhere.
How do you measure performance with OSSignposter?
OSSignposter wraps a slow operation in a named interval that Instruments draws in the Points of Interest track. OSSignposter is available from iOS 15 and replaces the older os_signpost function calls (Apple: OSSignposter).
A heavy view load is the typical case. Begin the interval before the work starts and end it in a defer, so every exit path closes it:
import os
private let signposter = OSSignposter(
subsystem: "com.example.app",
category: "PointsOfInterest"
)
func loadDashboard() async {
let id = signposter.makeSignpostID()
let state = signposter.beginInterval("DashboardLoad", id: id)
defer { signposter.endInterval("DashboardLoad", state) }
let models = await repository.fetchModels()
signposter.emitEvent("ModelsFetched", id: id)
await viewModel.apply(models)
}
Profile with the Points of Interest instrument. The interval appears as a bar labeled DashboardLoad, and emitEvent adds a flag at that moment. Line the bar up against the CPU track to see which call dominates.
Choose intervals by app type: rendering time for games, request duration for network-heavy apps, and processing time for data-heavy apps.
Keep signposts out of hot paths such as per-frame callbacks, cell configuration, or loops over thousands of rows. Each call still costs something when Instruments is not recording, and thousands of tiny intervals bury the one you wanted. Put the interval around the whole operation, not each iteration inside it.
iOS remote logging best practices
Remote logging is justified only when a production failure can't be reproduced locally, and crash reporting plus MetricKit should come before any custom log shipping.
MetricKit's MXMetricManager delivers aggregated metric payloads and diagnostic payloads (crashes, hangs) from the device with no pipeline to build, and for most apps that is enough.
Add log shipping for one flow at a time, such as payments, sync, or onboarding. Our decision rule: add it only when all of these hold.
- The failure is neither a crash nor a hang, so diagnostic payloads don't cover it.
- You tried to reproduce it, for example with Network Link Conditioner, and couldn't.
- You can name the specific fields the report needs.
Example: checkout fails intermittently for some users, with no crash and no hang. You log the payment flow under its own subsystem, with error codes, HTTP status, and retry count. When the user taps "Send diagnostics", the app reads OSLogStore for the current process and attaches the filtered entries.
func recentPaymentErrors() throws -> [OSLogEntryLog] {
let store = try OSLogStore(scope: .currentProcessIdentifier)
return try store
.getEntries(at: store.position(date: Date().addingTimeInterval(-15 * 60)))
.compactMap { $0 as? OSLogEntryLog }
.filter { $0.subsystem == "com.example.app.payments"
&& ($0.level == .error || $0.level == .fault) }
}
The tap is your consent point. Testers can send a sysdiagnose archive instead. Because the store covers only the current launch, if the app was killed and relaunched, the report will be empty, and a rising share of empty reports is the early sign that you need to persist key events yourself.
What goes in the report:
| Send | Never send |
|---|---|
| Error codes, HTTP status, retry counts | Auth tokens, session IDs, push tokens |
| Subsystem, category, app and OS version | Emails, names, addresses, free-text input |
| Signpost durations for the failing flow | Full request or response bodies |
If a value was logged with .private, it should not leave the device in a report. Hash identifiers with .private(mask: .hash) so events can be correlated without exposing the value.
Declare what you collect in your privacy manifest and App Store Connect's App Privacy details. GDPR Article 5(1)(e) requires keeping personal data no longer than necessary, so set a fixed retention window and delete reports when it ends. The iOS app data security guide covers storage and transport.
For network debugging, Netguru's open-source ResponseDetective framework intercepts outgoing requests and incoming responses and prints them in full, so compile it into debug builds only.
Where does swift-log fit next to OSLog?
The apple/swift-log package is a logging facade, not a replacement for OSLog: call sites use its Logger API, and a LogHandler you supply decides whether anything reaches the unified logging system. Without one, the default handler writes plain text to the process's output stream, and nothing appears in Console.app (apple/swift-log).

In an app target, call LoggingSystem.bootstrap once at launch, before any dependency logs. A handler that forwards to Logger from the os framework then keeps subsystem filtering and Console.app output working. Because the handler writes through Logger, OSLogStore export also keeps working. Packages should never bootstrap; the app owns that call.
The second layer costs three things:
- Privacy: swift-log messages arrive as finished strings, so the handler picks one OSLogPrivacy setting for the whole message. Per-value .private and
.private(mask: .hash)markers are lost. - Level mapping: swift-log has trace and warning levels that OSLog lacks. Map trace to .debug, warning to .error, and its top level to .fault.
- Call site: entries record the handler's location unless you take care to pass the original context.
Our recommendation: use Logger directly in app code. Add swift-log only when a shared package must also run on Linux, or when a dependency requires a swift-log logger.
FAQ
What is the difference between os_log and Logger in Swift?
Does Logger affect app performance?
Build iOS apps you can debug in production
An iOS app you can debug in production needs three decisions made before release: a Logger from the os framework per feature, privacy annotations on every interpolated value, and crash reporting that collects stack traces with user consent and a defined retention period. These three elements let you reconstruct field failures from logs and crash reports.
If you are planning a new app, or auditing the logging in one that is already live, our iOS team can review your Logger setup, redaction rules, and crash reporting with you: get an estimate for your project.
