Episode #344

Using os_log to Log Messages

Series: Unified Logging and Activity Tracing

12 minutes
Published on July 3, 2018

This video is only available to subscribers. Get access to this video and 584 others.

In this episode we show how you adopt the Unified Logging framework in code by using the OSLog type to define your log subsystems and categories, and how to use os_log to actually log events and messages.

Episode Links

Defining Shared OSLog instances

You will likely want to log statements and reuse the same subsystem and category throughout your application. For this, you can define a struct with a static member:

import os.log

struct Log {
    static var general = OSLog(subsystem: "com.myapp.my_target", category: "general")
}

Logging Messages

Then you can use the shared log instance to log messages with os_log:

os_log("The app did something interesting", 
    log: Log.general,
    type: .info)

Including values in your log messages

We can include values in our log messages by using one of the built-in formatting type specifiers:

%dIntegers
%.2fFloats
%sStrings
%@Objects

Sometimes we may want to give the system some information on how we want these values to be interpreted and formatted on display. One example is using time_t to get a formatted date to be displayed:

os_log("The record was modified at %{time_t}d", 
    log: Log.general, 
    type: .info, 
    time_t(date.timeIntervalSince1970))

This episode uses Xcode 10.0-beta2, Swift 4.2.