|

Swift Log: Why Context Metadata Belongs at the Logging Boundary

Three metadata layers flowing into one log event

A request can pass through several functions before an error is logged. The message may say what failed, but without context it cannot say which request it belongs to. Passing a request identifier through every logging call is repetitive; storing one global identifier is wrong when requests overlap.

Swift Log separates the message from the context attached to it. A logger can hold stable metadata, a MetadataProvider can supply values when a log event is emitted, and a call can override metadata for one event. The interesting design is not the dictionary itself. It is where the three sources meet and which one wins.

We will trace the merge order in the source, demonstrate the behavior using the package’s in-memory handler, and look at the boundary between logger value semantics and shared log storage.

Three Sources, One Event

The InMemoryLogHandler.log(event:) implementation begins with the handler’s metadata, merges the provider’s current values, and then merges event.metadata. Each merge keeps the right-hand value for duplicate keys. StreamLogHandler.prepareMetadata follows the same order for its normal metadata layers.

The example deliberately uses the in-memory backend rather than parsing timestamps from console output. It makes the resulting metadata directly inspectable.

import Logging
import InMemoryLogging

let provider = Logger.MetadataProvider {
    ["request": "req-42", "region": "provider"]
}
var handler = InMemoryLogHandler()
handler.metadata = ["service": "checkout", "region": "base"]
handler.metadataProvider = provider

let logger = Logger(label: "checkout") { _ in handler }
logger.info("accepted", metadata: ["region": "event"])
let event = handler.entries[0]
print("message:", event.message)
print("service:", event.metadata["service"]!)
print("request:", event.metadata["request"]!)
print("region:", event.metadata["region"]!)
message: accepted
service: checkout
request: req-42
region: event

The service key survives from the handler because neither later layer replaces it. The request key comes from the provider. All three layers specify region, so the per-event value event wins. This is a deterministic precedence rule, not a promise that all logging backends serialize metadata identically.

The handler.entries accessor is supplied by the in-memory logging module. It is suitable for inspection in this example, not a reason to use an unbounded memory store for production logs.

Providers Are Evaluated, Not Snapshotted

A Logger.MetadataProvider stores a @Sendable () -> Logger.Metadata closure. Calling get() invokes it. The provider does not automatically capture a request identifier from the network stack; the application or an instrumentation library must supply the current context.

The following example demonstrates the invocation boundary without relying on a task-local dependency:

import Logging

let first = Logger.MetadataProvider {
    ["request": "req-42", "region": "east"]
}
let second = Logger.MetadataProvider {
    ["region": "west", "worker": "queue"]
}
let combined = Logger.MetadataProvider.multiplex([first, second])!
let values = combined.get()
print("request:", values["request"]!)
print("region:", values["region"]!)
print("worker:", values["worker"]!)
request: req-42
region: west
worker: queue

multiplex evaluates providers from left to right and merges their dictionaries. The second provider replaces region with west, while request and worker remain. This is a provider-to-provider merge, separate from the handler → provider → event precedence in the previous section.

In a server application, a provider may read a task-local request context at emission time. That is an architectural possibility described by the API, not a behavior demonstrated by this constant-value example. Context propagation and cleanup must be implemented correctly by the application or tracing integration.

Logger Copies and Shared Storage Are Different

A Logger is a value with respect to its configured level and metadata. Its source uses copy-on-write storage: mutating a copied logger’s handler can first separate that logger’s configuration from the original. This matters when a library receives a logger and adds its own metadata.

The following example inspects configuration without depending on output formatting:

import Logging
import InMemoryLogging

var parent = Logger(label: "jobs") { _ in InMemoryLogHandler() }
parent.logLevel = .debug
parent[metadataKey: "scope"] = "parent"

var child = parent
child.logLevel = .error
child[metadataKey: "scope"] = "child"

print("parent level:", parent.logLevel)
print("child level:", child.logLevel)
print("parent scope:", parent[metadataKey: "scope"]!)
print("child scope:", child[metadataKey: "scope"]!)
parent level: debug
child level: error
parent scope: parent
child scope: child

Changing child does not change parent’s level or scope metadata. This does not imply that two logger copies have independent output destinations. The in-memory handler’s LogStore is a reference shared through handler copies, protected by a lock. Value semantics for configuration and shared storage for emitted events solve different problems.

A backend implementing LogHandler must preserve the former. If it stores all configuration in one mutable shared object, changing a copied logger can unexpectedly affect another caller.

Filtering Happens Before the Handler

The logger compares the event’s severity with its configured logLevel before handing the event to the handler. The in-memory backend makes this visible without assuming a particular console format:

import Logging
import InMemoryLogging

let handler = InMemoryLogHandler()
var logger = Logger(label: "worker") { _ in handler }
logger.logLevel = .warning
logger.info("polling")
logger.error("failed")
print("entries:", handler.entries.count)
print("kept:", handler.entries[0].message)
entries: 1
kept: failed

The info event is below the warning threshold, while error is admitted. The handler receives one event. A threshold is not a sampling strategy: it cannot distinguish important and unimportant messages at the same severity.

Recent source also contains SwiftPM traits that can compile out selected log levels. That is a different decision from changing logger.logLevel at runtime. The example above demonstrates only runtime filtering; it does not build with a compile-time trait.

Practical Uses and Limits

For HTTP request diagnostics, stable logger metadata can identify a service while a provider supplies request context at emission time. The first example’s service and request fields illustrate the two roles; the sample uses a fixed request value, not automatic propagation.

For background workers, a copied logger can add a local scope without changing the parent logger’s configuration. The parent and child example shows the separation. This is useful when a job-processing component adds job-specific fields to a logger received from its caller.

For tests of error paths, an in-memory handler makes emitted events inspectable. The filtering example proves that only the error event was recorded at the configured threshold. Tests should inspect semantic fields rather than assume a stable timestamped console line.

There are limits. The LoggingSystem.bootstrap factory is a process-wide, one-time configuration point; it should not be called separately for every request or test. A custom LogHandler must implement provider support to receive contextual values; the protocol’s default metadataProvider implementation returns nil and does not retain assignments. Metadata may contain sensitive values, so providers need an explicit policy for what is safe to emit. And creating a dictionary on each event has a cost: the API does not make metadata generation free.

What the Source Actually Guarantees

The inspected default-branch Package.swift declares Swift tools 6.2, library products Logging and InMemoryLogging, and no external package dependencies. It defines optional traits for excluding log levels at compile time. The manifest does not specify Apple platform minimums. These facts describe the inspected default branch on November 12, 2026, not a verified tagged release; no latest-release version is asserted here.

The repository is licensed under Apache 2.0. The key implementation paths are MetadataProvider.swift, Logger.swift, InMemoryLogHandler.swift, and StreamLogHandler.swift. They distinguish four concerns: obtaining context, merging it, isolating logger configuration, and deciding which events reach a backend.

The examples’ outputs above are source-derived expectations, not recorded results of an actual package build. The execution environment could not fetch the GitHub dependency because DNS resolution failed. That validation remains open.

The useful lesson is a boundary: the application owns context, the logger owns event intent, and the handler owns output. Swift Log makes their meeting point explicit. That makes logging easier to adapt across libraries, but it does not remove the application’s responsibility for context propagation, privacy, or backend behavior.

Sources
Next PostSwiftNIO: Why ByteBuffer Has Two Cursors