From c9c6bb9d275ec0d95c3ad16391f3f045dc623104 Mon Sep 17 00:00:00 2001 From: om singhal <91667160+Om-singhaI@users.noreply.github.com> Date: Thu, 22 Oct 2026 05:30:03 -0400 Subject: [PATCH] Mutate the logger's handler in place on metadata writes (#529) Give `Logger.handler` a `_modify` accessor and replace its `get` with `_read`, so metadata writes update the stored handler instead of a copy. ### Motivation: `Logger.handler` only has `get` and `set`. A write such as `logger[metadataKey: "k"] = "v"` gets a copy of the handler, writes to it while the stored handler still shares the metadata dictionary, and sets it back. So every write copies the whole dictionary, and `withLogger(mergingMetadata:)` does that once per key. ### Modifications: - Give `Logger.handler` `_read`, `set` and `_modify` accessors. `_read` yields the stored handler. `_modify` keeps the existing uniqueness check on the storage and then yields the stored handler, so metadata and log level writes change it in place. `set` keeps the same check for plain `logger.handler = newHandler` assignments, which are cheaper through a setter than through `_modify`. - Add a test handler that counts copies of its metadata, with tests for direct writes and for `withLogger(mergingMetadata:)`. Without the change they report 10 copies instead of 0, and 5 instead of 1. ### Result: A metadata write on a logger that owns its storage no longer copies the dictionary. A copied logger still copies once on its first write, so value semantics are unchanged. 1,000 metadata writes with a handler that keeps metadata in a plain dictionary, debug build, three runs each: | Keys on the logger | Before | After | |---|---|---| | 10 | 7.2 to 8.1 ms | 0.46 to 0.50 ms | | 1,000 | 20.2 to 20.6 ms | 0.46 to 0.55 ms | | 10,000 | 134.0 to 134.4 ms | 0.47 to 0.50 ms | | 100,000 | 1.29 to 1.30 s | 0.32 to 0.35 ms | `withLogger(mergingMetadata:)` with 10,000 keys went from 0.64 to 0.65 s down to 2.9 to 3.1 ms. `StreamLogHandler` still rebuilds its pretty metadata string on every write; this change does not touch that. All 176 tests pass on macOS with Swift 6.4, and `swift format lint --strict` and `swift package diagnose-api-breaking-changes` are clean. Once yielding accessors land, `_read` and `_modify` can become `yielding borrow` and `yielding mutate`. Fixes #526. --- Sources/Logging/Logger.swift | 12 ++++- Tests/LoggingTests/LoggingTest.swift | 17 ++++++ Tests/LoggingTests/TaskLocalLoggerTest.swift | 14 +++++ Tests/LoggingTests/TestLogger.swift | 55 ++++++++++++++++++++ 4 files changed, 96 insertions(+), 2 deletions(-) diff --git a/Sources/Logging/Logger.swift b/Sources/Logging/Logger.swift index 4009e16..36ea9a0 100644 --- a/Sources/Logging/Logger.swift +++ b/Sources/Logging/Logger.swift @@ -57,15 +57,23 @@ public struct Logger { /// This computed property provides access to the `LogHandler`. @inlinable public var handler: any LogHandler { - get { - self._storage.handler + _read { + yield self._storage.handler } + // Keep a setter for plain assignments, which is cheaper than going through `_modify`. set { if !isKnownUniquelyReferenced(&self._storage) { self._storage = self._storage.copy() } self._storage.handler = newValue } + // Yield the stored handler, so a metadata write does not copy the handler's metadata. + _modify { + if !isKnownUniquelyReferenced(&self._storage) { + self._storage = self._storage.copy() + } + yield &self._storage.handler + } } /// The metadata provider this logger was created with. diff --git a/Tests/LoggingTests/LoggingTest.swift b/Tests/LoggingTests/LoggingTest.swift index c6991dc..c292d3d 100644 --- a/Tests/LoggingTests/LoggingTest.swift +++ b/Tests/LoggingTests/LoggingTest.swift @@ -1143,6 +1143,23 @@ struct LoggingTest { #expect(.error == logger1.logLevel) #expect(.trace == logger2.logLevel) } + + @Test func loggerMetadataWriteMutatesHandlerInPlace() { + var logger1 = Logger(label: "foo", factory: { _ in CopyCountingLogHandler() }) + for i in 0..<10 { + logger1[metadataKey: "key\(i)"] = "\(i)" + } + #expect(logger1.handlerCopies == 0) + + // The first write to a copy copies the handler once, later writes reuse that copy. + var logger2 = logger1 + for i in 0..<10 { + logger2[metadataKey: "key\(i)"] = "changed" + } + #expect(logger2.handlerCopies == 1) + #expect(logger1.handlerCopies == 0) + #expect(logger1[metadataKey: "key0"] == "0") + } } extension Logger { diff --git a/Tests/LoggingTests/TaskLocalLoggerTest.swift b/Tests/LoggingTests/TaskLocalLoggerTest.swift index 10d3e85..1f3982e 100644 --- a/Tests/LoggingTests/TaskLocalLoggerTest.swift +++ b/Tests/LoggingTests/TaskLocalLoggerTest.swift @@ -79,6 +79,20 @@ struct TaskLocalLoggerTest { logging.history.assertExist(level: .info, message: "merged", metadata: ["key": "value"]) } + @Test func mergeMetadataCopiesHandlerOnce() { + let logger = Logger(label: "test", factory: { _ in CopyCountingLogHandler() }) + let metadata: Logger.Metadata = ["a": "1", "b": "2", "c": "3", "d": "4", "e": "5"] + + withLogger(logger) { _ in + withLogger(mergingMetadata: metadata) { inner in + #expect(inner.handler.metadata == metadata) + #expect(inner.handlerCopies == 1) + } + #expect(Logger.current.handler.metadata.isEmpty) + #expect(Logger.current.handlerCopies == 0) + } + } + @Test func overrideLogLevel() { let logging = TestLogging() let logger = Logger(label: "test", factory: { logging.make(label: $0) }) diff --git a/Tests/LoggingTests/TestLogger.swift b/Tests/LoggingTests/TestLogger.swift index 06281cb..8c8e5c9 100644 --- a/Tests/LoggingTests/TestLogger.swift +++ b/Tests/LoggingTests/TestLogger.swift @@ -485,9 +485,64 @@ internal struct TestLibrary: Sendable { } } +/// A log handler that keeps its metadata in a copy-on-write box and counts how often the box was copied. +internal struct CopyCountingLogHandler: LogHandler { + final class Box { + var metadata: Logger.Metadata = [:] + var copies = 0 + } + + private var box = Box() + + var logLevel: Logger.Level = .info + + var copies: Int { + self.box.copies + } + + var metadata: Logger.Metadata { + get { + self.box.metadata + } + set { + self.makeUnique() + self.box.metadata = newValue + } + } + + subscript(metadataKey metadataKey: String) -> Logger.Metadata.Value? { + get { + self.box.metadata[metadataKey] + } + set { + self.makeUnique() + self.box.metadata[metadataKey] = newValue + } + } + + func log(event: LogEvent) {} + + private mutating func makeUnique() { + if !isKnownUniquelyReferenced(&self.box) { + let copy = Box() + copy.metadata = self.box.metadata + copy.copies = self.box.copies + 1 + self.box = copy + } + } +} + +extension Logger { + /// How often the `CopyCountingLogHandler` of this logger copied its box. + var handlerCopies: Int? { + (self.handler as? CopyCountingLogHandler)?.copies + } +} + // MARK: - Sendable extension TestLogHandler: @unchecked Sendable {} +extension CopyCountingLogHandler.Box: @unchecked Sendable {} extension Recorder: @unchecked Sendable {} extension Config: @unchecked Sendable {} extension MDC: @unchecked Sendable {}