Compare commits

...
24 Commits
Author SHA1 Message Date
Samuel MurrayandVladimir Kukushkin 5073617dac SLG-0003: Error parameter implementation (#425)
Add new methods on `Logger` that allows the caller to attach `Error`s to
log events, which will be propagated to the `LogHandler` as-is.

### Motivation:

Error information is typically of high interest in logs and log
analysis. Currently, however, there is no standardized way of attaching
`Error` information to logs, forcing users to either append it to the
log message (`logger.warning("Something went wrong: \(error)")`), or
attach it as metadata. By providing a separate parameter for this, and
passing it as-is to the `LogHandler`, we both provide a standard,
visible way to attach it, while also letting the `LogHandler` format it
as it sees fit.
Closes #291 

### Modifications:

* New methods on `Logger` that accept an (optional) `Error`.
* An `error` property is added to `LogEvent`, which contains the `Error`
from the new `Logger` methods.
* Adjust `LogHandler` implementations to serialize error as metadata.

### Result:

Users of `Logger` can use the new methods to attach `Error`s to their
logs, which should help unify how `Error`s get logged in various code
bases.
`LogHandler` implementations can use the new `error` property on
`LogEvent` and serialize it in a way that's suitable for that
implementation. In general, extracting the string representation and the
(qualified) type name should be a good baseline.

---------

Co-authored-by: Vladimir Kukushkin <kukushechkin@mac.com>
2026-04-14 06:03:57 -07:00
dependabot[bot]andVladimir Kukushkin 6f3fbace66 Bump swiftlang/github-workflows/.github/workflows/soundness.yml from 0.0.8 to 0.0.9 (#437)
Bumps
[swiftlang/github-workflows/.github/workflows/soundness.yml](https://github.com/swiftlang/github-workflows)
from 0.0.8 to 0.0.9.
<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.9</h2>
<h2>What's Changed</h2>
<ul>
<li>When splitting lines for the cross-PR checkout also split on \r\n by
<a href="https://github.com/ahoppen"><code>@​ahoppen</code></a> in <a
href="https://redirect.github.com/swiftlang/github-workflows/pull/249">swiftlang/github-workflows#249</a></li>
<li>Fix template injection by <a
href="https://github.com/justice-adams-apple"><code>@​justice-adams-apple</code></a>
in <a
href="https://redirect.github.com/swiftlang/github-workflows/pull/247">swiftlang/github-workflows#247</a></li>
<li>Remove tailing comma in matrix JSON by <a
href="https://github.com/plemarquand"><code>@​plemarquand</code></a> in
<a
href="https://redirect.github.com/swiftlang/github-workflows/pull/254">swiftlang/github-workflows#254</a></li>
<li>Update default Xcode versions in workflow to 16.4, 26.3, and 26.4 by
<a href="https://github.com/shahmishal"><code>@​shahmishal</code></a> in
<a
href="https://redirect.github.com/swiftlang/github-workflows/pull/255">swiftlang/github-workflows#255</a></li>
</ul>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/swiftlang/github-workflows/compare/0.0.8...0.0.9">https://github.com/swiftlang/github-workflows/compare/0.0.8...0.0.9</a></p>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/swiftlang/github-workflows/commit/f84da042883848ad67aadd051dc322eec18660d3"><code>f84da04</code></a>
Update default Xcode versions in workflow to 16.4, 26.3, and 26.4 (<a
href="https://redirect.github.com/swiftlang/github-workflows/issues/255">#255</a>)</li>
<li><a
href="https://github.com/swiftlang/github-workflows/commit/47c9717a9218ab60fe9fc6e957980d55fe949f1d"><code>47c9717</code></a>
Remove tailing comma in matrix JSON (<a
href="https://redirect.github.com/swiftlang/github-workflows/issues/254">#254</a>)</li>
<li><a
href="https://github.com/swiftlang/github-workflows/commit/8e529b937e15ba0a65af9b492393704fe3f16bdf"><code>8e529b9</code></a>
Fix template injection (<a
href="https://redirect.github.com/swiftlang/github-workflows/issues/247">#247</a>)</li>
<li><a
href="https://github.com/swiftlang/github-workflows/commit/58677410ce8ef88844850c908bcd830ad108c812"><code>5867741</code></a>
When splitting lines for the cross-PR checkout also split on \r\n (<a
href="https://redirect.github.com/swiftlang/github-workflows/issues/249">#249</a>)</li>
<li>See full diff in <a
href="https://github.com/swiftlang/github-workflows/compare/0.0.8...0.0.9">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.8&new-version=0.0.9)](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>
Co-authored-by: Vladimir Kukushkin <kukushechkin@mac.com>
2026-04-13 14:50:09 +01:00
Samuel Murray 41f6c72707 Retroactively update status of SLG-0005 to Approved (#438)
### Motivation:

SLG-0005 is implemented and released in 1.11.0.

### Modifications:

Update status to 'Approved'.

### Result:

The proposal reflects the actual status.
2026-04-09 08:35:48 +00:00
Rick Newton-Rogers bffceaf778 Drop Swift 6.0 (#436)
Motivation:

Swift 6.0 is no longer supported, we should bump the tools version and
remove it from our CI.

Modifications:

* Bump the Swift tools version to Swift 6.1
* Remove Swift 6.0 jobs where appropriate in main.yml, pull_request.yml

Result:

Code reflects our support window.
2026-04-08 14:52:39 +01:00
Vladimir Kukushkin 6558438e46 SLG-0004: Metadata privacy levels proposal (#416)
This proposal introduces an **attributed metadata system** that allows
attaching attributes to metadata values. Privacy level is the first
concrete attribute, enabling developers to mark metadata values as
`.private` or `.public` so `LogHandler` implementations can redact
sensitive values before logging.

### Motivation:

SwiftLog lacks a mechanism to attach attributes to metadata values as
sensitive to allow Log Handlers to control logging behavior.

### Modifications:

Added the SLG-004 proposal, introducing attributed metadata values
mechanism and privacy levels for metadata values.

### Result:

Proposal is ready for review.

Review result: the proposal is not accepted and needs rework.
2026-04-02 17:10:43 +01:00
Rick Newton-Rogers 7c04f86fba Enable Swift 6.3 jobs in CI (#435)
Motivation:

Swift 6.3 has been released, we should add it to our CI coverage.

Modifications:

Add additional Swift 6.3 jobs where appropriate in main.yml,
pull_request.yml

Result:

Improved test coverage.
2026-04-01 14:18:23 +01:00
Vladimir Kukushkin 8c0f217f01 [CI] Add automated release workflow using swift-temporal-sdk (#434)
Integrate swift-temporal-sdk's reusable auto-release workflow for
automated semantic versioning releases. Update CONTRIBUTING.md with a
link to the workflow documentation.

### Motivation

- Automate the release process using semantic versioning labels,
reducing manual overhead and ensuring consistent versioning across
releases.

### Modifications

- Add .github/workflows/auto-release.yml that uses swift-temporal-sdk's
reusable workflow
- Update CONTRIBUTING.md with automated release process documentation
linking to swift-temporal-sdk's workflow README

### Result

- When PRs are merged with semver labels (semver/patch, semver/minor),
the workflow automatically creates GitHub releases. Major releases
require manual creation.

### Test Plan

- Workflow will be validated after merge by labeling PRs with semver
labels and verifying that releases are created automatically.
2026-03-31 12:06:46 +01:00
Mads Odgaard f4f84c9f26 Avoid using CFilePointer typealias in default logger (#433)
Rewrites the default log handler to avoid typing out what the C file
pointer looks like on different platforms.

This fixes #374 - as we do not make any assumptions at compile time
about what `FILE*` is imported as in Swift.
2026-03-27 13:27:10 +00:00
Vladimir Kukushkin 1f38a59922 [SLG-0005]: LogEvent LogHandler API implementation (#423)
Replace the flat-parameter
`log(level:message:metadata:source:file:function:line:)` method on
`LogHandler` with
`log(event: LogEvent)`, enabling forward-compatible evolution of the
`LogHandler` interface without breaking existing
handler implementations.

### Motivation:

Changes to the `LogHandler` API require dance around creating new
overloads, deprecating old overloads, which unnecessary bloats
`LogHandler` protocol surface (like happened with the source:
parameter). We have upcoming changes that would introduce new
capabilities to the `LogHandler` protocol, for example
https://forums.swift.org/t/proposal-slg-0003-standardized-error-metadata-via-logger-convenience/84518/35.
It makes sense to introduce a single container structure for all the
data associated with a log event before introducing any new overloads in
`LogHandler` protocol.

### Modifications:

- New struct `LogEvent` is added.
- `LogHandler` protocol now has an additional `log(event: LogEvent)`
method.
- `Logger` is calling handler's `log(event: LogEvent)` method.

### Result:

Further changes to the `LogEvent` with new information passed from the
`Logger` to a `LogHandler` does not require changes in the `LogHandler`
API. As a bonus, `LogEvent` makes `source` a computable variable,
improving performance for log handlers who do not need the default
source created based on the log file location.
2026-03-27 13:13:04 +00:00
Honza Dvorsky 39e14910f6 [CI] Disable Darwin tests while we investigate flakiness (#430)
### Motivation:

Darwin tests got enabled recently to test out reliability, unfortunately
they're flaky so let's disable them for now and I'll open a test PR
where we can iterate on them instead.

### Modifications:

Disabled Darwin test runs on nightly jobs.

### Result:

More reliable CI again.
2026-03-24 11:29:03 +00:00
Vladimir Kukushkin 63ee499927 Enable tests on simulators (#429) 2026-03-20 22:06:35 +00:00
Vladimir Kukushkin c9ceb519e7 [SLG-0005]: LogEvent LogHandler API proposal (#424)
Replace the flat-parameter
`log(level:message:metadata:source:file:function:line:)` method on
`LogHandler` with
`log(event: LogEvent)`, enabling forward-compatible evolution of the
`LogHandler` interface without breaking existing
handler implementations.

### Motivation:

Changes to the `LogHandler` API require dance around creating new
overloads, deprecating old overloads, which unnecessary bloats
`LogHandler` protocol surface (like happened with the source:
parameter). We have upcoming changes that would introduce new
capabilities to the `LogHandler` protocol, for example
https://forums.swift.org/t/proposal-slg-0003-standardized-error-metadata-via-logger-convenience/84518/35.
It makes sense to introduce a single container structure for all the
data associated with a log event before introducing any new overloads in
`LogHandler` protocol.

### Modifications:

- SLG-0005 proposal added.

### Result:

Proposal is ready for implementation.
The reason the proposal has
2026-03-20 12:16:20 +00:00
dependabot[bot] 154acdf7d4 Bump swiftlang/github-workflows/.github/workflows/soundness.yml from 0.0.7 to 0.0.8 (#428)
Bumps
[swiftlang/github-workflows/.github/workflows/soundness.yml](https://github.com/swiftlang/github-workflows)
from 0.0.7 to 0.0.8.
<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.8</h2>
<h2>What's Changed</h2>
<ul>
<li>Fix build warnings in the workflow for iOS by <a
href="https://github.com/kkebo"><code>@​kkebo</code></a> in <a
href="https://redirect.github.com/swiftlang/github-workflows/pull/173">swiftlang/github-workflows#173</a></li>
<li>Check if the locally installed Android NDK matches the wanted NDK
version by <a
href="https://github.com/finagolfin"><code>@​finagolfin</code></a> in <a
href="https://redirect.github.com/swiftlang/github-workflows/pull/235">swiftlang/github-workflows#235</a></li>
<li>Update installed version of static linux SDK to 0.1.0 when using
released toolchains by <a
href="https://github.com/owenv"><code>@​owenv</code></a> in <a
href="https://redirect.github.com/swiftlang/github-workflows/pull/241">swiftlang/github-workflows#241</a></li>
<li>Update the Xcode versions - 26.3 and 26.4b2 by <a
href="https://github.com/shahmishal"><code>@​shahmishal</code></a> in <a
href="https://redirect.github.com/swiftlang/github-workflows/pull/245">swiftlang/github-workflows#245</a></li>
</ul>
<h2>New Contributors</h2>
<ul>
<li><a href="https://github.com/kkebo"><code>@​kkebo</code></a> made
their first contribution in <a
href="https://redirect.github.com/swiftlang/github-workflows/pull/173">swiftlang/github-workflows#173</a></li>
<li><a
href="https://github.com/finagolfin"><code>@​finagolfin</code></a> made
their first contribution in <a
href="https://redirect.github.com/swiftlang/github-workflows/pull/235">swiftlang/github-workflows#235</a></li>
<li><a href="https://github.com/owenv"><code>@​owenv</code></a> made
their first contribution in <a
href="https://redirect.github.com/swiftlang/github-workflows/pull/241">swiftlang/github-workflows#241</a></li>
</ul>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/swiftlang/github-workflows/compare/0.0.7...0.0.8">https://github.com/swiftlang/github-workflows/compare/0.0.7...0.0.8</a></p>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/swiftlang/github-workflows/commit/61db6917df4ec2ddeeb493757e2d1effd46af855"><code>61db691</code></a>
Update the Xcode versions - 26.3 and 26.4b2 (<a
href="https://redirect.github.com/swiftlang/github-workflows/issues/245">#245</a>)</li>
<li><a
href="https://github.com/swiftlang/github-workflows/commit/d7f8c780c9994917d6088e165e0fee6fb0bd06a1"><code>d7f8c78</code></a>
Update installed version of static linux SDK to 0.1.0 (<a
href="https://redirect.github.com/swiftlang/github-workflows/issues/241">#241</a>)</li>
<li><a
href="https://github.com/swiftlang/github-workflows/commit/bca81f75d7d1ae2474f1213169aab56dcad8961f"><code>bca81f7</code></a>
Revert Use local copy on action invocation (<a
href="https://redirect.github.com/swiftlang/github-workflows/issues/239">#239</a>)</li>
<li><a
href="https://github.com/swiftlang/github-workflows/commit/27ad4acfa502b0cb8b901532e8294a14b7273988"><code>27ad4ac</code></a>
Add symlinks for backwards compatability (<a
href="https://redirect.github.com/swiftlang/github-workflows/issues/238">#238</a>)</li>
<li><a
href="https://github.com/swiftlang/github-workflows/commit/555b8029955d1e91ed50768afb969805c796bdd6"><code>555b802</code></a>
Check if the locally installed Android NDK matches the wanted NDK
version (<a
href="https://redirect.github.com/swiftlang/github-workflows/issues/235">#235</a>)</li>
<li><a
href="https://github.com/swiftlang/github-workflows/commit/c6fcbaf70a845126ec165107a2d509bda17a2fd1"><code>c6fcbaf</code></a>
Use local copy on action invocation (<a
href="https://redirect.github.com/swiftlang/github-workflows/issues/236">#236</a>)</li>
<li><a
href="https://github.com/swiftlang/github-workflows/commit/2b7c7405cd7ce3627f84fb0765c785f099d19715"><code>2b7c740</code></a>
Fix build warnings in the workflow for iOS (<a
href="https://redirect.github.com/swiftlang/github-workflows/issues/173">#173</a>)</li>
<li>See full diff in <a
href="https://github.com/swiftlang/github-workflows/compare/0.0.7...0.0.8">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.7&new-version=0.0.8)](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-03-13 19:46:39 +00:00
Samuel MurrayandVladimir Kukushkin b93451412b Update proposal SLG-0003 after public review (#419)
Motivation:

The public review of the original proposal

(https://forums.swift.org/t/proposal-slg-0003-standardized-error-metadata-via-logger-convenience/84518)
is done, and these changes adjust for what was decided on.

Modifications:

The main difference is to pass Error instances as-is to LogHandlers,
rather than serializing it to metadata in Logger.

Co-authored-by: Vladimir Kukushkin <kukushechkin@mac.com>
2026-03-12 12:19:26 +00:00
Mike Drob c5f42781c4 Use org security policy instead of our bespoke version (#426) 2026-03-12 11:00:27 +00:00
Vladimir Kukushkin 4f1022c5cd Fix benchmarks — traits are only available in 6.1+ (#417) 2026-02-18 10:01:24 +00:00
Vladimir Kukushkin f22537f94d Do not run benchmarks on linux, we can’t collect anything anyway (#415)
`swift-nio` reusable workflow for running benchmarks has been recently
fixed and now linux benchmarks are failing because we do not have any
thresholds recorded. The main purpose for `swift-log` benchmarks is to
keep track of the amount of instructions and on linux runners
performance metrics are not available, so we cannot check the relevant
metric. Let's remove them.
2026-02-17 18:51:49 +00:00
Honza Dvorsky 185a56a488 Enable dependabot and switch GHA references to tags (#412)
### Motivation:

For better control over GitHub workflows, switch over to a tags-based
dependency.

### Modifications:

- Switch to tags
- Enable dependabot to get weekly update checks

### Result:

More streamlined and controlled GHA dependency updates.
2026-02-17 18:16:30 +00:00
Honza Dvorsky bbd81b6725 Fix: Only use unsafe flag on Swift 6.2 (#411)
### Motivation:

Package.swift needs to use tools-version 6.2, as we have dedicated 6.0
and 6.1 manifests.

Here, when building on 6.1, the Package.swift was being picked and an
unsafe flag was found, which isn't allowed on 6.1 (only on 6.2+).

### Modifications:

Bump Package.swift's tools-version to 6.2.

### Result:

Should fix dependees.
2026-02-16 18:22:18 +01:00
scottmarchant 8fb4e7147d chore: update Lock implementation with latest changes from swift-nio (#408)
Ports changes to `Lock` from swift-nio to swift-log.

### Motivation:

The copy-paste of `Lock` in swift-log should be updated with changes
from swift-nio.

### Modifications:

- Rolls back changed [made previously for
FreeBSD](https://github.com/apple/swift-log/pull/387/changes#diff-7b1bd45403dd1a7418287bd60682bf05ba2e4bf75dca1c0ca55a86d0477c9af5L73)
in favor of a consolidated implementation in swift-nio that will be in
place once https://github.com/apple/swift-nio/pull/3494 merges. @kkebo
Please confirm this works. After both of our PR's merge, swift-log and
swift-nio will have the same implementation as far as FreeBSD is
concerned.
- Brought the following recent changes from swift-nio over to swift-log:

  - https://github.com/apple/swift-nio/pull/3482
  - https://github.com/apple/swift-nio/pull/3480
  - https://github.com/apple/swift-nio/pull/3483

- Removed stale `// SRWLOCK does not need to be free'd` comment.

### Result:

`Lock` implementation will have the same implementation as swift-nio
(assuming https://github.com/apple/swift-nio/pull/3494 merges).
2026-02-12 12:51:03 +00:00
Samuel MurrayandVladimir Kukushkin d5dbc04d53 [SLG-0003]: [Proposal] Standardized Error Metadata via Logger Convenience (#405)
Add a proposal for the standardized way of attaching data from Error instances to log
posts.

### Motivation:

Addresses https://github.com/apple/swift-log/issues/291

### Modifications:

The "SLG-0003" proposal doc added.

### Result:

The proposal is ready for review.

---------

Co-authored-by: Vladimir Kukushkin <kukushechkin@mac.com>
2026-02-02 16:30:32 +00:00
Vladimir Kukushkin 47ef0ec6a4 Enable upcoming compiler features (#401)
Enable several upcoming compiler features to make the codebase more
explicit in intention:

```
    // https://github.com/apple/swift-evolution/blob/main/proposals/0335-existential-any.md
    // Require `any` for existential types.
    settings.append(.enableUpcomingFeature("ExistentialAny"))

    // https://github.com/swiftlang/swift-evolution/blob/main/proposals/0444-member-import-visibility.md
    settings.append(.enableUpcomingFeature("MemberImportVisibility"))

    // https://github.com/swiftlang/swift-evolution/blob/main/proposals/0409-access-level-on-imports.md
    settings.append(.enableUpcomingFeature("InternalImportsByDefault"))

    // https://docs.swift.org/compiler/documentation/diagnostics/nonisolated-nonsending-by-default/
    settings.append(.enableUpcomingFeature("NonisolatedNonsendingByDefault"))

    // Ensure all public types are explicitly annotated as Sendable or not Sendable.
    settings.append(.unsafeFlags(["-Xfrontend", "-require-explicit-sendable"]))
```

### Motivation:

Sync codebase with the modern practice, get ready for the upcoming
features.

### Modifications:

- Compiler flags added for all the existing targets.
- Imports and access modifiers adjusted.
- `LoggingSystem` marked as `Sendable`

### Result:

Codebase is updated with the modern practices.
2026-01-30 08:58:47 +01:00
Vladimir Kukushkin 7d6d55f9ed Update benchmarks expectations on Tahoe (#404)
Update macOS benchmarks after moving to Tahoe runners.

### Motivation:

`swift-log` has performance benchmarks measuring instructions. Results
may vary from version to version of macOS.

### Modifications:

Benchmarking thresholds updated based on the Tahoe runners results.

### Result:

Benchmark jobs pass.
2026-01-23 16:38:37 +01:00
Kenta KuboandFranz Busch 8f634e4e68 Add support for FreeBSD and OpenBSD (#387)
I've added support for FreeBSD. I've only tested this PR on FreeBSD, but
I believe it should also work on OpenBSD.

### Motivation:

closes #372 

Also, [Swift on FreeBSD preview
toolchain](https://forums.swift.org/t/swift-on-freebsd-preview/83064) is
now available.

### Modifications:

- changed pthread-related code for *BSD
- changed `Glibc.stdout` and `Glibc.stderr` for *BSD because they are
non-optional on *BSD

### Result:

swift-log and packages depending on it will be usable on FreeBSD.

### Checks:

I tested it with `swift build` and `swift test`. All tests have passed.

```console
$ swift test
...
Test Suite 'All tests' passed at 2025-11-07 04:29:34.003                                                                                         
         Executed 0 tests, with 0 failures (0 unexpected) in 0.0 (0.0) seconds
...
✔ Test run with 52 tests in 7 suites passed after 0.309 seconds.
```

Environment:

```console
$ uname -a
FreeBSD Coconut-rhinoceros-beetle 15.0-BETA4 FreeBSD 15.0-BETA4 releng/15.0-n280841-a7707f2a3bf4 GENERIC amd64
$ swift --version
Swift version 6.3-dev (LLVM bff1370bd79c983, Swift 57cf4ce563f700b)
Target: x86_64-unknown-freebsd14.3
Build config: +assertions
```

Swift toolchain is from
https://forums.swift.org/t/swift-on-freebsd-preview/83064.

---------

Co-authored-by: Franz Busch <f.busch@apple.com>
2026-01-19 16:37:43 +00:00
36 changed files with 2776 additions and 514 deletions

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
version: 2
updates:
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"
+12
View File
@@ -0,0 +1,12 @@
name: Auto Release
on:
workflow_dispatch:
permissions:
contents: write
pull-requests: read
jobs:
auto-release:
uses: apple/swift-temporal-sdk/.github/workflows/auto-release.yml@main
+18 -18
View File
@@ -14,28 +14,22 @@ jobs:
name: Unit tests
uses: apple/swift-nio/.github/workflows/unit_tests.yml@main
with:
linux_6_0_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
linux_6_1_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
linux_6_2_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
linux_6_3_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
linux_nightly_next_arguments_override: "--explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
linux_nightly_main_arguments_override: "--explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
windows_6_0_enabled: true
windows_6_1_enabled: true
windows_6_2_enabled: true
windows_6_3_enabled: true
windows_nightly_next_enabled: true
windows_nightly_main_enabled: true
windows_6_0_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
windows_6_1_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
windows_6_2_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
windows_6_3_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
windows_nightly_next_arguments_override: "--explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
windows_nightly_main_arguments_override: "--explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
benchmarks:
name: Benchmarks (NoTraits)
uses: apple/swift-nio/.github/workflows/benchmarks.yml@main
with:
benchmark_package_path: "Benchmarks/NoTraits"
macos-benchmarks:
name: macOS benchmarks (NoTraits)
uses: apple/swift-nio/.github/workflows/macos_benchmarks.yml@main
@@ -44,13 +38,6 @@ jobs:
macos_xcode_16_4_enabled: true
macos_xcode_26_1_enabled: true
benchmarks-MaxLogLevelWarningBenchmarks-trait:
name: Benchmarks (MaxLogLevelWarning)
needs: benchmarks
uses: apple/swift-nio/.github/workflows/benchmarks.yml@main
with:
benchmark_package_path: "Benchmarks/MaxLogLevelWarning"
macos-benchmarks-MaxLogLevelWarningBenchmarks-trait:
name: macOS benchmarks (MaxLogLevelWarning)
needs: macos-benchmarks
@@ -74,7 +61,20 @@ jobs:
with:
runner_pool: nightly
build_scheme: swift-log-Package
swift_test_enabled: true
debug_output_enabled: true
xcode_16_3_enabled: false
xcode_16_4_enabled: false
xcode_26_0_enabled: false
xcode_26_1_enabled: false
xcode_26_2_enabled: false
swift_6_1_enabled: true
swift_6_2_enabled: true
swift_6_3_enabled: true
macos_xcode_test_enabled: false
ios_xcode_test_enabled: false
watchos_xcode_test_enabled: false
tvos_xcode_test_enabled: false
visionos_xcode_test_enabled: false
wasm:
name: Wasm Swift SDK
@@ -89,8 +89,8 @@ jobs:
name: Release builds
uses: apple/swift-nio/.github/workflows/release_builds.yml@main
with:
windows_6_0_enabled: true
windows_6_1_enabled: true
windows_6_2_enabled: true
windows_6_3_enabled: true
windows_nightly_next_enabled: true
windows_nightly_main_enabled: true
+5 -19
View File
@@ -10,7 +10,7 @@ on:
jobs:
soundness:
name: Soundness
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@main
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@0.0.9
with:
license_header_check_project_name: "Swift Logging API"
@@ -18,28 +18,22 @@ jobs:
name: Unit tests
uses: apple/swift-nio/.github/workflows/unit_tests.yml@main
with:
linux_6_0_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
linux_6_1_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
linux_6_2_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
linux_6_3_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
linux_nightly_next_arguments_override: "--explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
linux_nightly_main_arguments_override: "--explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
windows_6_0_enabled: true
windows_6_1_enabled: true
windows_6_2_enabled: true
windows_6_3_enabled: true
windows_nightly_next_enabled: true
windows_nightly_main_enabled: true
windows_6_0_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
windows_6_1_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
windows_6_2_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
windows_6_3_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
windows_nightly_next_arguments_override: "--explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
windows_nightly_main_arguments_override: "--explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
benchmarks:
name: Benchmarks (NoTraits)
uses: apple/swift-nio/.github/workflows/benchmarks.yml@main
with:
benchmark_package_path: "Benchmarks/NoTraits"
macos-benchmarks:
name: macOS benchmarks (NoTraits)
uses: apple/swift-nio/.github/workflows/macos_benchmarks.yml@main
@@ -49,14 +43,6 @@ jobs:
macos_xcode_16_4_enabled: true
macos_xcode_26_1_enabled: true
benchmarks-MaxLogLevelWarningBenchmarks-trait:
name: Benchmarks (MaxLogLevelWarning)
# Workaround for reusing the same benchmarks.yml workflow
needs: benchmarks
uses: apple/swift-nio/.github/workflows/benchmarks.yml@main
with:
benchmark_package_path: "Benchmarks/MaxLogLevelWarning"
macos-benchmarks-MaxLogLevelWarningBenchmarks-trait:
name: macOS benchmarks (MaxLogLevelWarning)
# Workaround for reusing the same benchmarks.yml workflow
@@ -93,9 +79,9 @@ jobs:
name: Release builds
uses: apple/swift-nio/.github/workflows/release_builds.yml@main
with:
windows_6_0_enabled: true
windows_6_1_enabled: true
windows_6_2_enabled: true
windows_6_3_enabled: true
windows_nightly_next_enabled: true
windows_nightly_main_enabled: true
@@ -1,4 +1,4 @@
{
"instructions" : 589,
"instructions" : 619,
"objectAllocCount" : 0
}
@@ -1,4 +1,4 @@
{
"instructions" : 589,
"instructions" : 619,
"objectAllocCount" : 0
}
@@ -1,4 +1,4 @@
{
"instructions" : 3009,
"objectAllocCount" : 1
"instructions" : 1651,
"objectAllocCount" : 0
}
@@ -1,4 +1,4 @@
{
"instructions" : 3009,
"objectAllocCount" : 1
"instructions" : 1651,
"objectAllocCount" : 0
}
+1 -1
View File
@@ -1,4 +1,4 @@
// swift-tools-version: 6.0
// swift-tools-version:6.1
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
@@ -1,4 +1,4 @@
{
"instructions" : 937,
"instructions" : 984,
"objectAllocCount" : 0
}
@@ -1,4 +1,4 @@
{
"instructions" : 1718,
"instructions" : 1368,
"objectAllocCount" : 0
}
@@ -1,4 +1,4 @@
{
"instructions" : 855,
"instructions" : 893,
"objectAllocCount" : 0
}
@@ -1,4 +1,4 @@
{
"instructions" : 1636,
"instructions" : 1649,
"objectAllocCount" : 0
}
+1 -1
View File
@@ -1,4 +1,4 @@
// swift-tools-version: 6.1
// swift-tools-version:6.1
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
@@ -28,6 +28,12 @@ struct NoOpLogHandler: LogHandler {
self.metadataProvider = LoggingSystem.metadataProvider
}
func log(
event: LogEvent
) {
// Do nothing
}
func log(
level: Logger.Level,
message: Logger.Message,
+5
View File
@@ -118,3 +118,8 @@ For more information please refer to `swift package benchmark --help` or the [do
## How to contribute your work
Please open a pull request at https://github.com/apple/swift-log. Make sure the CI passes, and then wait for code review.
## Automated release process
This repository uses automated releases based on semantic versioning labels. See the [Auto Release Workflow documentation](https://github.com/apple/swift-temporal-sdk/blob/main/.github/workflows/README.md) for details.
+22 -19
View File
@@ -1,4 +1,4 @@
// swift-tools-version:6.1
// swift-tools-version:6.2
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Logging API open source project
@@ -59,24 +59,27 @@ let package = Package(
]
)
for target in package.targets {
for target in package.targets
where [.executable, .test, .regular].contains(
target.type
) {
var settings = target.swiftSettings ?? []
settings.append(.enableExperimentalFeature("StrictConcurrency=complete"))
// https://github.com/apple/swift-evolution/blob/main/proposals/0335-existential-any.md
// Require `any` for existential types.
settings.append(.enableUpcomingFeature("ExistentialAny"))
// https://github.com/swiftlang/swift-evolution/blob/main/proposals/0444-member-import-visibility.md
settings.append(.enableUpcomingFeature("MemberImportVisibility"))
// https://github.com/swiftlang/swift-evolution/blob/main/proposals/0409-access-level-on-imports.md
settings.append(.enableUpcomingFeature("InternalImportsByDefault"))
// https://docs.swift.org/compiler/documentation/diagnostics/nonisolated-nonsending-by-default/
settings.append(.enableUpcomingFeature("NonisolatedNonsendingByDefault"))
// Ensure all public types are explicitly annotated as Sendable or not Sendable.
settings.append(.unsafeFlags(["-Xfrontend", "-require-explicit-sendable"]))
target.swiftSettings = settings
}
// --- STANDARD CROSS-REPO SETTINGS DO NOT EDIT --- //
for target in package.targets {
switch target.type {
case .regular, .test, .executable:
var settings = target.swiftSettings ?? []
// https://github.com/swiftlang/swift-evolution/blob/main/proposals/0444-member-import-visibility.md
settings.append(.enableUpcomingFeature("MemberImportVisibility"))
target.swiftSettings = settings
case .macro, .plugin, .system, .binary:
() // not applicable
@unknown default:
() // we don't know what to do here, do nothing
}
}
// --- END: STANDARD CROSS-REPO SETTINGS DO NOT EDIT --- //
-64
View File
@@ -1,64 +0,0 @@
// swift-tools-version:6.0
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Logging API open source project
//
// Copyright (c) 2018-2019 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 PackageDescription
let package = Package(
name: "swift-log",
products: [
.library(name: "Logging", targets: ["Logging"]),
.library(name: "InMemoryLogging", targets: ["InMemoryLogging"]),
],
targets: [
.target(
name: "Logging",
dependencies: []
),
.target(
name: "InMemoryLogging",
dependencies: ["Logging"]
),
.testTarget(
name: "LoggingTests",
dependencies: ["Logging"]
),
.testTarget(
name: "InMemoryLoggingTests",
dependencies: ["InMemoryLogging", "Logging"]
),
]
)
for target in package.targets {
var settings = target.swiftSettings ?? []
settings.append(.enableExperimentalFeature("StrictConcurrency=complete"))
target.swiftSettings = settings
}
// --- STANDARD CROSS-REPO SETTINGS DO NOT EDIT --- //
for target in package.targets {
switch target.type {
case .regular, .test, .executable:
var settings = target.swiftSettings ?? []
// https://github.com/swiftlang/swift-evolution/blob/main/proposals/0444-member-import-visibility.md
settings.append(.enableUpcomingFeature("MemberImportVisibility"))
target.swiftSettings = settings
case .macro, .plugin, .system, .binary:
() // not applicable
@unknown default:
() // we don't know what to do here, do nothing
}
}
// --- END: STANDARD CROSS-REPO SETTINGS DO NOT EDIT --- //
+79
View File
@@ -0,0 +1,79 @@
// swift-tools-version:6.1
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Logging API open source project
//
// Copyright (c) 2018-2019 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 PackageDescription
let package = Package(
name: "swift-log",
products: [
.library(name: "Logging", targets: ["Logging"]),
.library(name: "InMemoryLogging", targets: ["InMemoryLogging"]),
],
traits: [
.trait(name: "MaxLogLevelDebug", description: "Debug and above available (compiles out trace)"),
.trait(name: "MaxLogLevelInfo", description: "Info and above available (compiles out trace, debug)"),
.trait(name: "MaxLogLevelNotice", description: "Notice and above available (compiles out trace, debug, info)"),
.trait(
name: "MaxLogLevelWarning",
description: "Warning and above available (compiles out trace, debug, info, notice)"
),
.trait(
name: "MaxLogLevelError",
description: "Error and above available (compiles out trace, debug, info, notice, warning)"
),
.trait(name: "MaxLogLevelCritical", description: "Only critical available (compiles out all except critical)"),
.trait(name: "MaxLogLevelNone", description: "All logging compiled out (no log levels available)"),
// By default, no traits are enabled (all log levels available)
.default(enabledTraits: []),
],
targets: [
.target(
name: "Logging",
dependencies: []
),
.target(
name: "InMemoryLogging",
dependencies: ["Logging"]
),
.testTarget(
name: "LoggingTests",
dependencies: ["Logging"]
),
.testTarget(
name: "InMemoryLoggingTests",
dependencies: ["InMemoryLogging", "Logging"]
),
]
)
for target in package.targets
where [.executable, .test, .regular].contains(
target.type
) {
var settings = target.swiftSettings ?? []
// https://github.com/apple/swift-evolution/blob/main/proposals/0335-existential-any.md
// Require `any` for existential types.
settings.append(.enableUpcomingFeature("ExistentialAny"))
// https://github.com/swiftlang/swift-evolution/blob/main/proposals/0444-member-import-visibility.md
settings.append(.enableUpcomingFeature("MemberImportVisibility"))
// https://github.com/swiftlang/swift-evolution/blob/main/proposals/0409-access-level-on-imports.md
settings.append(.enableUpcomingFeature("InternalImportsByDefault"))
target.swiftSettings = settings
}
-43
View File
@@ -1,43 +0,0 @@
# Security
This document specifies the security process for the SwiftLog project.
## Disclosures
### Private Disclosure Process
The SwiftLog maintainers ask that known and suspected vulnerabilities be
privately and responsibly disclosed by emailing
[sswg-security-reports@forums.swift.org](mailto:sswg-security-reports@forums.swift.org)
with the all the required detail.
**Do not file a public issue.**
#### When to report a vulnerability
* You think you have discovered a potential security vulnerability in SwiftLog.
* You are unsure how a vulnerability affects SwiftLog.
#### What happens next?
* A member of the team will acknowledge receipt of the report within 3
working days (United States). This may include a request for additional
information about reproducing the vulnerability.
* We will privately inform the Swift Server Work Group ([SSWG][sswg]) of the
vulnerability within 10 days of the report as per their [security
guidelines][sswg-security].
* Once we have identified a fix we may ask you to validate it. We aim to do this
within 30 days. In some cases this may not be possible, for example when the
vulnerability exists at the protocol level and the industry must coordinate on
the disclosure process.
* If a CVE number is required, one will be requested from [MITRE][mitre]
providing you with full credit for the discovery.
* We will decide on a planned release date and let you know when it is.
* Prior to release, we will inform major dependents that a security-related
patch is impending.
* Once the fix has been released we will publish a security advisory on GitHub
and in the Server → Security Updates category on the [Swift forums][swift-forums-sec].
[sswg]: https://github.com/swift-server/sswg
[sswg-security]: https://www.swift.org/sswg/security/
[swift-forums-sec]: https://forums.swift.org/c/server/security-updates/
[mitre]: https://cveform.mitre.org/
@@ -12,7 +12,7 @@
//
//===----------------------------------------------------------------------===//
import Logging
public import Logging
/// A custom log handler which just collects logs into memory.
/// You can then retrieve an array of those log entries.
@@ -46,6 +46,8 @@ public struct InMemoryLogHandler: LogHandler {
public var level: Logger.Level
/// The message which was logged.
public var message: Logger.Message
/// The error which was logged.
public var error: (any Error)?
/// The metadata which was logged.
public var metadata: Logger.Metadata
@@ -54,18 +56,49 @@ public struct InMemoryLogHandler: LogHandler {
self.message = message
self.metadata = metadata
}
public init(level: Logger.Level, message: Logger.Message, error: (any Error)?, metadata: Logger.Metadata) {
self.level = level
self.message = message
self.error = error
self.metadata = metadata
}
public static func == (lhs: InMemoryLogHandler.Entry, rhs: InMemoryLogHandler.Entry) -> Bool {
lhs.level == rhs.level
&& lhs.message == rhs.message
&& errorsEqual(lhs.error, rhs.error)
&& lhs.metadata == rhs.metadata
}
private static func errorsEqual(_ lhs: (any Error)?, _ rhs: (any Error)?) -> Bool {
switch (lhs, rhs) {
case (nil, nil):
return true
case let (l?, r?):
return "\(l)" == "\(r)" && String(reflecting: type(of: l)) == String(reflecting: type(of: r))
default:
return false
}
}
}
private final class LogStore: @unchecked Sendable {
private var _entries: [Entry] = []
private let lock = Lock()
fileprivate func append(level: Logger.Level, message: Logger.Message, metadata: Logger.Metadata) {
fileprivate func append(
level: Logger.Level,
message: Logger.Message,
error: (any Error)?,
metadata: Logger.Metadata
) {
self.lock.withLockVoid {
self._entries.append(
Entry(
level: level,
message: message,
error: error,
metadata: metadata
)
)
@@ -92,6 +125,18 @@ public struct InMemoryLogHandler: LogHandler {
self.init(logStore: .init())
}
public func log(event: LogEvent) {
// Start with the metadata provider..
var mergedMetadata: Logger.Metadata = self.metadataProvider?.get() ?? [:]
// ..merge in self.metadata, overwriting existing keys
mergedMetadata = mergedMetadata.merging(self.metadata) { $1 }
// ..merge in metadata from this log call, overwriting existing keys
mergedMetadata = mergedMetadata.merging(event.metadata ?? [:]) { $1 }
self.logStore.append(level: event.level, message: event.message, error: event.error, metadata: mergedMetadata)
}
@available(*, deprecated, renamed: "log(event:)")
public func log(
level: Logger.Level,
message: Logger.Message,
@@ -101,14 +146,17 @@ public struct InMemoryLogHandler: LogHandler {
function: String,
line: UInt
) {
// Start with the metadata provider..
var mergedMetadata: Logger.Metadata = self.metadataProvider?.get() ?? [:]
// ..merge in self.metadata, overwriting existing keys
mergedMetadata = mergedMetadata.merging(self.metadata) { $1 }
// ..merge in metadata from this log call, overwriting existing keys
mergedMetadata = mergedMetadata.merging(metadata ?? [:]) { $1 }
self.logStore.append(level: level, message: message, metadata: mergedMetadata)
self.log(
event: LogEvent(
level: level,
message: message,
metadata: metadata,
source: source,
file: file,
function: function,
line: line
)
)
}
public subscript(metadataKey key: String) -> Logger.Metadata.Value? {
@@ -0,0 +1,416 @@
# SLG-0003: Support for Attaching Errors to Log Entries
Add standardized way of attaching data from `Error` instances to log entries.
## Overview
- Proposal: SLG-0003
- Author(s): [Samuel Murray](https://github.com/samuelmurray)
- Status: **Approved**
- Issue: [apple/swift-log#291](https://github.com/apple/swift-log/issues/291)
- Implementation:
- [apple/swift-log#425](https://github.com/apple/swift-log/pull/425)
- Related links:
- [Lightweight proposals process description](https://github.com/apple/swift-log/blob/main/Sources/Logging/Docs.docc/Proposals/Proposals.md)
- [First attempt at solution](https://github.com/apple/swift-log/pull/384)
### Introduction
Add new methods on `Logger` that accept an `Error` instance, which is passed as-is to the underlying `LogHandler`. To ensure backwards compatibility and a smooth adoption, a default implementation where the error is serialized into `MetadataValue`s is provided.
### Motivation
SwiftLog advocates for the use of _structured logging_, which in its implementation is achieved by using the `metadata` attribute in the log methods. This is important since it allows for automated tools to parse the logs and extract metadata values for filtering and/or visualization. When logging in a catch-block, it often makes sense to attach some information from the thrown `Error` in the log post, so as to capture the root cause.
```swift
do {
try someThrowingFunc()
} catch {
logger.warning("Something went wrong") // Want to somehow attach information about the error
}
```
Currently, there is no standardized way of doing this. The simplest way to do it would be to simply attach the stringified error to the message.
```swift
logger.warning("Something went wrong: \(error)")
```
This of course is not _structured_, so a better way would be:
```swift
logger.warning("Something went wrong", metadata: ["error": "\(error)"])
```
However, since there is no clear preference for what metadata key to use, it is likely that different code bases use variations of the above. This makes it hard for automated tools to extract error information, since there is no single key to look for.
Additionally, there is more information that we could extract from the error, such as the type name.
```swift
logger.warning("Something went wrong", metadata: ["error.message": "\(error)", "error.type": "\(String(reflecting: type(of: error)))"])
```
The above is a reasonable way to log a generic error, but it is unlikely that everyone will use the same metadata keys. It is also quite a lot of code, for something that feels like it should be easy to do - i.e. attach an error to a log.
Finally, even if you log errors in a consistent way in your code, you do not control logs generated in other modules/packages that you use. In practice, this makes it so that different parts of your application could log error information under different keys, which, again, makes it harder for tooling.
### Proposed solution
The solution we propose is to add convenience methods in `Logger` that allows the caller to do the following:
```swift
do {
try someThrowingFunc()
} catch {
logger.warning("Something went wrong", error: error)
}
```
The error would get passed as-is to the underlying `LogHandler`, which is free to serialize it in an appropriate way. We propose that such convenience methods are added for all log methods (even if it arguably makes less sense for e.g. `trace` and `debug` than `warning`).
There are two clear gains from this:
* It is obvious for the caller _how_ to attach an `Error` to a log (and the caller code also looks cleaner).
* `LogHandler`s are free to serialize the `Error` in an way appropriate to that handler.
A `LogHandler` instance can access the `Error` using a new protocol method. A typical `LogHandler` implementation could be to extract the string representation and type name, and serialize it as metadata.
```swift
struct ErrorLogHandler: LogHandler {
func log(
level: Logger.Level,
message: Logger.Message,
error: (any Error)?,
metadata: Logger.Metadata?,
source: String,
file: String,
function: String,
line: UInt
) {
var metadata = metadata ?? [:]
if let error {
metadata.merge([
"error.message": "\(error)",
"error.type": "\(String(reflecting: type(of: error)))",
]) { $1 }
}
// ...
}
/* ... */
}
```
As we extend the API of both `Logger` and `LogHandler`, we need to ensure compatibility with existing solutions on both sides. Specifically, users should be able to use the new `Logger` methods with existing `LogHandler`s, and get a reasonable serialization of the error. Otherwise, early adopters would have to manually serialize it _in addition to_ passing it using the new argument, until all `LogHandler`s have been updated. To achieve this, we add a default implementation on the `LogHandler` method, that serializes the `Error` as metadata, similar to the example above.
### Detailed design
The proposed solution is to add a new overload for each log method (`trace`, ..., `critical`) that accepts an `Error` as its second argument, as well as a new overload for `Logger.log`, that accepts an `Error` as its third argument.
```swift
extension Logger {
/// Log a message at the 'trace' log level with the source that you provide.
///
/// If ``Level/trace`` is at least as severe as this logger's ``logLevel`` the system logs the message;
/// otherwise nothing will happen.
///
/// - parameters:
/// - message: The message to be logged. The `message` parameter supports any string interpolation literal.
/// - error: An `Error` to attach to this log message.
/// - metadata: One-off metadata to attach to this log message.
/// - source: The source this log message originates from. The value defaults
/// to the module that emits the log message.
/// - file: The file this log message originates from. There's usually no need to pass it explicitly, as it
/// defaults to `#fileID`.
/// - function: The function this log message originates from. There's usually no need to pass it explicitly, as
/// it defaults to `#function`.
/// - line: The line this log message originates from. There's usually no need to pass it explicitly, as it
/// defaults to `#line`.
@inlinable
public func trace(
_ message: @autoclosure () -> Logger.Message,
error: (any Error)?,
metadata: @autoclosure () -> Logger.Metadata? = nil,
source: @autoclosure () -> String? = nil,
file: String = #fileID,
function: String = #function,
line: UInt = #line
)
/// Log a message at the 'debug' log level with the source that you provide.
///
/// If ``Level/debug`` is at least as severe as this logger's ``logLevel`` the system logs the message;
/// otherwise nothing will happen.
///
/// - parameters:
/// - message: The message to be logged. The `message` parameter supports any string interpolation literal.
/// - error: An `Error` to attach to this log message.
/// - metadata: One-off metadata to attach to this log message.
/// - source: The source this log message originates from. The value defaults
/// to the module that emits the log message.
/// - file: The file this log message originates from. There's usually no need to pass it explicitly, as it
/// defaults to `#fileID`.
/// - function: The function this log message originates from. There's usually no need to pass it explicitly, as
/// it defaults to `#function`.
/// - line: The line this log message originates from. There's usually no need to pass it explicitly, as it
/// defaults to `#line`.
@inlinable
public func debug(
_ message: @autoclosure () -> Logger.Message,
error: (any Error)?,
metadata: @autoclosure () -> Logger.Metadata? = nil,
source: @autoclosure () -> String? = nil,
file: String = #fileID,
function: String = #function,
line: UInt = #line
)
/// Log a message at the 'info' log level with the source that you provide.
///
/// If ``Level/info`` is at least as severe as this logger's ``logLevel`` the system logs the message;
/// otherwise nothing will happen.
///
/// - parameters:
/// - message: The message to be logged. The `message` parameter supports any string interpolation literal.
/// - error: An `Error` to attach to this log message.
/// - metadata: One-off metadata to attach to this log message.
/// - source: The source this log message originates from. The value defaults
/// to the module that emits the log message.
/// - file: The file this log message originates from. There's usually no need to pass it explicitly, as it
/// defaults to `#fileID`.
/// - function: The function this log message originates from. There's usually no need to pass it explicitly, as
/// it defaults to `#function`.
/// - line: The line this log message originates from. There's usually no need to pass it explicitly, as it
/// defaults to `#line`.
@inlinable
public func info(
_ message: @autoclosure () -> Logger.Message,
error: (any Error)?,
metadata: @autoclosure () -> Logger.Metadata? = nil,
source: @autoclosure () -> String? = nil,
file: String = #fileID,
function: String = #function,
line: UInt = #line
)
/// Log a message at the 'notice' log level with the source that you provide.
///
/// If ``Level/notice`` is at least as severe as this logger's ``logLevel`` the system logs the message;
/// otherwise nothing will happen.
///
/// - parameters:
/// - message: The message to be logged. The `message` parameter supports any string interpolation literal.
/// - error: An `Error` to attach to this log message.
/// - metadata: One-off metadata to attach to this log message.
/// - source: The source this log message originates from. The value defaults
/// to the module that emits the log message.
/// - file: The file this log message originates from. There's usually no need to pass it explicitly, as it
/// defaults to `#fileID`.
/// - function: The function this log message originates from. There's usually no need to pass it explicitly, as
/// it defaults to `#function`.
/// - line: The line this log message originates from. There's usually no need to pass it explicitly, as it
/// defaults to `#line`.
@inlinable
public func notice(
_ message: @autoclosure () -> Logger.Message,
error: (any Error)?,
metadata: @autoclosure () -> Logger.Metadata? = nil,
source: @autoclosure () -> String? = nil,
file: String = #fileID,
function: String = #function,
line: UInt = #line
)
/// Log a message at the 'warning' log level with the source that you provide.
///
/// If ``Level/warning`` is at least as severe as this logger's ``logLevel`` the system logs the message;
/// otherwise nothing will happen.
///
/// - parameters:
/// - message: The message to be logged. The `message` parameter supports any string interpolation literal.
/// - error: An `Error` to attach to this log message.
/// - metadata: One-off metadata to attach to this log message.
/// - source: The source this log message originates from. The value defaults
/// to the module that emits the log message.
/// - file: The file this log message originates from. There's usually no need to pass it explicitly, as it
/// defaults to `#fileID`.
/// - function: The function this log message originates from. There's usually no need to pass it explicitly, as
/// it defaults to `#function`.
/// - line: The line this log message originates from. There's usually no need to pass it explicitly, as it
/// defaults to `#line`.
@inlinable
public func warning(
_ message: @autoclosure () -> Logger.Message,
error: (any Error)?,
metadata: @autoclosure () -> Logger.Metadata? = nil,
source: @autoclosure () -> String? = nil,
file: String = #fileID,
function: String = #function,
line: UInt = #line
)
/// Log a message at the 'error' log level with the source that you provide.
///
/// If ``Level/error`` is at least as severe as this logger's ``logLevel`` the system logs the message;
/// otherwise nothing will happen.
///
/// - parameters:
/// - message: The message to be logged. The `message` parameter supports any string interpolation literal.
/// - error: An `Error` to attach to this log message.
/// - metadata: One-off metadata to attach to this log message.
/// - source: The source this log message originates from. The value defaults
/// to the module that emits the log message.
/// - file: The file this log message originates from. There's usually no need to pass it explicitly, as it
/// defaults to `#fileID`.
/// - function: The function this log message originates from. There's usually no need to pass it explicitly, as
/// it defaults to `#function`.
/// - line: The line this log message originates from. There's usually no need to pass it explicitly, as it
/// defaults to `#line`.
@inlinable
public func error(
_ message: @autoclosure () -> Logger.Message,
error: (any Error)?,
metadata: @autoclosure () -> Logger.Metadata? = nil,
source: @autoclosure () -> String? = nil,
file: String = #fileID,
function: String = #function,
line: UInt = #line
)
/// Log a message at the 'critical' log level with the source that you provide.
///
/// If ``Level/critical`` is at least as severe as this logger's ``logLevel`` the system logs the message;
/// otherwise nothing will happen.
///
/// - parameters:
/// - message: The message to be logged. The `message` parameter supports any string interpolation literal.
/// - error: An `Error` to attach to this log message.
/// - metadata: One-off metadata to attach to this log message.
/// - source: The source this log message originates from. The value defaults
/// to the module that emits the log message.
/// - file: The file this log message originates from. There's usually no need to pass it explicitly, as it
/// defaults to `#fileID`.
/// - function: The function this log message originates from. There's usually no need to pass it explicitly, as
/// it defaults to `#function`.
/// - line: The line this log message originates from. There's usually no need to pass it explicitly, as it
/// defaults to `#line`.
@inlinable
public func critical(
_ message: @autoclosure () -> Logger.Message,
error: (any Error)?,
metadata: @autoclosure () -> Logger.Metadata? = nil,
source: @autoclosure () -> String? = nil,
file: String = #fileID,
function: String = #function,
line: UInt = #line
)
/// Log a message using the log level and source that you provide.
///
/// If the `logLevel` passed to this method is more severe than the `Logger`'s ``logLevel``, the library
/// logs the message, otherwise nothing will happen.
///
/// - parameters:
/// - level: The severity level of the `message`.
/// - message: The message to be logged. The `message` parameter supports any string interpolation literal.
/// - error: An `Error` to attach to this log message.
/// - metadata: One-off metadata to attach to this log message.
/// - source: The source this log message originates from. The value defaults
/// to the module that emits the log message.
/// - file: The file this log message originates from. There's usually no need to pass it explicitly, as it
/// defaults to `#fileID`.
/// - function: The function this log message originates from. There's usually no need to pass it explicitly, as
/// it defaults to `#function`.
/// - line: The line this log message originates from. There's usually no need to pass it explicitly, as it
/// defaults to `#line`.
@inlinable
public func log(
level: Logger.Level,
_ message: @autoclosure () -> Logger.Message,
error: (any Error)?,
metadata: @autoclosure () -> Logger.Metadata? = nil,
source: @autoclosure () -> String? = nil,
file: String = #fileID,
function: String = #function,
line: UInt = #line
)
}
```
A new method is also added to `LogHandler`, which receives the `Error` passed to `Logger`.
```swift
protocol LogHandler {
/// The library calls this method when a log handler must emit a log message.
///
/// There is no need for the `LogHandler` to check if the `level` is above or
/// below the configured `logLevel` as `Logger` already performed this check and
/// determined that a message should be logged.
///
/// - Parameters:
/// - level: The log level of the message.
/// - message: The message to log. To obtain a `String` representation call `message.description`.
/// - error: The `Error` associated to this log message.
/// - metadata: The metadata associated to this log message.
/// - source: The source where the log message originated, for example the logging module.
/// - file: The file this log message originates from.
/// - function: The function this log message originates from.
/// - line: The line this log message originates from.
func log(
level: Logger.Level,
message: Logger.Message,
error: (any Error)?,
metadata: Logger.Metadata?,
source: String,
file: String,
function: String,
line: UInt
)
}
```
A default implementation is included via an extension method, that calls the existing `log` function. This is to ensure backwards compatibility, and is similar to how `source` was added. The default implementation will serialize the `Error`, extracting its string representation and fully qualified type name, and add those to the metadata under the keys `"error.message"` and `"error.type"` respectively.
A draft implementation can be found in [apple/swift-log#425](https://github.com/apple/swift-log/pull/425).
We choose the keys `"error.message"` and `"error.type"` since they correspond to what [ECS](https://www.elastic.co/docs/reference/ecs/ecs-error) and [OpenTelemetry](https://opentelemetry.io/docs/specs/semconv/registry/attributes/error/#error-type) use. However, we propose that the metadata keys used should **not** be considered stable or part of the `swift-log` API. Instead, if a `LogHandler` wants to use separate keys, it should implement the new protocol method, rather than re-map the metadata keys.
### API stability
The proposed additions are fully backwards compatible, meaning that all existing code will continue to function as is. Additionally, a user of `Logger` can start using the new convenience methods, without any modifications of the `LogHandler`, thanks to the default implementation and since a `LogHandler` is already expected to handle `Metadata`.
However, when using the default implementation, a potential metadata collision exists when an `Error` is passed via the new methods while the same keys (`"error.message"`, `"error.type"`) are present in metadata:
```swift
logger.warning("Something went wrong", error: error, metadata: ["error.message": "some other info"])
```
We recommend that the `error` parameter takes precedence in such cases, with conflicting metadata values discarded. This aligns with the principle that explicit `error:` parameters represent primary data, while the same keys in metadata are likely incidental. In practice, we don't expect callers to deliberately pass conflicting error information.
Conversely, a `LogHandler` can implement the new protocol method, and still function with existing users of `Logger` - the `error` parameter will then always be `nil`.
### Future directions
#### recordError
If `swift-log` develops better support for scoped loggers, it might be possible to add a `recordError` method on `Logger`, that would attach the `Error` to all logs in that scope.
### Alternatives considered
#### Standardized Error metadata via Logger convenience
The first proposed solution was to treat the new `Logger` methods as "convenience methods", that simply serialized the `Error` as metadata and did not pass the raw `Error` to `LogHandler`. The end result was similar to the currently proposed default implementation in `LogHandler`. In this solution, the metadata keys (`"error.message"` and `"error.type"`) were considered stable and part of the API, since that allowed for `LogHandler` implementations to re-map the keys (e.g. to `"err.*"`).
Ultimately, this was declined in favor of the current proposal. While the metadata based solution was simple, it lacked the flexibility that passing the raw `Error` allows for.
#### recordError convenience method
In the first iteration, we considered adding a new convenience method `recordError` on `Logger`, that would take an `Error`, serialize it, and add to the metadata on the `Logger`. This would primarily have been useful for when a `Logger` instance were passed down a call hierarchy and the `Error` metadata were relevant further down. However, it doesn't work well with the current proposal, since the serialization happens at a later stage.
#### Using .stringConvertible to pass Error to LogHandler
An alternative way to let the `LogHandler` get access to the raw `Error` would be to use the existing `.stringConvertible` enum case of `MetadataValue`. By putting the `Error` under a well-known metadata key (such as `"error"`), a `LogHandler` could get access to it, without any changes to the `LogHandler` protocol. However, this would only work for `Error`s that conform to `CustomStringConvertible`.
#### some Error vs any Error
The error argument in `Logger` was considered to be `some Error` rather than `any Error`. Ultimately, `any Error` was preferred. This is because in most typical use cases (e.g. general catch blocks), the error is an existential, so by using `some Error` we would get a slight performance penalty.
@@ -0,0 +1,467 @@
# SLG-0004: Metadata values privacy attribute
Introduce an attributed metadata system that allows attaching attributes to metadata values, with privacy level as the first attribute enabling developers to mark metadata as `.private` or `.public`.
## Overview
- Proposal: SLG-0004
- Author(s): [Vladimir Kukushkin](https://github.com/kukushechkin)
- Status: **Deferred**
- Issue: https://github.com/apple/swift-log/issues/204
- Implementation:
- [apple/swift-log#418](https://github.com/apple/swift-log/pull/418)
- Related links:
- [Lightweight proposals process description](https://github.com/apple/swift-log/blob/main/Sources/Logging/Docs.docc/Proposals/Proposals.md)
- [Review discussion](https://forums.swift.org/t/proposal-slg-0004-metadata-values-privacy-attribute/85249/16)
### Introduction
This proposal introduces an **attributed metadata system** that allows attaching attributes to metadata values. Privacy level is the first concrete attribute, enabling developers to mark metadata values as `.private` or `.public` so `LogHandler` implementations can redact sensitive values before logging.
### Motivation
SwiftLog lacks a mechanism to attach attributes to metadata values. This prevents marking metadata as sensitive and limits future extensibility for other metadata attributes.
Applications need privacy controls for:
- Compliance with privacy regulations.
- Backend integration with privacy-aware logging systems.
- Systematic control over what data appears in logs.
Beyond privacy, an attributed metadata system provides a foundation for future extensions such as retention policies, data classification, or other metadata attributes.
### Proposed solution
Introduce new `AttributedMetadata` data type, enabling users to mark metadata values with `.private` and `.public` privacy label:
```swift
// Add privacy level to metadata values obtained through a metadata provider
let serviceIp = "127.0.0.1"
var logger = Logger(label: "my-app", metadataProvider: .init {[
"service.ip": "\(serviceIp, privacy: .private)",
]})
// Add privacy level to metadata values attached to a `Loghandler` instance
let requestId = UUID()
logger[attributedMetadataKey: "request.id"] = "\(requestId, privacy: .private)"
// Mark sensitive values as private and non-sensitive as public at logging call site
let userId = UUID()
let action = "login"
logger.info("User action", attributedMetadata: [
"user.id": "\(userId, privacy: .private)",
"action": "\(action)" // default is .public for ease of adoption
])
```
This allows `Logger` users to mark certain metadata values as "I only trust LogHandlers, who know how to handle sensitive data, to see this value".
### Detailed design
#### Attributed Metadata
To support privacy labels and enable future extensibility, we introduce a generalized **attributed metadata** system. This provides a foundation for attaching arbitrary attributes to metadata values, with privacy labels being the first concrete use case:
```swift
// Plain metadata (existing)
let metadataValue: MetadataValue = .string("value")
logger.info("Message", metadata: ["key": metadataValue])
// Attributed metadata (new) — a value with attributes
logger.info("Message", attributedMetadata: [
"key": AttributedMetadataValue(value: metadataValue, attributes: ...)
])
```
The attributed metadata system instroduces new public API:
1. **`AttributedMetadataValue`**: Wraps a standard `MetadataValue` with associated attributes.
2. **`MetadataValueAttributes`**: Container for attributes.
3. **`AttributedMetadata`**: Dictionary type mapping `String` keys to attributed values.
4. **Parallel logging API**: New log methods accepting `attributedMetadata` parameter.
This design separates the transport mechanism (attributed metadata) from specific attribute semantics (privacy labels), allowing future extensions without breaking existing attributed metadata code.
#### Privacy levels
With attributed metadata as the foundation, privacy labels are implemented as the first concrete attribute:
```swift
extension Logger {
/// A metadata value with associated privacy attributes.
///
/// `AttributedMetadataValue` wraps a standard `MetadataValue` with privacy attributes,
/// allowing you to mark metadata as private or public for privacy-aware logging.
///
/// ## Creating Attributed Metadata
///
/// Use string interpolation with privacy parameter:
///
/// ```swift
/// // Preferred: String interpolation with privacy level specified
/// let userId = "12345"
/// let action = "login"
/// logger.info("User action", attributedMetadata: [
/// "user.id": "\(userId, privacy: .private)",
/// "action": "\(action, privacy: .public)" // explicit .public for non-sensitive data
/// ])
///
/// // Direct creation
/// let attributed = Logger.AttributedMetadataValue(
/// .string("12345"),
/// privacy: .private
/// )
/// ```
///
/// ## Important Limitations
///
/// - **No nested privacy**: When marking a dictionary or array as private, all contained
/// values are treated with the same privacy level. Fine-grained privacy within nested
/// structures is not currently supported.
///
/// - **Metadata only**: Privacy levels apply only to metadata values, not to log messages.
/// Avoid including sensitive data in log message string interpolation.
public struct AttributedMetadataValue: CustomStringConvertible, Sendable {
/// The redaction marker used for private values.
internal static let redactionMarker = "<private>"
public let value: MetadataValue
public let attributes: MetadataValueAttributes
/// String representation redacts private values to the redaction marker.
public var description: String {
attributes.privacy == .public ? value.description : Self.redactionMarker
}
public init(_ value: MetadataValue, attributes: MetadataValueAttributes)
public init(_ value: MetadataValue, privacy: PrivacyLevel)
}
extension AttributedMetadataValue {
/// Attributes that can be associated with metadata values.
public struct MetadataValueAttributes: CustomStringConvertible, Hashable, Sendable {
/// Privacy level for metadata values.
///
/// Privacy levels allow you to mark metadata values as either private (sensitive data that should be
/// protected) or public (safe to log in any context).
///
/// ## Usage
///
/// Use string interpolation with the privacy parameter to create attributed metadata values:
///
/// ```swift
/// let userId = "12345"
/// let action = "login"
/// logger.info("User action", attributedMetadata: [
/// "user.id": "\(userId, privacy: .private)",
/// "action": "\(action, privacy: .public)",
/// "ip": "\(ipAddress, privacy: .private)"
/// ])
/// ```
@frozen
public enum PrivacyLevel: Sendable, CaseIterable, Equatable, Hashable, CustomStringConvertible {
/// Private data that should be redacted in non-secure contexts.
case `private`
/// Public data safe for general logging.
case `public`
}
/// The privacy level of this metadata value.
public var privacy: PrivacyLevel
/// Create metadata value attributes with the specified privacy level.
///
/// - Parameter privacy: The privacy level for this metadata. Defaults to `.public`.
public init(privacy: PrivacyLevel = .public)
}
/// The underlying metadata value without privacy attributes.
public var value: MetadataValue
/// The privacy attributes associated with this metadata value.
public var attributes: MetadataValueAttributes
/// Create an attributed metadata value with the specified attributes.
///
/// - Parameters:
/// - value: The metadata value to wrap.
/// - attributes: The attributes for this value.
public init(_ value: MetadataValue, attributes: MetadataValueAttributes)
/// Convenience initializer for creating attributed metadata with a privacy level.
///
/// - Parameters:
/// - value: The metadata value to wrap.
/// - privacy: The privacy level for this value.
public init(_ value: MetadataValue, privacy: PrivacyLevel)
}
/// Metadata dictionary with privacy attributes.
///
/// A dictionary mapping string keys to ``AttributedMetadataValue`` instances, used with
/// the `attributedMetadata` parameter of logging methods.
///
/// ## Example
///
/// ```swift
/// let userId = "12345"
/// let requestId = "req-789"
/// let metadata: Logger.AttributedMetadata = [
/// "user.id": "\(userId, privacy: .private)",
/// "request.id": "\(requestId, privacy: .public)",
/// "action": "purchase" // String literal defaults to .public
/// ]
/// logger.info("User action", attributedMetadata: metadata)
/// ```
public typealias AttributedMetadata = [String: AttributedMetadataValue]
}
```
#### String interpolation for attributed metadata
```swift
extension Logger.AttributedMetadataValue: ExpressibleByStringLiteral, ExpressibleByStringInterpolation {
/// Custom string interpolation that captures privacy levels from interpolated values.
///
/// This enables syntax like:
/// ```swift
/// logger.info("User action", attributedMetadata: [
/// "user.id": "\(userId, privacy: .private)",
/// "action": "\(action, privacy: .public)"
/// ])
/// ```
public struct StringInterpolation: StringInterpolationProtocol {
public init(literalCapacity: Int, interpolationCount: Int)
public mutating func appendLiteral(_ literal: String)
/// Interpolation with explicit privacy parameter.
public mutating func appendInterpolation<T>(_ value: T, privacy: Logger.PrivacyLevel = .public)
where T: CustomStringConvertible
}
/// Creates an attributed metadata value from a string literal (defaults to .public).
public init(stringLiteral value: String)
/// Creates an attributed metadata value from string interpolation.
public init(stringInterpolation: StringInterpolation)
}
```
#### New Logger methods
```swift
extension Logger {
// Attributed metadata storage
var attributedMetadata: Logger.AttributedMetadata { get set }
subscript(attributedMetadataKey: String) -> Logger.AttributedMetadataValue? { get set }
// Log family of methods
public func log(level: Level, _ message: @autoclosure () -> Message,
attributedMetadata: @autoclosure () -> AttributedMetadata?,
source: @autoclosure () -> String? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line)
public func trace(_ message: @autoclosure () -> Message,
attributedMetadata: @autoclosure () -> AttributedMetadata?,
source: @autoclosure () -> String? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line)
public func debug(_ message: @autoclosure () -> Message,
attributedMetadata: @autoclosure () -> AttributedMetadata?,
source: @autoclosure () -> String? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line)
public func info(_ message: @autoclosure () -> Message,
attributedMetadata: @autoclosure () -> AttributedMetadata?,
source: @autoclosure () -> String? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line)
public func notice(_ message: @autoclosure () -> Message,
attributedMetadata: @autoclosure () -> AttributedMetadata?,
source: @autoclosure () -> String? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line)
public func warning(_ message: @autoclosure () -> Message,
attributedMetadata: @autoclosure () -> AttributedMetadata?,
source: @autoclosure () -> String? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line)
public func error(_ message: @autoclosure () -> Message,
attributedMetadata: @autoclosure () -> AttributedMetadata?,
source: @autoclosure () -> String? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line)
public func critical(_ message: @autoclosure () -> Message,
attributedMetadata: @autoclosure () -> AttributedMetadata?,
source: @autoclosure () -> String? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line)
}
```
#### AttributedMetadata support in LogHandler protocol
```swift
protocol LogHandler {
func log(level: Logger.Level, message: Logger.Message,
attributedMetadata: Logger.AttributedMetadata?, source: String,
file: String, function: String, line: UInt)
var attributedMetadata: Logger.AttributedMetadata { get set }
subscript(attributedMetadataKey: String) -> Logger.AttributedMetadataValue? { get set }
}
// Default implementations provided for backward compatibility
extension LogHandler {
// Default attributed metadata log method - redacts private values using helper
public func log(level: Logger.Level, message: Logger.Message,
attributedMetadata: Logger.AttributedMetadata?,
source: String, file: String, function: String, line: UInt) {
let processedMetadata = attributedMetadata.flatMap(Self.attributedToPlain)
self.log(level: level, message: message, metadata: processedMetadata,
source: source, file: file, function: function, line: line)
}
// Default attributed metadata storage - uses helpers for conversion
public var attributedMetadata: Logger.AttributedMetadata {
get { self.metadata.mapValues(Self.plainToAttributed) }
set { self.metadata = newValue.mapValues(Self.attributedToPlain) }
}
public subscript(attributedMetadataKey key: String) -> Logger.AttributedMetadataValue? {
get {
guard let plainValue = self[metadataKey: key] else { return nil }
return Self.plainToAttributed(plainValue)
}
set {
if let attributedValue = newValue {
self[metadataKey: key] = Self.attributedToPlain(attributedValue)
} else {
self[metadataKey: key] = nil
}
}
}
}
```
#### AttributedMetadata support in MetadataProvider
```swift
extension Logger.MetadataProvider {
/// Creates a new metadata provider that returns attributed metadata.
///
/// Attributed metadata providers allow you to specify privacy levels and other
/// attributes for each metadata value. When accessed through the plain ``get()``
/// method (for backward compatibility), private values are redacted to `"<private>"`.
///
/// ### Example
///
/// ```swift
/// let provider = Logger.MetadataProvider {
/// [
/// "request-id": "\(RequestContext.current.id, privacy: .public)",
/// "user-id": "\(RequestContext.current.userId, privacy: .private)"
/// ]
/// }
/// ```
///
/// - Parameter provideAttributed: A closure that extracts attributed metadata from the current execution context.
/// - Returns: A metadata provider that returns attributed metadata.
@_disfavoredOverload
public static func init(_ provideAttributed: @escaping @Sendable () -> AttributedMetadata) -> MetadataProvider
/// Returns attributed metadata if this is an attributed provider.
///
/// Handlers supporting attributed metadata should call this first,
/// falling back to `get()` if it returns nil.
public func getAttributed() -> AttributedMetadata?
}
```
### API stability
- All existing APIs unchanged.
- Plain and attributed metadata APIs coexist.
- No deprecation planned.
- Adoption is optional and incremental on both application and Log Handler sides.
- Default implementation ensures existing handlers work; logging private metadata is an application concern requiring a compatible `LogHandler`.
### Future directions
- Add more attributes (e.g., value data type, etc) and potential future unification of plain and attributed metadata APIs.
- Introduce "custom attributes", allowing applications to define application-specific attributes to work with application-specific log handlers.
### Alternatives considered
1. **Key-based redaction:** Configure which keys should be treated as private rather than marking each value:
```swift
logger.privateKeys = ["user.id", "password", "email"]
logger.info("User action", metadata: [
"user.id": "12345", // Automatically private
"action": "login" // Automatically public
])
```
Advantages:
- Simpler API (no new types).
- Centralized configuration.
- Safer at scale (new sensitive fields update all logs automatically).
- Easier migration.
**Not chosen because:**
- **Privacy belongs to data, not identifiers:** The same private data might be logged under different keys ("email", "user.email", "contact"), and the same key might contain different data with different privacy requirements in different contexts. Key-based redaction creates a synchronization problem—developers must maintain a separate list of "private keys" that stays in sync with actual logging code across the codebase, with no compile-time or review-time verification.
- **Code review visibility:** With value-based privacy, reviewers see privacy decisions at the call site: `"email": user.email.private()` makes it immediately clear that data is sensitive. With key-based redaction, reviewers must cross-reference a separate configuration file, making security review significantly harder.
- **No synchronization needed:** Value-based privacy is self-contained—privacy travels with the data at the point of use. No separate configuration to maintain, no risk of configuration drift, no runtime surprises when a key is missing from the private keys list.
- **Pattern complexity:** Supporting patterns/regex adds complexity and potential performance concerns.
The current design prioritizes **explicitness and data-centric privacy** over **configuration-based simplicity**. Privacy decisions are made where data is logged, making them visible during code review and keeping privacy attributes coupled to the data they protect.
2. **Convenience methods (`.private()` and `.public()`):** Add extension methods to `String` and `MetadataValue` for creating attributed metadata:
```swift
extension String {
public func `private`() -> Logger.AttributedMetadataValue
public func `public`() -> Logger.AttributedMetadataValue
}
logger.info("User action", attributedMetadata: [
"user.id": "12345".private(),
"action": "login".public()
])
```
**Not chosen because:**
- **Consistency with existing patterns:** `Logger.Message` and `Logger.MetadataValue` already use string interpolation extensively.
- **Natural syntax:** `"\(value, privacy: .private)"` reads clearly and fits Swift's interpolation conventions.
- **Less API surface:** No need for multiple extension methods across different types.
Metadata values already support string interpolation in SwiftLog. Rather than inventing additional API surface area with new methods, we leverage the existing string interpolation infrastructure with a custom `StringInterpolation` type. This provides:
3. **Default privacy level to `.private`:** Make attributed metadata values default to `.private` privacy level when no explicit privacy parameter is provided:
```swift
logger.info("User action", attributedMetadata: [
"user.id": "\(userId, privacy: .private)", // Explicit private (redundant with default)
"action": "\(action, privacy: .public)" // Must explicitly mark as public
])
```
Advantages:
- Security-by-default: requires explicit opt-out for logging non-sensitive data.
- Safer for accidental inclusion of sensitive data.
**Not chosen because:**
Privacy should be an explicit opt-in action from the user. The current design (defaulting to `.public`) prioritizes **ease of adoption** over **security-by-default**:
- Easier adoption - less boilerplate for common non-sensitive metadata.
- Matches the mental model that "most data is safe to log".
- Lower friction for migration from plain metadata.
- Forces developers to think about privacy only for sensitive data, rather than requiring `.public` annotations everywhere.
4. **Pass all metadata to non-privacy-aware handlers:** Security risk; current design filters private data by default.
5. **Message-level privacy:** Less granular than metadata-level privacy and requires message handling changes.
6. **Privacy level handling configuration** to be an attribute of the `Logger` instead of LogHandler configuration. This would centralize the configuration across various `LogHandler` implementations. However, existing `LogHandler` already have configurations and they might want to customize the behavior even further.
7. **Handler metadata merging:** LogHandlers are responsible for merging their own `metadata` property, `metadataProvider` output, and the explicit `attributedMetadata` parameter. This is consistent with how plain metadata works - handlers control merging. Plain handler metadata and provider values should be treated as public (`.public` privacy level). Attributed metadata from the log call takes precedence.
8. **Add a third `.auto`/`.default` privacy attribute value:** Libraries and applications can mark a metadata value as `privacy: .default` and rely on the `LogHandler` to configure what the default is. While this might've been a solution to overcome default `.public` values for all the attributed metadata, in reality it is confusing from the semantic point of view. If someone wants to mark something as `.default`, because this _might_ be sensitive, then it should be marked as `.private` or not logged at all. If something does not need to be marked as `.private`, then it is `.public`. A custom `LogHandler` with an allow list of metadata keys/messages/modules can be used as an escape hatch in case the application does not trust its dependencies.
@@ -0,0 +1,180 @@
# SLG-0005: `LogEvent`-based `LogHandler` API
Replace the flat-parameter `log(level:message:metadata:source:file:function:line:)` method on `LogHandler` with
`log(event: LogEvent)`, enabling forward-compatible evolution of the `LogHandler` interface without breaking existing
handler implementations.
## Overview
- Proposal: SLG-0005
- Author(s): [Vladimir Kukushkin](https://github.com/kukushechkin)
- Status: **Approved**
- Issue: [apple/swift-log#421](https://github.com/apple/swift-log/issues/421)
- Implementation:
- [apple/swift-log#423](https://github.com/apple/swift-log/pull/423)
- Related links:
- [Lightweight proposals process description](https://github.com/apple/swift-log/blob/main/Sources/Logging/Docs.docc/Proposals/Proposals.md)
- [SLG-0003: Standardized Error Metadata via Logger Convenience](https://github.com/apple/swift-log/blob/main/Sources/Logging/Docs.docc/Proposals/SLG-0003.md)
### Introduction
Introduce `LogEvent` that bundles all log-statement data, and replace the flat-parameter
`log(level:message:metadata:source:file:function:line:)` method on `LogHandler` with `log(event: LogEvent)`.
### Motivation
The `LogHandler` protocol currently requires implementing a single method with seven parameters:
```swift
func log(
level: Logger.Level,
message: Logger.Message,
metadata: Logger.Metadata?,
source: String,
file: String,
function: String,
line: UInt
)
```
Every time a new piece of data needs to be forwarded from a log call site to the handler — an error, or a richer metadata type — the only options are:
- **Add a new parameter to the existing method.** This is a source-breaking change: every existing `LogHandler`
implementation across the entire Swift ecosystem must be updated simultaneously.
- **Add a new `Logger` overload.** This requires 2 parallel APIs to coexist until the old one can be safely deprecated.
### Proposed solution
Introduce `LogEvent`, a `struct` that carries all the data associated with a single log statement. `LogEvent` is
a handler-side type: it is constructed by `Logger._log` and passed to `LogHandler`. The public `Logger` call-site
API — `logger.info(...)`, `logger.log(level:...)` and so on — is unchanged.
The `LogHandler` protocol gains a new required method `log(event: LogEvent)`, while the old flat-parameter method
is deprecated.
For existing handlers, a default implementation of `log(event:)` forwards to the old method, so no code changes
are required to keep existing implementations working. Handlers that want to take advantage of new fields added to
`LogEvent` in future proposals implement `log(event:)`.
### Detailed design
#### New `LogEvent` type
A new top-level `struct` in the `Logging` module:
```swift
public struct LogEvent: Sendable {
public var level: Logger.Level
public var message: Logger.Message
private var _metadata: Logger.Metadata?
public var metadata: Logger.Metadata? {
get { self._metadata }
set { self._metadata = newValue }
}
public var source: String
public var file: String
public var function: String
public var line: UInt
public init(
level: Logger.Level,
message: Logger.Message,
metadata: Logger.Metadata?,
source: String,
file: String,
function: String,
line: UInt
)
}
```
#### Updated `LogHandler` protocol
```swift
public protocol LogHandler: _SwiftLogSendableLogHandler {
/// The library calls this method when a log handler must emit a log message.
///
/// There is no need for the `LogHandler` to check if the level is above or below the configured `logLevel`
/// as `Logger` already performed this check and determined that a message should be logged.
///
/// - Parameter event: The log event containing the level, message, metadata, and source location.
func log(event: LogEvent)
/// Please do _not_ implement this method when you create a `LogHandler` implementation.
/// Implement ``log(event:)`` instead.
///
/// - Parameters:
/// - level: The log level of the message.
/// - message: The message to log. To obtain a `String` representation call `message.description`.
/// - metadata: The metadata associated to this log message.
/// - source: The source where the log message originated, for example the logging module.
/// - file: The file this log message originates from.
/// - function: The function this log message originates from.
/// - line: The line this log message originates from.
@available(*, deprecated, renamed: "log(event:)")
func log(
level: Logger.Level,
message: Logger.Message,
metadata: Logger.Metadata?,
source: String,
file: String,
function: String,
line: UInt
)
}
```
#### Default implementation
The default for `log(event:)` forwards all event fields to the old flat-parameter method,
preserving the behavior of existing handlers with no source changes required.
The default implementation is marked as deprecated to encourage handler authors to migrate to `log(event:)`.
Handlers that still rely on the forwarding bridge will see a deprecation warning at compile time, signaling that
they should adopt the new method directly.
```swift
extension LogHandler {
@available(*, deprecated, message: "You should implement this method instead of using the default implementation")
public func log(event: LogEvent) {
self.log(
level: event.level,
message: event.message,
metadata: event.metadata,
source: event.source,
file: event.file,
function: event.function,
line: event.line
)
}
}
```
### API stability
**For existing `Logger` users:** No changes. All existing call sites continue to compile and behave identically.
**For existing `LogHandler` implementations:** Implementations of
`log(level:message:metadata:source:file:function:line:)` continue to work without any source changes. The
default implementation of `log(event:)` forwards to the old method.
### Future directions
Future proposals can add new fields to `LogEvent` with sensible defaults — a richer metadata
type, or an attached `Error` (as a follow-up for [SLG-0003 proposal](https://forums.swift.org/t/proposal-slg-0003-standardized-error-metadata-via-logger-convenience/84518/39)) —
without touching the `LogHandler` protocol and without requiring any changes to
existing handler implementations. This is the primary motivation for this proposal.
The [SLG-0004 proposal](https://github.com/apple/swift-log/pull/416) introduces an `AttributedMetadata` type that wraps
`Logger.Metadata` with additional context. Adding it to `LogEvent` as a new optional field would be
source-compatible, and the existing `metadata` field could become a computed property that projects from
`attributedMetadata` when present, keeping old handlers fully functional without modification.
### Alternatives considered
#### Adding parameters with default values to the existing method
Adding new parameters with default values avoids introducing a new method, but still constitutes a
source-breaking change: every existing `LogHandler` implementation that implements the method explicitly
must add the new parameter. The whole point of this proposal is to avoid that pattern indefinitely.
+26 -13
View File
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift Logging API open source project
//
// Copyright (c) 2018-2019 Apple Inc. and the Swift Logging API project authors
// Copyright (c) 2018-2026 Apple Inc. and the Swift Logging API project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
@@ -16,7 +16,7 @@
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Copyright (c) 2017-2026 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
@@ -58,10 +58,10 @@ package final class Lock {
#if os(Windows)
fileprivate let mutex: UnsafeMutablePointer<SRWLOCK> =
UnsafeMutablePointer.allocate(capacity: 1)
#elseif os(OpenBSD)
#elseif os(FreeBSD) || os(OpenBSD)
fileprivate let mutex: UnsafeMutablePointer<pthread_mutex_t?> =
UnsafeMutablePointer.allocate(capacity: 1)
#else
#elseif (compiler(<6.1) && !os(WASI)) || (compiler(>=6.1) && _runtime(_multithreaded))
fileprivate let mutex: UnsafeMutablePointer<pthread_mutex_t> =
UnsafeMutablePointer.allocate(capacity: 1)
#endif
@@ -70,30 +70,41 @@ package final class Lock {
package init() {
#if os(Windows)
InitializeSRWLock(self.mutex)
#elseif os(OpenBSD)
var attr = pthread_mutexattr_t(bitPattern: 0)
let err = pthread_mutex_init(self.mutex, &attr)
precondition(err == 0, "\(#function) failed in pthread_mutex with error \(err)")
#elseif (compiler(<6.1) && !os(WASI)) || (compiler(>=6.1) && _runtime(_multithreaded))
#if os(FreeBSD) || os(OpenBSD)
var attr = pthread_mutexattr_t(bitPattern: 0)
#else
var attr = pthread_mutexattr_t()
pthread_mutexattr_init(&attr)
#endif
var err = pthread_mutexattr_init(&attr)
precondition(err == 0, "\(#function) failed in pthread_mutexattr_init with error \(err)")
debugOnly {
#if os(FreeBSD) || os(OpenBSD)
pthread_mutexattr_settype(&attr, .init(PTHREAD_MUTEX_ERRORCHECK.rawValue))
#else
pthread_mutexattr_settype(&attr, .init(PTHREAD_MUTEX_ERRORCHECK))
#endif
}
let err = pthread_mutex_init(self.mutex, &attr)
err = pthread_mutex_init(self.mutex, &attr)
precondition(err == 0, "\(#function) failed in pthread_mutex with error \(err)")
// `pthread_mutexattr_t` only lives during init; destroy here instead of deinit.
let attrDestroyErr = pthread_mutexattr_destroy(&attr)
precondition(
attrDestroyErr == 0,
"\(#function) failed in pthread_mutexattr_destroy with error \(attrDestroyErr)"
)
#endif
}
deinit {
#if os(Windows)
// SRWLOCK does not need to be free'd
mutex.deallocate()
#elseif (compiler(<6.1) && !os(WASI)) || (compiler(>=6.1) && _runtime(_multithreaded))
let err = pthread_mutex_destroy(self.mutex)
precondition(err == 0, "\(#function) failed in pthread_mutex with error \(err)")
#endif
mutex.deallocate()
#endif
}
/// Acquire the lock.
@@ -176,6 +187,9 @@ internal final class ReadWriteLock: @unchecked Sendable {
fileprivate let rwlock: UnsafeMutablePointer<SRWLOCK> =
UnsafeMutablePointer.allocate(capacity: 1)
fileprivate var shared: Bool = true
#elseif os(FreeBSD) || os(OpenBSD)
fileprivate let rwlock: UnsafeMutablePointer<pthread_rwlock_t?> =
UnsafeMutablePointer.allocate(capacity: 1)
#else
fileprivate let rwlock: UnsafeMutablePointer<pthread_rwlock_t> =
UnsafeMutablePointer.allocate(capacity: 1)
@@ -193,7 +207,6 @@ internal final class ReadWriteLock: @unchecked Sendable {
deinit {
#if os(Windows)
// SRWLOCK does not need to be free'd
self.rwlock.deallocate()
#elseif (compiler(<6.1) && !os(WASI)) || (compiler(>=6.1) && _runtime(_multithreaded))
let err = pthread_rwlock_destroy(self.rwlock)
+125
View File
@@ -0,0 +1,125 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Logging API open source project
//
// Copyright (c) 2018-2019 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
//
//===----------------------------------------------------------------------===//
/// A log event that contains all the information about a single log statement.
///
/// `LogEvent` is passed to a ``LogHandler`` via ``LogHandler/log(event:)`` and carries every piece of data emitted
/// at the log call site. Handlers may inspect, modify, or forward any of the event's properties.
///
/// All properties are mutable so that handler wrappers (for example ``MultiplexLogHandler``) can rewrite fields
/// such as metadata or source before forwarding to downstream handlers.
public struct LogEvent: Sendable {
/// The log level of this event.
public var level: Logger.Level
/// The message of this event.
public var message: Logger.Message
/// The error associated with this event, if any.
public var error: (any Error)?
/// The metadata associated with this event, if any.
public var metadata: Logger.Metadata? {
get { self._metadata }
set { self._metadata = newValue }
}
private var _metadata: Logger.Metadata?
/// The source where this log event originated, for example the logging module.
///
/// When no explicit source was provided at the call site, this is derived lazily from ``file``
/// every time this property is accessed. Handlers that never read this property pay no
/// allocation cost for source computation.
public var source: String {
@inlinable get { self._source ?? Logger.currentModule(fileID: self.file) }
@inlinable set { self._source = newValue }
}
@usableFromInline
internal var _source: String?
/// The file this log event originates from.
public var file: String
/// The function this log event originates from.
public var function: String
/// The line this log event originates from.
public var line: UInt
/// Creates a new log event.
///
/// - Parameters:
/// - level: The log level of this event.
/// - message: The message of this event.
/// - metadata: The metadata associated with this event, if any.
/// - source: The source where this log event originated. When `nil`, ``source`` is derived lazily
/// from ``file`` on first access so handlers that never read it pay no allocation cost.
/// - file: The file this log event originates from.
/// - function: The function this log event originates from.
/// - line: The line this log event originates from.
public init(
level: Logger.Level,
message: Logger.Message,
metadata: Logger.Metadata?,
source: String?,
file: String,
function: String,
line: UInt
) {
self.init(
level: level,
message: message,
error: nil,
metadata: metadata,
source: source,
file: file,
function: function,
line: line
)
}
/// Creates a new log event.
///
/// - Parameters:
/// - level: The log level of this event.
/// - message: The message of this event.
/// - error: The error associated with this event, if any.
/// - metadata: The metadata associated with this event, if any.
/// - source: The source where this log event originated. When `nil`, ``source`` is derived lazily
/// from ``file`` on first access so handlers that never read it pay no allocation cost.
/// - file: The file this log event originates from.
/// - function: The function this log event originates from.
/// - line: The line this log event originates from.
public init(
level: Logger.Level,
message: Logger.Message,
error: (any Error)?,
metadata: Logger.Metadata?,
source: String?,
file: String,
function: String,
line: UInt
) {
self.level = level
self.message = message
self.error = error
self._metadata = metadata
self._source = source
self.file = file
self.function = function
self.line = line
}
}
+55 -32
View File
@@ -138,9 +138,14 @@ public protocol LogHandler: _SwiftLogSendableLogHandler {
/// The library calls this method when a log handler must emit a log message.
///
/// There is no need for the `LogHandler` to check if the `level` is above or
/// below the configured `logLevel` as `Logger` already performed this check and
/// determined that a message should be logged.
/// There is no need for the `LogHandler` to check if the level is above or below the configured `logLevel`
/// as `Logger` already performed this check and determined that a message should be logged.
///
/// - Parameter event: The log event containing the level, message, metadata, and source location.
func log(event: LogEvent)
/// Please do _not_ implement this method when you create a `LogHandler` implementation.
/// Implement ``log(event:)`` instead.
///
/// - Parameters:
/// - level: The log level of the message.
@@ -150,6 +155,7 @@ public protocol LogHandler: _SwiftLogSendableLogHandler {
/// - file: The file this log message originates from.
/// - function: The function this log message originates from.
/// - line: The line this log message originates from.
@available(*, deprecated, renamed: "log(event:)")
func log(
level: Logger.Level,
message: Logger.Message,
@@ -163,7 +169,7 @@ public protocol LogHandler: _SwiftLogSendableLogHandler {
/// SwiftLog 1.0 log compatibility method.
///
/// Please do _not_ implement this method when you create a LogHandler implementation.
/// Implement `log(level:message:metadata:source:file:function:line:)` instead.
/// Implement ``log(event:)`` instead.
///
/// - Parameters:
/// - level: The log level of the message.
@@ -172,7 +178,7 @@ public protocol LogHandler: _SwiftLogSendableLogHandler {
/// - file: The file this log message originates from.
/// - function: The function this log message originates from.
/// - line: The line this log message originates from.
@available(*, deprecated, renamed: "log(level:message:metadata:source:file:function:line:)")
@available(*, deprecated, renamed: "log(event:)")
func log(
level: Logging.Logger.Level,
message: Logging.Logger.Message,
@@ -218,14 +224,16 @@ extension LogHandler {
#if DEBUG
if LoggingSystem.warnOnceLogHandlerNotSupportedMetadataProvider(Self.self) {
self.log(
level: .warning,
message:
"Attempted to set metadataProvider on \(Self.self) that did not implement support for them. Please contact the log handler maintainer to implement metadata provider support.",
metadata: nil,
source: "Logging",
file: #file,
function: #function,
line: #line
event: LogEvent(
level: .warning,
message:
"Attempted to set metadataProvider on \(Self.self) that did not implement support for them. Please contact the log handler maintainer to implement metadata provider support.",
metadata: nil,
source: "Logging",
file: #file,
function: #function,
line: #line
)
)
}
#endif
@@ -234,16 +242,31 @@ extension LogHandler {
}
extension LogHandler {
/// A default implementation for a log message handler that forwards the source location for the message.
/// - Parameters:
/// - level: The log level of the message.
/// - message: The message to log. To obtain a `String` representation call `message.description`.
/// - metadata: The metadata associated to this log message.
/// - source: The source where the log message originated, for example the logging module.
/// - file: The file this log message originates from.
/// - function: The function this log message originates from.
/// - line: The line this log message originates from.
/// Default implementation of ``log(event:)`` for backward compatibility with handlers that implement the
/// deprecated flat-parameter method.
///
/// Handlers that implement ``log(level:message:metadata:source:file:function:line:)`` continue to work
/// without any source changes; this default forwards the event's fields to that method.
///
/// New handlers should implement ``log(event:)`` directly and rely on this default only as a fallback.
///
/// > Warning: Do not call this default directly. It exists only as a backward-compatibility bridge.
/// Implement ``log(event:)`` in your ``LogHandler`` instead.
@available(*, deprecated, message: "You should implement this method instead of using the default implementation")
public func log(event: LogEvent) {
self.log(
level: event.level,
message: event.message,
metadata: event.metadata,
source: event.source,
file: event.file,
function: event.function,
line: event.line
)
}
/// A default implementation for a log message handler that forwards to the SwiftLog 1.0 compatibility method.
@available(*, deprecated, renamed: "log(event:)")
public func log(
level: Logger.Level,
message: Logger.Message,
@@ -253,18 +276,18 @@ extension LogHandler {
function: String,
line: UInt
) {
self.log(level: level, message: message, metadata: metadata, file: file, function: function, line: line)
self.log(
level: level,
message: message,
metadata: metadata,
file: file,
function: function,
line: line
)
}
/// A default implementation for a log message handler.
/// - Parameters:
/// - level: The log level of the message.
/// - message: The message to log. To obtain a `String` representation call `message.description`.
/// - metadata: The metadata associated to this log message.
/// - file: The file this log message originates from.
/// - function: The function this log message originates from.
/// - line: The line this log message originates from.
@available(*, deprecated, renamed: "log(level:message:metadata:source:file:function:line:)")
/// A default implementation for the SwiftLog 1.0 log message handler.
@available(*, deprecated, renamed: "log(event:)")
public func log(
level: Logging.Logger.Level,
message: Logging.Logger.Message,
File diff suppressed because it is too large. Load diff
@@ -69,6 +69,53 @@ struct InMemoryLogHandlerTests {
)
}
@Test
func errorEquality() throws {
let (logHandler, logger) = self.makeTestLogger()
logger.info("hello", error: TestError.first)
let entry = try #require(logHandler.entries.first)
#expect(
entry
== InMemoryLogHandler.Entry(
level: .info,
message: "hello",
error: TestError.first,
metadata: [:],
)
)
#expect(
entry
!= InMemoryLogHandler.Entry(
level: .info,
message: "hello",
error: nil,
metadata: [:],
)
)
#expect(
entry
!= InMemoryLogHandler.Entry(
level: .info,
message: "hello",
error: TestError.second,
metadata: [:]
)
)
#expect(
entry
!= InMemoryLogHandler.Entry(
level: .info,
message: "hello",
error: Nested.TestError.first,
metadata: [:]
)
)
}
@Test
func clear() {
let (logHandler, logger) = self.makeTestLogger()
@@ -95,4 +142,15 @@ struct InMemoryLogHandlerTests {
)
return (logHandler, logger)
}
enum TestError: Error {
case first
case second
}
struct Nested {
enum TestError: Error {
case first
}
}
}
@@ -41,6 +41,31 @@ struct CompatibilityTest {
testLogging.history.assertExist(level: .error, message: "yes: error", source: "no source")
testLogging.history.assertExist(level: .critical, message: "yes: critical", source: "no source")
}
@available(*, deprecated, message: "Testing deprecated functionality")
@Test func allLogLevelsWorkWithNewerButStillOldLogHandlerWorks() {
let testLogging = NewerButStillOldTestLogging()
var logger = Logger(label: "\(#function)", factory: { testLogging.make(label: $0) })
logger.logLevel = .trace
logger.trace("yes: trace", source: "yes: trace source")
logger.debug("yes: debug", source: "yes: debug source")
logger.info("yes: info", source: "yes: info source")
logger.notice("yes: notice", source: "yes: notice source")
logger.warning("yes: warning", source: "yes: warning source")
logger.error("yes: error", source: "yes: error source")
logger.critical("yes: critical", source: "yes: critical source")
// Please note that the source is _not_ propagated (because the backend doesn't support it).
testLogging.history.assertExist(level: .trace, message: "yes: trace", source: "yes: trace source")
testLogging.history.assertExist(level: .debug, message: "yes: debug", source: "yes: debug source")
testLogging.history.assertExist(level: .info, message: "yes: info", source: "yes: info source")
testLogging.history.assertExist(level: .notice, message: "yes: notice", source: "yes: notice source")
testLogging.history.assertExist(level: .warning, message: "yes: warning", source: "yes: warning source")
testLogging.history.assertExist(level: .error, message: "yes: error", source: "yes: error source")
testLogging.history.assertExist(level: .critical, message: "yes: critical", source: "yes: critical source")
}
}
private struct OldSchoolTestLogging {
@@ -96,3 +121,58 @@ private struct OldSchoolLogHandler: LogHandler {
var logLevel: Logger.Level
}
private struct NewerButStillOldTestLogging {
private let _config = Config() // shared among loggers
private let recorder = Recorder() // shared among loggers
@available(*, deprecated, message: "Testing deprecated functionality")
func make(label: String) -> any LogHandler {
NewerButStillOldLogHandler(
label: label,
config: self.config,
recorder: self.recorder,
metadata: [:],
logLevel: .info
)
}
var config: Config { self._config }
var history: some History { self.recorder }
}
@available(*, deprecated, message: "Testing deprecated functionality")
private struct NewerButStillOldLogHandler: LogHandler {
var label: String
let config: Config
let recorder: Recorder
func make(label: String) -> some LogHandler {
TestLogHandler(label: label, config: self.config, recorder: self.recorder)
}
func log(
level: Logger.Level,
message: Logger.Message,
metadata: Logger.Metadata?,
source: String,
file: String,
function: String,
line: UInt
) {
self.recorder.record(level: level, metadata: metadata, message: message, source: source)
}
subscript(metadataKey metadataKey: String) -> Logger.Metadata.Value? {
get {
self.metadata[metadataKey]
}
set {
self.metadata[metadataKey] = newValue
}
}
var metadata: Logger.Metadata
var logLevel: Logger.Level
}
+74
View File
@@ -0,0 +1,74 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Logging API open source project
//
// Copyright (c) 2018-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
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2026 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Testing
@testable import Logging
#if canImport(Dispatch)
import Dispatch
private let canImportDispatch = true
#else
private let canImportDispatch = false
#endif
@Suite("Lock Test Suite")
struct LockTestSuite {
@Test(.enabled(if: canImportDispatch)) func testLockMutualExclusion() {
#if canImport(Dispatch)
let l = Lock()
nonisolated(unsafe) var x = 1
let q = DispatchQueue(label: "q")
let g = DispatchGroup()
let sem1 = DispatchSemaphore(value: 0)
let sem2 = DispatchSemaphore(value: 0)
l.lock()
q.async(group: g) {
sem1.signal()
l.lock()
x = 2
l.unlock()
sem2.signal()
}
sem1.wait()
#expect(DispatchTimeoutResult.timedOut == g.wait(timeout: .now() + 0.1))
#expect(1 == x)
l.unlock()
sem2.wait()
l.lock()
#expect(2 == x)
l.unlock()
#endif // canImport(Dispatch)
}
}
+189
View File
@@ -0,0 +1,189 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Logging API open source project
//
// Copyright (c) 2025 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 Testing
@testable import Logging
struct LogEventTest {
// MARK: - Lazy source computation
@Test func sourceIsDerivedFromFileWhenNotProvided() {
let event = LogEvent(
level: .info,
message: "hello",
metadata: nil,
source: nil,
file: "MyModule/MyFile.swift",
function: "f()",
line: 1
)
#expect(event.source == "MyModule")
}
@Test func sourceUsesExplicitValueWhenProvided() {
let event = LogEvent(
level: .info,
message: "hello",
metadata: nil,
source: "ExplicitSource",
file: "MyModule/MyFile.swift",
function: "f()",
line: 1
)
#expect(event.source == "ExplicitSource")
}
@Test func sourceSetterOverridesLazyValue() {
var event = LogEvent(
level: .info,
message: "hello",
metadata: nil,
source: nil,
file: "MyModule/MyFile.swift",
function: "f()",
line: 1
)
#expect(event.source == "MyModule")
event.source = "OverriddenSource"
#expect(event.source == "OverriddenSource")
}
@Test func sourceLazyDerivationDoesNotStoreComputedValue() {
let event = LogEvent(
level: .info,
message: "hello",
metadata: nil,
source: nil,
file: "MyModule/MyFile.swift",
function: "f()",
line: 1
)
// Internal _source should be nil when no explicit source was provided.
#expect(event._source == nil)
// Accessing source derives it from file but does not mutate _source (it's a computed get).
_ = event.source
#expect(event._source == nil)
}
@Test func metadataSetterStoresThroughComputedProperty() {
var event = LogEvent(
level: .info,
message: "hello",
metadata: nil,
source: nil,
file: "M/F.swift",
function: "f()",
line: 1
)
#expect(event.metadata == nil)
event.metadata = ["key": "value"]
#expect(event.metadata?["key"] == "value")
event.metadata = nil
#expect(event.metadata == nil)
}
@Test func loggerDerivedSourceMatchesModuleName() {
let recorder = Recorder()
let handler = LogEventHandler(recorder: recorder)
var logger = Logger(label: "test", handler)
logger.logLevel = .trace
// Log without explicit source — source should be derived from #fileID.
logger.info("derived source test")
let entries = recorder.entries
#expect(entries.count == 1)
#expect(entries[0].source == "LoggingTests")
}
// MARK: - Default log(event:) forwarding to deprecated flat-parameter method
@available(*, deprecated, message: "Testing deprecated functionality")
@Test func defaultLogEventForwardsAllFieldsIncludingSourceLocation() {
let recorder = Recorder()
let handler = FlatParametersHandler(recorder: recorder)
var logger = Logger(label: "test", handler)
logger.logLevel = .trace
logger.warning("location test")
let line = UInt(#line - 1)
let entries = recorder.entries
#expect(entries.count == 1)
#expect(entries[0].level == .warning)
#expect(entries[0].message == "location test")
#expect(entries[0].file.hasSuffix("LogEventTest.swift"))
#expect(entries[0].function.contains("defaultLogEventForwardsAllFieldsIncludingSourceLocation"))
#expect(entries[0].line == line)
}
}
// MARK: - Test Helpers
/// A handler that implements `log(event:)` directly and records entries.
private struct LogEventHandler: LogHandler {
let recorder: Recorder
var logLevel: Logger.Level = .trace
var metadata: Logger.Metadata = [:]
var metadataProvider: Logger.MetadataProvider?
func log(event: LogEvent) {
self.recorder.record(level: event.level, metadata: event.metadata, message: event.message, source: event.source)
}
subscript(metadataKey key: String) -> Logger.Metadata.Value? {
get { self.metadata[key] }
set { self.metadata[key] = newValue }
}
}
/// A handler that only implements the deprecated flat-parameter method, relying on the
/// default `log(event:)` forwarding bridge.
@available(*, deprecated, message: "Testing deprecated functionality")
private struct FlatParametersHandler: LogHandler {
let recorder: Recorder
var logLevel: Logger.Level = .trace
var metadata: Logger.Metadata = [:]
var metadataProvider: Logger.MetadataProvider?
func log(
level: Logger.Level,
message: Logger.Message,
metadata: Logger.Metadata?,
source: String,
file: String,
function: String,
line: UInt
) {
self.recorder.record(
level: level,
metadata: metadata,
message: message,
source: source,
file: file,
function: function,
line: line
)
}
subscript(metadataKey key: String) -> Logger.Metadata.Value? {
get { self.metadata[key] }
set { self.metadata[key] = newValue }
}
}
+102 -34
View File
@@ -387,6 +387,7 @@ struct LoggingTest {
enum TestError: Error {
case boom
case withMessage(String)
}
@Test func dictionaryMetadata() {
@@ -443,13 +444,13 @@ struct LoggingTest {
private var makeValue: (() -> String)?
private var _value: String?
public init(_ makeValue: @escaping () -> String) {
init(_ makeValue: @escaping () -> String) {
self.makeValue = makeValue
}
/// This allows caching a value in case it is accessed via an by name subscript,
// rather than as part of rendering all metadata that a LoggingContext was carrying
public var value: String {
var value: String {
if let f = self.makeValue {
self._value = f()
self.makeValue = nil
@@ -459,7 +460,7 @@ struct LoggingTest {
return self._value!
}
public var description: String {
var description: String {
"\(self.value)"
}
}
@@ -515,6 +516,7 @@ struct LoggingTest {
logger.debug(self.dontEvaluateThisString())
logger.info(self.dontEvaluateThisString())
logger.warning(self.dontEvaluateThisString())
logger.warning(self.dontEvaluateThisString(), error: TestError.withMessage("\(self.dontEvaluateThisString())"))
logger.log(level: .warning, self.dontEvaluateThisString())
}
@@ -543,15 +545,7 @@ struct LoggingTest {
@Test func customFactory() {
struct CustomHandler: LogHandler {
func log(
level: Logger.Level,
message: Logger.Message,
metadata: Logger.Metadata?,
source: String,
file: String,
function: String,
line: UInt
) {}
func log(event: LogEvent) {}
subscript(metadataKey _: String) -> Logger.Metadata.Value? {
get { nil }
@@ -575,6 +569,19 @@ struct LoggingTest {
#expect(logger2.handler is CustomHandler, "expected custom log handler")
}
@Test func errorParameter() {
let testLogging = TestLogging()
let logger = Logger(
label: "\(#function)",
factory: {
testLogging.make(label: $0)
}
)
logger.log(level: .info, "hello world!", error: TestError.boom)
testLogging.history.assertExist(level: .info, message: "hello world!", error: TestError.boom)
}
@Test func allLogLevelsExceptCriticalCanBeBlocked() {
let testLogging = TestLogging()
@@ -631,7 +638,48 @@ struct LoggingTest {
testLogging.history.assertExist(level: .critical, message: "yes: critical")
}
@Test func allLogLevelByFunctionRefWithSource() {
@Test func allLogLevelByFunctionRefWithSourceAndError() {
let testLogging = TestLogging()
var logger = Logger(
label: "\(#function)",
factory: {
testLogging.make(label: $0)
}
)
logger.logLevel = .trace
let trace = logger.trace(_:error:metadata:source:file:function:line:)
let debug = logger.debug(_:error:metadata:source:file:function:line:)
let info = logger.info(_:error:metadata:source:file:function:line:)
let notice = logger.notice(_:error:metadata:source:file:function:line:)
let warning = logger.warning(_:error:metadata:source:file:function:line:)
let error = logger.error(_:error:metadata:source:file:function:line:)
let critical = logger.critical(_:error:metadata:source:file:function:line:)
trace("yes: trace", TestError.boom, [:], "foo", #file, #function, #line)
debug("yes: debug", TestError.boom, [:], "foo", #file, #function, #line)
info("yes: info", TestError.boom, [:], "foo", #file, #function, #line)
notice("yes: notice", TestError.boom, [:], "foo", #file, #function, #line)
warning("yes: warning", TestError.boom, [:], "foo", #file, #function, #line)
error("yes: error", TestError.boom, [:], "foo", #file, #function, #line)
critical("yes: critical", TestError.boom, [:], "foo", #file, #function, #line)
testLogging.history.assertExist(level: .trace, message: "yes: trace", error: TestError.boom, source: "foo")
testLogging.history.assertExist(level: .debug, message: "yes: debug", error: TestError.boom, source: "foo")
testLogging.history.assertExist(level: .info, message: "yes: info", error: TestError.boom, source: "foo")
testLogging.history.assertExist(level: .notice, message: "yes: notice", error: TestError.boom, source: "foo")
testLogging.history.assertExist(level: .warning, message: "yes: warning", error: TestError.boom, source: "foo")
testLogging.history.assertExist(level: .error, message: "yes: error", error: TestError.boom, source: "foo")
testLogging.history.assertExist(
level: .critical,
message: "yes: critical",
error: TestError.boom,
source: "foo"
)
}
@Test func allLogLevelByFunctionRefWithSourceWithoutError() {
let testLogging = TestLogging()
var logger = Logger(
@@ -667,7 +715,7 @@ struct LoggingTest {
testLogging.history.assertExist(level: .critical, message: "yes: critical", source: "foo")
}
@Test func allLogLevelByFunctionRefWithoutSource() {
@Test func allLogLevelByFunctionRefWithoutSourceOrError() {
let testLogging = TestLogging()
var logger = Logger(
@@ -869,16 +917,13 @@ struct LoggingTest {
}
}
func log(
level: Logger.Level,
message: Logger.Message,
metadata: Logger.Metadata?,
source: String,
file: String,
function: String,
line: UInt
) {
self.recorder.record(level: level, metadata: metadata, message: message, source: source)
func log(event: LogEvent) {
self.recorder.record(
level: event.level,
metadata: event.metadata,
message: event.message,
source: event.source
)
}
subscript(metadataKey metadataKey: String) -> Logger.Metadata.Value? {
@@ -1117,8 +1162,7 @@ struct LoggingTest {
}
@Test func stdioOutputStreamWrite() {
self.withWriteReadFDsAndReadBuffer { writeFD, readFD, readBuffer in
let logStream = StdioOutputStream(file: writeFD, flushMode: .always)
self.withWriteReadFDsAndReadBuffer(flushMode: .always) { logStream, readFD, readBuffer in
let log = Logger(
label: "test",
factory: {
@@ -1145,8 +1189,7 @@ struct LoggingTest {
@Test func stdioOutputStreamFlush() {
// flush on every statement
self.withWriteReadFDsAndReadBuffer { writeFD, readFD, readBuffer in
let logStream = StdioOutputStream(file: writeFD, flushMode: .always)
self.withWriteReadFDsAndReadBuffer(flushMode: .always) { logStream, readFD, readBuffer in
Logger(
label: "test",
factory: {
@@ -1171,8 +1214,7 @@ struct LoggingTest {
#expect(size2 == -1, "expected no flush")
}
// default flushing
self.withWriteReadFDsAndReadBuffer { writeFD, readFD, readBuffer in
let logStream = StdioOutputStream(file: writeFD, flushMode: .undefined)
self.withWriteReadFDsAndReadBuffer(flushMode: .undefined) { logStream, readFD, readBuffer in
Logger(
label: "test",
factory: {
@@ -1198,7 +1240,10 @@ struct LoggingTest {
}
}
func withWriteReadFDsAndReadBuffer(_ body: (CFilePointer, CInt, UnsafeMutablePointer<Int8>) -> Void) {
func withWriteReadFDsAndReadBuffer(
flushMode: StdioOutputStream.FlushMode,
_ body: (StdioOutputStream, CInt, UnsafeMutablePointer<Int8>) -> Void
) {
var fds: [Int32] = [-1, -1]
#if os(Windows)
fds.withUnsafeMutableBufferPointer {
@@ -1229,6 +1274,29 @@ struct LoggingTest {
var err = setvbuf(writeFD, writeBuffer, _IOFBF, 256)
#expect(err == 0, "setvbuf failed \(err)")
// Create the stream here while writeFD's concrete type is in scope.
// Type inference in the generic StdioOutputStream init picks the right
// C functions for whatever FILE representation this platform/API level uses.
#if os(Windows)
let stream = StdioOutputStream(
file: writeFD,
flushMode: flushMode,
lock: _lock_file,
unlock: _unlock_file,
write: fwrite,
flush: fflush
)
#else
let stream = StdioOutputStream(
file: writeFD,
flushMode: flushMode,
lock: flockfile,
unlock: funlockfile,
write: fwrite,
flush: fflush
)
#endif
let readFD = fds[0]
#if os(Windows)
let hPipe: HANDLE = HANDLE(bitPattern: _get_osfhandle(readFD))!
@@ -1249,7 +1317,7 @@ struct LoggingTest {
}
// the actual test
body(writeFD, readFD, readBuffer)
body(stream, readFD, readBuffer)
for fd in fds {
#if os(Windows)
@@ -1292,7 +1360,7 @@ struct LoggingTest {
LoggingSystem.bootstrap { (label: String) in StreamLogHandler.standardOutput(label: label) }
LoggingSystem.bootstrap { (label: String) in StreamLogHandler.standardError(label: label) }
// with metadata handler, explicitly, public api
// with metadata handler, explicitly, api
LoggingSystem.bootstrap(
{ label, metadataProvider in
StreamLogHandler.standardOutput(label: label, metadataProvider: metadataProvider)
@@ -1337,7 +1405,7 @@ struct LoggingTest {
}
extension Logger {
public func error(
func error(
error: any Error,
metadata: @autoclosure () -> Logger.Metadata? = nil,
file: String = #fileID,
+13 -45
View File
@@ -74,13 +74,13 @@ extension Logger.MetadataProvider {
}
}
public struct LogHandlerThatDidNotImplementMetadataProviders: LogHandler {
struct LogHandlerThatDidNotImplementMetadataProviders: LogHandler {
let testLogging: TestLogging
init(testLogging: TestLogging) {
self.testLogging = testLogging
}
public subscript(metadataKey _: String) -> Logging.Logger.Metadata.Value? {
subscript(metadataKey _: String) -> Logging.Logger.Metadata.Value? {
get {
nil
}
@@ -89,38 +89,22 @@ public struct LogHandlerThatDidNotImplementMetadataProviders: LogHandler {
}
}
public var metadata: Logging.Logger.Metadata = [:]
var metadata: Logging.Logger.Metadata = [:]
public var logLevel: Logging.Logger.Level = .trace
var logLevel: Logging.Logger.Level = .trace
public func log(
level: Logger.Level,
message: Logger.Message,
metadata: Logger.Metadata?,
source: String,
file: String,
function: String,
line: UInt
) {
self.testLogging.make(label: "fake").log(
level: level,
message: message,
metadata: metadata,
source: source,
file: file,
function: function,
line: line
)
func log(event: LogEvent) {
self.testLogging.make(label: "fake").log(event: event)
}
}
public struct LogHandlerThatDidImplementMetadataProviders: LogHandler {
struct LogHandlerThatDidImplementMetadataProviders: LogHandler {
let testLogging: TestLogging
init(testLogging: TestLogging) {
self.testLogging = testLogging
}
public subscript(metadataKey _: String) -> Logging.Logger.Metadata.Value? {
subscript(metadataKey _: String) -> Logging.Logger.Metadata.Value? {
get {
nil
}
@@ -129,29 +113,13 @@ public struct LogHandlerThatDidImplementMetadataProviders: LogHandler {
}
}
public var metadata: Logging.Logger.Metadata = [:]
var metadata: Logging.Logger.Metadata = [:]
public var logLevel: Logging.Logger.Level = .trace
var logLevel: Logging.Logger.Level = .trace
public var metadataProvider: Logger.MetadataProvider?
var metadataProvider: Logger.MetadataProvider?
public func log(
level: Logger.Level,
message: Logger.Message,
metadata: Logger.Metadata?,
source: String,
file: String,
function: String,
line: UInt
) {
self.testLogging.make(label: "fake").log(
level: level,
message: message,
metadata: metadata,
source: source,
file: file,
function: function,
line: line
)
func log(event: LogEvent) {
self.testLogging.make(label: "fake").log(event: event)
}
}
+117 -36
View File
@@ -54,7 +54,7 @@ internal struct TestLogHandler: LogHandler {
private var logger: Logger // the actual logger
let label: String
public var metadataProvider: Logger.MetadataProvider?
var metadataProvider: Logger.MetadataProvider?
init(label: String, config: Config, recorder: Recorder, metadataProvider: Logger.MetadataProvider?) {
self.label = label
@@ -74,15 +74,7 @@ internal struct TestLogHandler: LogHandler {
self.metadataProvider = LoggingSystem.metadataProvider
}
func log(
level: Logger.Level,
message: Logger.Message,
metadata explicitMetadata: Logger.Metadata?,
source: String,
file: String,
function: String,
line: UInt
) {
func log(event: LogEvent) {
// baseline metadata, that was set on handler:
var metadata = self._metadataSet ? self.metadata : MDC.global.metadata
// contextual metadata, e.g. from task-locals:
@@ -91,20 +83,27 @@ internal struct TestLogHandler: LogHandler {
metadata.merge(contextualMetadata, uniquingKeysWith: { _, contextual in contextual })
}
// override using any explicit metadata passed for this log statement:
if let explicitMetadata = explicitMetadata {
if let explicitMetadata = event.metadata {
metadata.merge(explicitMetadata, uniquingKeysWith: { _, explicit in explicit })
}
self.logger.log(
level: level,
message,
level: event.level,
event.message,
error: event.error,
metadata: metadata,
source: source,
file: file,
function: function,
line: line
source: event.source,
file: event.file,
function: event.function,
line: event.line
)
self.recorder.record(
level: event.level,
metadata: metadata,
message: event.message,
error: event.error,
source: event.source
)
self.recorder.record(level: level, metadata: metadata, message: message, source: source)
}
private var _logLevel: Logger.Level?
@@ -125,7 +124,7 @@ internal struct TestLogHandler: LogHandler {
}
}
public var metadata: Logger.Metadata {
var metadata: Logger.Metadata {
get {
self._metadata
}
@@ -175,10 +174,42 @@ internal class Recorder: History {
private let lock = NSLock()
private var _entries = [LogEntry]()
func record(level: Logger.Level, metadata: Logger.Metadata?, message: Logger.Message, source: String) {
func record(
level: Logger.Level,
metadata: Logger.Metadata?,
message: Logger.Message,
error: (any Error)? = nil,
source: String
) {
self.lock.withLock {
self._entries.append(
LogEntry(level: level, metadata: metadata, message: message.description, source: source)
LogEntry(level: level, metadata: metadata, message: message.description, error: error, source: source)
)
}
}
func record(
level: Logger.Level,
metadata: Logger.Metadata?,
message: Logger.Message,
error: (any Error)? = nil,
source: String,
file: String,
function: String,
line: UInt
) {
self.lock.withLock {
self._entries.append(
LogEntry(
level: level,
metadata: metadata,
message: message.description,
error: error,
source: source,
file: file,
function: function,
line: line
)
)
}
}
@@ -224,13 +255,38 @@ internal struct LogEntry {
let level: Logger.Level
let metadata: Logger.Metadata?
let message: String
let error: (any Error)?
let source: String
let file: String
let function: String
let line: UInt
init(
level: Logger.Level,
metadata: Logger.Metadata?,
message: String,
error: (any Error)?,
source: String,
file: String = "",
function: String = "",
line: UInt = 0
) {
self.level = level
self.metadata = metadata
self.message = message
self.error = error
self.source = source
self.file = file
self.function = function
self.line = line
}
}
extension History {
func assertExist(
level: Logger.Level,
message: String,
error: (any Error)? = nil,
metadata: Logger.Metadata? = nil,
source: String? = nil,
file: String = #filePath,
@@ -239,10 +295,10 @@ extension History {
column: Int = #column
) {
let source = source ?? Logger.currentModule(fileID: "\(fileID)")
let entry = self.find(level: level, message: message, metadata: metadata, source: source)
let entry = self.find(level: level, message: message, error: error, metadata: metadata, source: source)
#expect(
entry != nil,
"entry not found: \(level), \(source), \(String(describing: metadata)), \(message)",
"entry not found: \(level), \(source), \(String(describing: metadata)), \(message), \(String(describing: error))",
sourceLocation: SourceLocation(fileID: fileID, filePath: file, line: line, column: column)
)
}
@@ -250,6 +306,7 @@ extension History {
func assertNotExist(
level: Logger.Level,
message: String,
error: (any Error)? = nil,
metadata: Logger.Metadata? = nil,
source: String? = nil,
file: String = #filePath,
@@ -258,15 +315,21 @@ extension History {
column: Int = #column
) {
let source = source ?? Logger.currentModule(fileID: "\(fileID)")
let entry = self.find(level: level, message: message, metadata: metadata, source: source)
let entry = self.find(level: level, message: message, error: error, metadata: metadata, source: source)
#expect(
entry == nil,
"entry was found: \(level), \(source), \(String(describing: metadata)), \(message)",
"entry was found: \(level), \(source), \(String(describing: metadata)), \(message), \(String(describing: error))",
sourceLocation: SourceLocation(fileID: fileID, filePath: file, line: line, column: column)
)
}
func find(level: Logger.Level, message: String, metadata: Logger.Metadata? = nil, source: String) -> LogEntry? {
func find(
level: Logger.Level,
message: String,
error: (any Error)? = nil,
metadata: Logger.Metadata? = nil,
source: String
) -> LogEntry? {
self.entries.first { entry in
if entry.level != level {
return false
@@ -274,6 +337,9 @@ extension History {
if entry.message != message {
return false
}
if !errorsEqual(error, entry.error) {
return false
}
if let lhs = entry.metadata, let rhs = metadata {
if lhs.count != rhs.count {
return false
@@ -300,18 +366,29 @@ extension History {
return true
}
}
private func errorsEqual(_ lhs: (any Error)?, _ rhs: (any Error)?) -> Bool {
switch (lhs, rhs) {
case (nil, nil):
return true
case let (l?, r?):
return "\(l)" == "\(r)" && String(reflecting: type(of: l)) == String(reflecting: type(of: r))
default:
return false
}
}
}
/// MDC stands for Mapped Diagnostic Context
public class MDC {
class MDC {
private let lock = NSLock()
private var storage = [Int: Logger.Metadata]()
public static let global = MDC()
static let global = MDC()
private init() {}
public subscript(metadataKey: String) -> Logger.Metadata.Value? {
subscript(metadataKey: String) -> Logger.Metadata.Value? {
get {
self.lock.withLock {
self.storage[self.threadId]?[metadataKey]
@@ -327,19 +404,19 @@ public class MDC {
}
}
public var metadata: Logger.Metadata {
var metadata: Logger.Metadata {
self.lock.withLock {
self.storage[self.threadId] ?? [:]
}
}
public func clear() {
func clear() {
self.lock.withLock {
_ = self.storage.removeValue(forKey: self.threadId)
}
}
public func with(metadata: Logger.Metadata, _ body: () throws -> Void) rethrows {
func with(metadata: Logger.Metadata, _ body: () throws -> Void) rethrows {
for (key, value) in metadata {
self[key] = value
}
@@ -351,7 +428,7 @@ public class MDC {
try body()
}
public func with<T>(metadata: Logger.Metadata, _ body: () throws -> T) rethrows -> T {
func with<T>(metadata: Logger.Metadata, _ body: () throws -> T) rethrows -> T {
for (key, value) in metadata {
self[key] = value
}
@@ -375,6 +452,10 @@ public class MDC {
return Int(pthread_mach_thread_np(pthread_self()))
#elseif os(Windows)
return Int(GetCurrentThreadId())
#elseif os(FreeBSD)
return Int(pthread_getthreadid_np())
#elseif os(OpenBSD)
return Int(bitPattern: pthread_self())
#else
return Int(pthread_self())
#endif
@@ -385,13 +466,13 @@ internal struct TestLibrary: Sendable {
private let logger = Logger(label: "TestLibrary")
private let queue = DispatchQueue(label: "TestLibrary")
public init() {}
init() {}
public func doSomething() {
func doSomething() {
self.logger.info("TestLibrary::doSomething")
}
public func doSomethingAsync(completion: @escaping @Sendable () -> Void) {
func doSomethingAsync(completion: @escaping @Sendable () -> Void) {
// libraries that use global loggers and async, need to make sure they propagate the
// logging metadata when creating a new thread
let metadata = MDC.global.metadata
+5
View File
@@ -29,12 +29,14 @@ struct SendableTest {
let message1 = Logger.Message(stringLiteral: "critical 1")
let message2 = Logger.Message(stringLiteral: "critical 2")
let metadata: Logger.Metadata = ["key": "value"]
let error = TestError()
let task = Task.detached {
logger.info("info")
logger.critical(message1)
logger.critical(message2)
logger.warning(.init(stringLiteral: "warning"), metadata: metadata)
logger.warning("error", error: error)
}
await task.value
@@ -42,5 +44,8 @@ struct SendableTest {
testLogging.history.assertExist(level: .critical, message: "critical 1", metadata: [:])
testLogging.history.assertExist(level: .critical, message: "critical 2", metadata: [:])
testLogging.history.assertExist(level: .warning, message: "warning", metadata: metadata)
testLogging.history.assertExist(level: .warning, message: "error", error: error)
}
final class TestError: Error {}
}