From 7af2de138f5f0fddf0bd5c7e19face6944ed76af Mon Sep 17 00:00:00 2001 From: Vladimir Kukushkin Date: Fri, 24 Jul 2026 09:59:05 -0700 Subject: [PATCH] Document how to construct log handlers that need more than a label (#490) Document best practice for creating complex `LogHandlers`. ### Motivation: `LogHandler`s often need an expensive resource to write or export log events. This pattern should be documented. ### Modifications: Add "Constructing handlers that need more than a label" section to `ImplementingALogHandler.md` guide. ### Result: Closes #80. --------- Co-authored-by: Joseph Heck --- .../Docs.docc/ImplementingALogHandler.md | 130 ++++++++++++++++++ 1 file changed, 130 insertions(+) diff --git a/Sources/Logging/Docs.docc/ImplementingALogHandler.md b/Sources/Logging/Docs.docc/ImplementingALogHandler.md index d9853ca..9d02dd4 100644 --- a/Sources/Logging/Docs.docc/ImplementingALogHandler.md +++ b/Sources/Logging/Docs.docc/ImplementingALogHandler.md @@ -102,6 +102,136 @@ public struct PrintLogHandler: LogHandler { ``` +### Constructing handlers that need more than a label + +Many log handler backends need more than a `label` in order to construct them: a file path, a remote address, credentials, or +a buffer. A handler is an ordinary value that you construct, so nothing constrains its +initializer — it can take any parameters it needs, and it can `throw`. There is no +protocol-required `init(label:)`. The single `label` argument on factory methods such as +`StreamLogHandler.standardOutput(label:)` is a convention, not a requirement. + +Open expensive or fallible resources, such as a file, a socket, early and up front in your own initializer that can `throw`, so that failures surface at setup time. +``LogHandler/log(event:)`` cannot throw, so an error deferred to logging time has nowhere to go. +Keep the handler `struct` cheap and copyable by placing any shared resource behind a thread-safe reference type. +Value semantics apply to a handler's *configuration* — its level and metadata — not its *destination*, so copies writing to +the same file are correct and expected. + +The `FileLogHandler` below opens its file once, in an initializer that throws and exception when you create it with an overlapping `Destination`. +The handler `struct` itself stays a cheap, copyable value: + +```swift +import Foundation +import Logging +import Synchronization + +/// A log handler that appends formatted log lines to a file on disk. +public struct FileLogHandler: LogHandler { + /// The shared, thread-safe destination. Open it once, then share it across handlers: because + /// the destination is a reference type, all those value-semantic handlers write through a single + /// locked file handle. + public final class Destination: @unchecked Sendable { + private let fileHandle: Mutex + + /// Opens `url` for appending. All validation happens here, at setup time. + public init(writingTo url: URL) throws { + let fileManager = FileManager.default + if !fileManager.fileExists(atPath: url.path) { + guard fileManager.createFile(atPath: url.path, contents: nil) else { + throw Failure.cannotCreateFile(url) + } + } + self.fileHandle = .init(try FileHandle(forWritingTo: url)) + _ = try self.fileHandle.withLock { try $0.seekToEnd() } + } + + func write(_ line: String) { + // `log(event:)` cannot throw, so a write failure is handled here, not propagated. + do { + try self.fileHandle.withLock { try $0.write(contentsOf: Data(line.utf8)) } + } catch { + // Surface the failure without crashing the application. + try? FileHandle.standardError.write(contentsOf: Data("FileLogHandler: \(error)\n".utf8)) + } + } + + /// Flushes and closes the file. Call this during shutdown. + public func close() { + self.fileHandle.withLock { try? $0.close() } + } + } + + /// Errors thrown while opening a ``Destination``. + public enum Failure: Error { + case cannotCreateFile(URL) + } + + private let label: String + private let destination: Destination + + // Per-logger configuration — this is what must carry value semantics. + public var logLevel: Logger.Level = .info + public var metadata: Logger.Metadata = [:] + public var metadataProvider: Logger.MetadataProvider? + + /// Cheap and non-throwing, so it is safe to call from a bootstrap factory closure per label. + public init(label: String, destination: Destination, metadataProvider: Logger.MetadataProvider? = nil) { + self.label = label + self.destination = destination + self.metadataProvider = metadataProvider + } + + public func log(event: LogEvent) { + var merged = self.metadata + if let provided = self.metadataProvider?.get() { + merged.merge(provided, uniquingKeysWith: { _, new in new }) + } + if let explicit = event.metadata { + merged.merge(explicit, uniquingKeysWith: { _, new in new }) + } + let renderedMetadata = + merged.isEmpty + ? "" + : " " + merged.sorted { $0.key < $1.key }.map { "\($0.key)=\($0.value)" }.joined(separator: " ") + self.destination.write("\(event.level) \(self.label):\(renderedMetadata) \(event.message)\n") + } + + public subscript(metadataKey key: String) -> Logger.Metadata.Value? { + get { self.metadata[key] } + set { self.metadata[key] = newValue } + } +} +``` + +#### Using your log handler + +Construct the destination where you can use `try` to build a logger backed by your handler, then bind it +as ``Logger/current`` for the application's lifetime using `withLogger`: + +```swift +// Open the file once, where setup can throw. +let destination = try FileLogHandler.Destination(writingTo: URL(fileURLWithPath: "/var/log/myapp.log")) +defer { destination.close() } + +// Build a logger backed by the handler, then bind it for the scope. +let logger = Logger(label: "app") { label in + FileLogHandler(label: label, destination: destination) +} +try await withLogger(logger) { logger in + logger.info("Application started") + // Code in this scope reads the handler through Logger.current. +} +``` + +The `try` on `Destination` is where setup fails if the path is unwritable: validation happens +before the logger is constructed, so you never need a throwing factory overload. +Use the same pattern for handlers that connect to a remote service: + - validate and connect up front + - keep ``LogHandler/log(event:)`` non-blocking by buffering onto a background task + - provide a `close()` or `shutdown()` (or use [Swift Service Lifecycle](https://github.com/swift-server/swift-service-lifecycle) service) to flush on shutdown + +For runtime failures the handler can't avoid, such as a full disk or a broken pipe, degrade gracefully inside `log(event:)` by dropping the log message, retrying, or reporting to `stderr`. +Never call `fatalError` on the logging path. + ### Advanced features #### Metadata providers