Skip to main content

iOS Logging in Swift: Apple's Unified Logging, OSLog and Logger

· 12 min read
Nikita Lazarev-Zubov

iOS Log

Updated November 2026: added how to read logs from an iPhone, with and without a Mac, and how to collect logs remotely from your users' devices.

Logging is the process of collecting data about events occurring in a system. It’s an indispensable tool for identifying, investigating, and debugging incidents. Every software development platform has to offer a means of logging, and iOS is no exception.

Being a UNIX-like system, iOS supported the syslog standard from as long as iOS has been around (since 2007). In addition, from 2005 Apple System Log (ASL) has been supported by all Apple operating systems. However, ASL isn’t perfect: It has multiple APIs performing similar functions to one another; it stores logs in plain text, and it requires going deep into the file system to read them. It also doesn’t perform very well, because string processing happens mostly in real time. Apple deprecated ASL in iOS 10 and macOS 10.12 in favor of an improved system.

iOS Logging APIs at a Glance​

APISinceWhere the output goes
Apple System Log (asl_log), syslogiOS 2Deprecated since iOS 10
printSwift 2Xcode console (stdout) only, not stored on the device
NSLogiOS 2Unified logging (and stderr)
os_logiOS 10Unified logging
LoggeriOS 14Unified logging, with a Swift API
OSLogStoreiOS 15Reads your app's own unified log entries
OSSignposteriOS 15Performance intervals for Instruments

For new Swift code, Logger is the API to use. The rest of this post shows how it works.

Apple’s Unified Logging​

In 2016, Apple presented its replacement for ASL, the OSLog framework, also known as unified logging. And “unified” is right: It has a simple and clean API for creating entries, and an efficient way of reading logs across all Apple platforms. It logs both kernel and user events, and lets you read them all in a single place.

Beyond its impressive efficiency and visual presentation, unified logging offers performance benefits. It stores data in a binary format, thus saving a lot of space. The notorious observer effect is mitigated by deferring all string processing work until log entries are actually displayed.

Let’s dive in and put unified logging to work.

Unified Logging in Depth​

Writing and Reading Logs​

The easiest way to create an entry using OSLog is to initialize a Logger instance and call its log method:

    import OSLog

let logger = Logger()
logger.log("Hello Shipbook!")

After running this small Swift program, the message "Hello Shipbook!" will appear in the Xcode debug output:

Xcode debug output

Figure 1: Xcode debug output

Since unified logging stores its data in binary format, reading that data requires special tools. This is why Apple introduced the brand new Console application alongside the framework. This is how the log message appears in Console:

The Console application for reading unified logging messages

Figure 2: The Console application for reading unified logging messages

As you can see, unified logging takes care of all relevant metadata for you: Human-readable timestamps, the corresponding process name, etc.

Another often underestimated way of reading logs is by means of the OSLog framework itself. The process is straightforward: You only need to have a specific instance of the OSLogStore class and a particular point in time that you’re interested in. For example, the code snippet below reads the entries the app has written since it launched:

    do {
let store = try OSLogStore(scope: .currentProcessIdentifier)
let position = store.position(timeIntervalSinceLatestBoot: 0)

let entries = try store.getEntries(at: position)
// Do something with retrieved log entries.
} catch {
// Handle possible disk reading errors.
}

This might be useful in testing, or for sending logs to your servers. Keep in mind that on iOS, OSLogStore only reads the current process: after a crash, the next launch can't read the logs of the run that crashed.

Log Levels​

For grouping and filtering purposes, logs are usually separated into levels. The levels signify the severity of each entry. Unified logging supports five levels, with 1 being the least problematic and 5 being the most severe. Here’s the full list of supported levels and Apple’s recommendations for using them:

  1. The debug level is typically used for information that is useful while debugging. Log entries of this level are not stored to disk, and are displayed in Console only if enabled.
  2. The info level is used for non-essential information that might come in handy for debugging problems. By default, the log messages at this level are not persisted.
  3. The default level (also called notice level) is for logging information essential for troubleshooting potential errors. Starting from this level, messages are always persisted on disk.
  4. The error level is for logging process-level errors in your code.
  5. The fault level is intended for messages about unrecoverable errors, faults, and major bugs in your code.

Beyond their use in classifying error severity, log levels have an important impact on log processing: The higher the level, the more information the system gathers, and the higher the overhead. Debug messages produce negligible overhead, compared to the most critical (and supposedly rare) errors and faults.

Here’s how different levels can be used in code:

    logger.log(level: .debug, "I am a debug message")
logger.log(level: .info, "I am info")
logger.log(level: .default, "I am a notice")
logger.log(level: .error, "I am an error")
logger.log(level: .fault, "I am a fault, you're doomed")

And this is how those entries look in Console:

Logs of different levels in Console

Figure 3: Logs of different levels in Console

The debug and info messages are only visible here because the corresponding option is enabled. Otherwise, messages would be shown exclusively in the IDE’s debug output.

Logger also has a method for each level, plus a few aliases that read more naturally: trace (logged as debug), debug, info, notice, warning (logged as error), error, critical (logged as fault) and fault:

    logger.notice("Sync finished in \(duration) seconds")
logger.warning("Low disk space: \(freeBytes) bytes left")

Subsystems and Categories​

Logs generated by all applications are stored and processed together, along with kernel logs. This means that it’s crucial to have a way to organize log messages. Conveniently, Logger can be initialized using strings denoting the corresponding subsystem and the category of the message.

The most common way (and the method recommended by Apple) to denote the subsystem is to use the identifier of your app or its extension in reverse domain notation. The other parameter is used to categorize emitted log messages, for instance, “Network” or “I/O”. Here’s an example of a logger for categorized messages in Console:

    let logger = Logger(subsystem: "com.shipbook.Playground",
category: "I/O")

