Skip to main content

Logging

This page shows how to create loggers and write messages, from a simple call to async code, actors and SwiftUI.

Creating Logly loggers​

A logger in Logly is a LogCategory value. It belongs to a category whose name appears in every line. There are three ways to create one, as the following example shows:

import Logly
import os

// 1. Recommended: the subsystem is the app's bundle ID
let network = Logger.custom(category: "Network")

// 2. With a custom subsystem
let payments = Logger.custom(subsystem: "com.example.shop.payments", category: "Payments")

// 3. Directly through the initializer
let database = LogCategory(subsystem: "com.example.shop", category: "Database")

If you omit it, Logger.custom uses Bundle.main.bundleIdentifier as the subsystem. If there is no bundle ID, as in some command-line tools, it is "DefaultSubsystem".

The subsystem does not appear in the output

The subsystem does not appear anywhere in Logly's output. Format, file and sinks only use the category name.

LogCategory is Sendable. You can store a logger as a static constant and use it from any thread, actor and task.

The recommended pattern for Logly creates all loggers as static constants in an extension of Logger:

extension Logger {
static let network = Logger.custom(category: "Network")
static let database = Logger.custom(category: "Database")
static let auth = Logger.custom(category: "Auth")
static let ui = Logger.custom(category: "UI")
}

Logger.network.info("Request started")
Logger.database.debug("Fetch executed")

Log levels in Logly​

The following table lists the five Logly log levels with their rawValue, output and purpose:

LevelrawValueOutputUse for
.debug1DEBUGDetails during development: variable values, control flow
.info2INFONormal events: startup, sign-in, completed actions
.warning3WARNINGAnomalies that do not stop operation
.error4ERRORAn operation failed, the app keeps running
.fault5FAULTSevere errors, e.g. corrupted data

Logly only processes a message if its rawValue is greater than or equal to that of LoggerConfiguration.shared.currentLogLevel. The default is .debug, so everything is logged. The following example shows which messages are dropped with the minimum level .warning:

LoggerConfiguration.shared.currentLogLevel = .warning

Logger.network.debug("Headers: \(headers)") // dropped
Logger.network.info("Response received") // dropped
Logger.network.warning("Response very slow") // logged
Logger.network.error("Timeout") // logged

Writing messages with Logly​

Every Logly log method takes a String. Swift adds file and line automatically through #file and #line. This is how you write messages at all five levels:

Logger.auth.debug("Token expires at \(expiryDate)")
Logger.auth.info("User \(userID) signed in")
Logger.auth.warning("Second sign-in attempt for \(userID)")
Logger.auth.error("Sign-in failed")
Logger.auth.fault("Keychain not readable")
No lazy evaluation

The text is built before Logly checks the level. Expensive expressions in the string interpolation are evaluated even if the message is dropped. In such cases check the level yourself:

if LoggerConfiguration.shared.currentLogLevel.rawValue <= LogLevel.debug.rawValue {
Logger.database.debug("State: \(store.expensiveDebugDescription())")
}

Passing errors to Logly​

The Logly methods error and fault have an additional error: parameter. Use it to pass the original Error value, as the following example shows:

do {
try context.save()
} catch {
Logger.database.error("Saving failed: \(error.localizedDescription)", error: error)
}

Good to know about errors in Logly:

  • The Error value is passed to the sinks only (in LogEvent.error). The Sentry integration, for example, turns it into a grouped exception event.
  • Console and log file contain only the text. If you want to see the error there, include it in the text as shown above.
  • debug, info and warning have no error: parameter.

Logging in async code with Logly​

Every Logly log method has an async variant with the same signature. Inside an async function the compiler picks that variant, and you have to write await:

func loadProfile(id: String) async throws -> Profile {
await Logger.network.info("Loading profile \(id)")
do {
let profile = try await api.profile(id: id)
await Logger.network.debug("Profile \(id) loaded")
return profile
} catch {
await Logger.network.error("Profile \(id) not loaded", error: error)
throw error
}
}

Without await, the compiler reports expression is 'async' but is not marked with 'await' inside async functions. Outside async functions you use the synchronous variant without await.

Both variants behave the same. The async variant does not wait for the file to be written. Whether the work runs in the background is decided solely by asynchronousLogging.

Real-world Logly examples​

Logly in a network client​

This network client uses Logly to log every request, error statuses, slow responses and failures:

final class APIClient: Sendable {
func fetch(_ url: URL) async throws -> Data {
await Logger.network.info("GET \(url.absoluteString)")
let start = Date()

do {
let (data, response) = try await URLSession.shared.data(from: url)
let status = (response as? HTTPURLResponse)?.statusCode ?? -1
let duration = Date().timeIntervalSince(start)

if status >= 400 {
await Logger.network.error("HTTP \(status) for \(url.absoluteString)")
} else if duration > 2 {
await Logger.network.warning("Slow response: \(String(format: "%.2f", duration)) s")
} else {
await Logger.network.debug("\(data.count) bytes in \(String(format: "%.2f", duration)) s")
}
return data
} catch {
await Logger.network.error("Request failed: \(error.localizedDescription)", error: error)
throw error
}
}
}

Logly in an actor​

In an actor you write Logly messages with await:

actor ImageCache {
private var images: [URL: Data] = [:]

func store(_ data: Data, for url: URL) async {
images[url] = data
await Logger.custom(category: "Cache").debug("Stored: \(url.lastPathComponent), \(images.count) entries")
}
}

Logly in parallel tasks​

You can also log with Logly from the parallel tasks of a task group:

await withTaskGroup(of: Void.self) { group in
for id in 1...5 {
group.addTask {
await Logger.custom(category: "Sync").info("Starting part \(id)")
}
}
}

With asynchronousLogging on, all messages go to the same serial queue and are written in the order in which they arrive there.

Logly in SwiftUI​

In a SwiftUI view you use Logly synchronously in onAppear and with await in the async function:

import SwiftUI
import Logly
import os

struct ContentView: View {
@State private var items: [String] = []

var body: some View {
List(items, id: \.self) { Text($0) }
.onAppear { Logger.ui.debug("ContentView visible") }
.task { await load() }
}

private func load() async {
await Logger.ui.info("Loading list")
items = ["A", "B", "C"]
await Logger.ui.debug("\(items.count) entries loaded")
}
}

Logly in synchronous code (UIKit, AppKit, helper functions)​

In synchronous code such as a UIKit view controller you call the Logly methods without await:

final class SettingsViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
Logger.ui.debug("Settings opened")
}

@objc private func resetTapped() {
Logger.ui.warning("User resets all settings")
}
}