Compare commits

...
6 Commits
Author SHA1 Message Date
om singhal c9c6bb9d27 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.
2026-10-22 10:30:03 +01:00
dependabot[bot] 6404842475 Bump swiftlang/github-workflows/.github/workflows/soundness.yml from 0.0.15 to 0.0.16 (#528)
Bumps
[swiftlang/github-workflows/.github/workflows/soundness.yml](https://github.com/swiftlang/github-workflows)
from 0.0.15 to 0.0.16.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/swiftlang/github-workflows/releases">swiftlang/github-workflows/.github/workflows/soundness.yml's
releases</a>.</em></p>
<blockquote>
<h2>0.0.16</h2>
<h2>What's Changed</h2>
<ul>
<li>sha-pin for dependencies-action by <a
href="https://github.com/madrob"><code>@​madrob</code></a> in <a
href="https://redirect.github.com/swiftlang/github-workflows/pull/317">swiftlang/github-workflows#317</a></li>
<li>Update all Swift package test defaults to 6.4 by <a
href="https://github.com/finagolfin"><code>@​finagolfin</code></a> in <a
href="https://redirect.github.com/swiftlang/github-workflows/pull/319">swiftlang/github-workflows#319</a></li>
<li>Fix check-docs.sh failing on macOS when an option has no values by
<a
href="https://github.com/jakepetroules"><code>@​jakepetroules</code></a>
in <a
href="https://redirect.github.com/swiftlang/github-workflows/pull/320">swiftlang/github-workflows#320</a></li>
<li>Make CONTRIBUTORS.txt optional in license headers by <a
href="https://github.com/crleonard"><code>@​crleonard</code></a> in <a
href="https://redirect.github.com/swiftlang/github-workflows/pull/268">swiftlang/github-workflows#268</a></li>
<li>Add configurable timeouts for Linux, Static SDK, Wasm, and Android
builds by <a
href="https://github.com/austenstone"><code>@​austenstone</code></a> in
<a
href="https://redirect.github.com/swiftlang/github-workflows/pull/321">swiftlang/github-workflows#321</a></li>
<li>Use the new LTS Android NDK alone for both testing packages and for
workflow pulls here by <a
href="https://github.com/finagolfin"><code>@​finagolfin</code></a> in <a
href="https://redirect.github.com/swiftlang/github-workflows/pull/315">swiftlang/github-workflows#315</a></li>
</ul>
<h2>New Contributors</h2>
<ul>
<li><a href="https://github.com/crleonard"><code>@​crleonard</code></a>
made their first contribution in <a
href="https://redirect.github.com/swiftlang/github-workflows/pull/268">swiftlang/github-workflows#268</a></li>
<li><a
href="https://github.com/austenstone"><code>@​austenstone</code></a>
made their first contribution in <a
href="https://redirect.github.com/swiftlang/github-workflows/pull/321">swiftlang/github-workflows#321</a></li>
</ul>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/swiftlang/github-workflows/compare/0.0.15...0.0.16">https://github.com/swiftlang/github-workflows/compare/0.0.15...0.0.16</a></p>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/swiftlang/github-workflows/commit/3137ed1a48293ae9f4312fce349ed6210251db89"><code>3137ed1</code></a>
Use the new LTS Android NDK alone for both testing packages and for
workflow ...</li>
<li><a
href="https://github.com/swiftlang/github-workflows/commit/b9dfa3cb6e7361cac9170478c8569df324683ce6"><code>b9dfa3c</code></a>
Add configurable step timeouts for Linux, Static SDK, Wasm, and Android
build...</li>
<li><a
href="https://github.com/swiftlang/github-workflows/commit/a0e26726cfe9f46c9eec63f7af64060bb733761f"><code>a0e2672</code></a>
Make CONTRIBUTORS.txt optional in license headers (<a
href="https://redirect.github.com/swiftlang/github-workflows/issues/268">#268</a>)</li>
<li><a
href="https://github.com/swiftlang/github-workflows/commit/b9633883fec533530ebd7d5e82ef8ca832c2035f"><code>b963388</code></a>
Fix check-docs.sh failing on macOS when an option has no values (<a
href="https://redirect.github.com/swiftlang/github-workflows/issues/320">#320</a>)</li>
<li><a
href="https://github.com/swiftlang/github-workflows/commit/fa1e46cf0f07ffde2de131e9ed5bd66a488c289c"><code>fa1e46c</code></a>
Update all Swift package test defaults to 6.4 (<a
href="https://redirect.github.com/swiftlang/github-workflows/issues/319">#319</a>)</li>
<li><a
href="https://github.com/swiftlang/github-workflows/commit/81d865a4ea288ffefb0055d23ce4a748a845db20"><code>81d865a</code></a>
sha-pin for dependencies-action (<a
href="https://redirect.github.com/swiftlang/github-workflows/issues/317">#317</a>)</li>
<li>See full diff in <a
href="https://github.com/swiftlang/github-workflows/compare/0.0.15...0.0.16">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=swiftlang/github-workflows/.github/workflows/soundness.yml&package-manager=github_actions&previous-version=0.0.15&new-version=0.0.16)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)


</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-19 17:33:54 +00:00
Azeem Jiva fcd893317d Update benchmark expectations (#527)
_[One line description of your change]_

### Motivation: 

Update benchmark expectations, with the updated performance level

### Modifications:

Update json file with the new instruction count

### Result:

passing test
2026-10-15 14:56:54 +00:00
Azeem Jiva 65b3417512 Update threshold for GH runner (#525)
_[One line description of your change]_

### Motivation: Update threshold

This allows the faster GitHub runners to pass the benchmark tests.

### Modifications:

Updated threshold to a lower value

### Result:

Passing test
2026-10-13 13:23:02 +00:00
Vladimir Kukushkin 666b45a252 Adjust benchmark expectations (#523)
### Motivation:

Benchmarks CI has been failing recently on Swift 6.3 and 6.4, for
example: https://github.com/apple/swift-log/actions/runs/38083241726.
The results are actually better than expected in the thresholds.

### Modifications:

- Swift 6.3
MaxLogLevelNone.critical_log_with_critical_log_level_metadata_set.p90.json
threshold reduced
- Swift 6.4
MaxLogLevelWarning.notice_log_with_notice_log_level_attributed_generic.p90.json
threshold reduced

### Result:

CI should not fail anymore.
2026-10-13 12:03:23 +01:00
Chris Leonard 4038b6a4f7 Fix metadata provider handling when multiplexing log events (#522)
Ensure metadata from the multiplex handler’s own provider reaches
emitted logs.

Fixes #521.

## Motivation

`MultiplexLogHandler` accepts a metadata provider in its initializer,
but `log(event:)` never invokes it. Provider values such as trace IDs
are therefore missing from downstream logs.

## Modifications

- Merge the multiplex provider’s metadata into the event before
forwarding it.
- Preserve explicit per-message metadata overrides.
- Add regression tests covering one and two downstream handlers and
metadata precedence.

## Result

The supplied provider’s metadata is included in emitted logs.

Regression tests fail before the fix and pass afterward. All 174 tests
pass on macOS with Swift 6.4. Formatting and `git diff --check` also
pass.
2026-10-07 15:03:40 +00:00
11 changed files with 165 additions and 9 deletions

No files matched your search

+1 -1
View File
@@ -10,7 +10,7 @@ on:
jobs:
soundness:
name: Soundness
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@0.0.15
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@0.0.16
with:
license_header_check_project_name: "Swift Logging API"
@@ -1,4 +1,4 @@
{
"instructions" : 759,
"instructions" : 710,
"objectAllocCount" : 0
}
@@ -1,4 +1,4 @@
{
"instructions" : 734,
"instructions" : 689,
"objectAllocCount" : 0
}
}
@@ -1,4 +1,4 @@
{
"instructions" : 803,
"instructions" : 750,
"objectAllocCount" : 0
}
}
@@ -1,4 +1,4 @@
{
"instructions" : 828,
"instructions" : 775,
"objectAllocCount" : 0
}
@@ -144,9 +144,23 @@ public struct MultiplexLogHandler: LogHandler {
/// Log a message using the log level and source that you provide.
///
/// Metadata from this handler's metadata provider overrides metadata from
/// the underlying handlers and their providers. Explicit metadata in the
/// log event takes precedence over this handler's provider.
///
/// - parameters:
/// - event: The log event containing the level, message, metadata, and source location.
public func log(event: LogEvent) {
var event = event
if let provider = self._metadataProvider {
var metadata = provider.get()
if let explicit = event.metadata {
metadata.merge(explicit, uniquingKeysWith: { _, explicit in explicit })
}
if !metadata.isEmpty {
event.metadata = metadata
}
}
for handler in self.handlers where handler.logLevel <= event.level {
handler.log(event: event)
}
+10 -2
View File
@@ -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.
@@ -0,0 +1,48 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Logging API open source project
//
// Copyright (c) 2026 Apple Inc. and the Swift Logging API project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Swift Logging API project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import InMemoryLogging
import Logging
import Testing
struct MultiplexProviderRegressionTests {
@Test(arguments: [1, 2])
func constructorProviderReachesEverySink(handlerCount: Int) {
let sinks = (0..<handlerCount).map { _ in InMemoryLogHandler() }
let handler = MultiplexLogHandler(sinks, metadataProvider: .init { ["trace-id": "123"] })
let logger = Logger(label: "test", factory: { _ in handler })
#expect(logger.metadataProvider?.get()["trace-id"] == "123")
logger.info("hello")
for sink in sinks {
#expect(sink.entries.count == 1)
#expect(sink.entries.first?.metadata["trace-id"] == "123")
}
}
@Test func constructorProviderLayersBetweenChildAndExplicitMetadata() {
var sink = InMemoryLogHandler()
sink.metadataProvider = .init { ["child": "kept", "shared": "child"] }
let handler = MultiplexLogHandler(
[sink],
metadataProvider: .init {
["outer": "kept", "shared": "outer"]
}
)
let logger = Logger(label: "test", factory: { _ in handler })
logger.info("provided")
logger.info("explicit", metadata: ["shared": "explicit"])
#expect(sink.entries.first?.metadata == ["child": "kept", "outer": "kept", "shared": "outer"])
#expect(sink.entries.last?.metadata == ["child": "kept", "outer": "kept", "shared": "explicit"])
}
}
+17
View File
@@ -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 {
@@ -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) })
+55
View File
@@ -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 {}