Log categorization in Console

Figure 4: Log categorization in Console

Formatting Entries​

Static strings are not the only type of data we want to use in logs. We often want to log some dynamic data together with the string, which can be achieved with string interpolation:

    logger.log(
level: .debug,
"User \(userID) has reached the limit of \(availableSpace)"
)

Strictly speaking, the string literal passed as a parameter to the log method is not a String, it’s an OSLogMessage object. As I mentioned before, the logging system postpones processing the string literal until the corresponding log entry is accessed by a reading tool. The unified logging system saves all data in binary format for further use (or until it’s removed, once the storage limit is exceeded).

All common data types that can be used in an interpolated String can also be used inside an OSLogMessage: other strings, integers, arrays, etc.

Redacting Private Data​

By default, almost all dynamic data—i.e., variables used inside a log message—is considered private and is hidden from the output (unless you’re running the code in Simulator or with the debugger attached). In Figure 5, below, the string value is substituted by “<private>”, but the integer is printed publicly.

Redacted private entry

Figure 5: Redacted private entry

Only scalar primitives are printed unredacted. If you need to log a dynamic value—like string or dictionary—without redacting, you can mark the interpolated variable as public:

    logger.log(
level: .debug,
"User \(userID, privacy: .public) has reached the limit of \(availableSpace)"
)

Apart from public, there are also private and sensitive levels of privacy, which currently work identically to the default level. Apple recommends specifying them anyway, presumably to ensure that your code is future-proof.

In many cases, you will want to keep data private while identifying it in logs massif. This option could come in handy for filtering out all messages concerning the same user ID, for example, in which case the variable can be hidden under a mask:

    logger.log(
level: .debug,
"User \(userID, privacy: .private(mask: .hash)) has reached the limit of \(availableSpace)"
)

The value in the output will be meaningless, but identifiable:

Private data hidden under a mask

Figure 6: Private data hidden under a mask

Performance Measuring​

A special use case of unified logging is performance measurement, a function that was introduced two years after the system was first released. The principle is simple: You create an instance of OSSignposter and call its methods at the beginning and end of the piece of code that you want to measure. Optionally, in the middle of the measured code you can add events, which will be visible on the timeline when analyzing measured data. Here’s how it looks in assembly:

    let signposter = OSSignposter(logger: logger)
let signpostID = signposter.makeSignpostID()

// Start measuring.
let state = signposter.beginInterval("heavyActivity",
id: signpostID)

// The piece of code of interest.
runHeavyActivity()
signposter.emitEvent("Heavy activity finished running",
id: signpostID)
finalizeHeavyActivity()

// Stop measuring.
signposter.endInterval("heavyActivity", state)

You can analyze this data using the os_signpost tool in Instruments:

Performance measurement using OSSignposter

Figure 7: Performance measurement using OSSignposter

Reading Logs from an iPhone​

While the app runs from Xcode, its logs show up in Xcode's debug console. To see the logs of a device that isn't running your app from Xcode, you have a few options.

With a Mac: Console and log collect​

Connect the iPhone to your Mac, open the Console app, select the iPhone in the sidebar and start streaming. Console shows the device's live unified log. Filter by your subsystem (your bundle identifier) to see only your app.

To save the device's logs for later, collect a log archive from the terminal and open it in Console, or query it with log show:

    sudo log collect --device --last 1h --output device.logarchive
log show device.logarchive --predicate 'subsystem == "com.shipbook.Playground"'

Without a Mac: sysdiagnose​

On the iPhone itself, press both volume buttons and the side button together for about a second, until the phone vibrates. iOS writes a sysdiagnose in the background, which takes a few minutes. It then appears under Settings → Privacy & Security → Analytics & Improvements → Analytics Data, named sysdiagnose_…, and you can share it from there. The archive contains the unified log, which you open in Console on a Mac.

Both ways need the phone in your hands, or a user willing to follow these steps and send you a large file. They also only contain what the device kept: debug and info messages aren't stored, and older entries are deleted as space runs out.

iOS Remote Logging: Getting Logs from Your Users' Devices​

When a bug happens on a user's iPhone, unified logging has already done its job, but the logs stay on that phone. To see what happened before an error in production, the app has to send its logs to you. That's remote logging.

Shipbook is a remote logging platform for iOS. Its SDK has an API much like Logger, uploads the logs of every session to the cloud, and lets you search them by user, session, and severity. Install it with Swift Package Manager from https://github.com/ShipBook/ShipBookSDK-iOS.git, then start it when the app launches:

    import ShipBookSDK

// In application(_:didFinishLaunchingWithOptions:)
ShipBook.start(appId: "YOUR_APP_ID", appKey: "YOUR_APP_KEY")

Create a logger per class and log at the level you need:

    fileprivate let log = ShipBook.getLogger(MainViewController.self)

log.e("Payment failed: \(error)") // Error
log.w("Retrying request") // Warning
log.i("User opened settings") // Info
log.d("Cache hit for \(key)") // Debug
log.v("Rendering cell \(index)") // Verbose

Shipbook also writes every log to unified logging, with your bundle identifier as the subsystem and the logger's tag as the category. So while you run the app from Xcode, the same messages still show up in Xcode's debug console. The full setup, including linking sessions to your users, is in the iOS integration guide.

Conclusion​

Apple’s unified logging is both powerful and simple to use. As its name suggests, the system can be used with all Apple platforms: iOS, iPadOS, macOS, and watchOS, using either Swift or Objective-C. Unified logging is also efficient thanks to its deferred log processing and compressed binary format storage. It mitigates the observer effect and reduces disk usage.

Unified logging is the right tool while you're debugging, or when you can get the device in your hands. For the bugs your users hit in production, you need the logs sent to you, which is what iOS remote logging with Shipbook does.