mirror of
https://github.com/apple/swift-log
synced 2026-11-22 03:40:39 +00:00
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.