Give `Logger.handler` a `_modify` accessor and replace its `get` with
`_read`, so metadata writes update the stored handler instead of a copy.
### Motivation:
`Logger.handler` only has `get` and `set`. A write such as
`logger[metadataKey: "k"] = "v"` gets a copy of the handler, writes to
it while the stored handler still shares the metadata dictionary, and
sets it back. So every write copies the whole dictionary, and
`withLogger(mergingMetadata:)` does that once per key.
### Modifications:
- Give `Logger.handler` `_read`, `set` and `_modify` accessors. `_read`
yields the stored handler. `_modify` keeps the existing uniqueness check
on the storage and then yields the stored handler, so metadata and log
level writes change it in place. `set` keeps the same check for plain
`logger.handler = newHandler` assignments, which are cheaper through a
setter than through `_modify`.
- Add a test handler that counts copies of its metadata, with tests for
direct writes and for `withLogger(mergingMetadata:)`. Without the change
they report 10 copies instead of 0, and 5 instead of 1.
### Result:
A metadata write on a logger that owns its storage no longer copies the
dictionary. A copied logger still copies once on its first write, so
value semantics are unchanged.
1,000 metadata writes with a handler that keeps metadata in a plain
dictionary, debug build, three runs each:
| Keys on the logger | Before | After |
|---|---|---|
| 10 | 7.2 to 8.1 ms | 0.46 to 0.50 ms |
| 1,000 | 20.2 to 20.6 ms | 0.46 to 0.55 ms |
| 10,000 | 134.0 to 134.4 ms | 0.47 to 0.50 ms |
| 100,000 | 1.29 to 1.30 s | 0.32 to 0.35 ms |
`withLogger(mergingMetadata:)` with 10,000 keys went from 0.64 to 0.65 s
down to 2.9 to 3.1 ms. `StreamLogHandler` still rebuilds its pretty
metadata string on every write; this change does not touch that.
All 176 tests pass on macOS with Swift 6.4, and `swift format lint
--strict` and `swift package diagnose-api-breaking-changes` are clean.
Once yielding accessors land, `_read` and `_modify` can become `yielding
borrow` and `yielding mutate`.
Fixes#526.
_[One line description of your change]_
### Motivation:
Update benchmark expectations, with the updated performance level
### Modifications:
Update json file with the new instruction count
### Result:
passing test
_[One line description of your change]_
### Motivation: Update threshold
This allows the faster GitHub runners to pass the benchmark tests.
### Modifications:
Updated threshold to a lower value
### Result:
Passing test
### Motivation:
Benchmarks CI has been failing recently on Swift 6.3 and 6.4, for
example: https://github.com/apple/swift-log/actions/runs/38083241726.
The results are actually better than expected in the thresholds.
### Modifications:
- Swift 6.3
MaxLogLevelNone.critical_log_with_critical_log_level_metadata_set.p90.json
threshold reduced
- Swift 6.4
MaxLogLevelWarning.notice_log_with_notice_log_level_attributed_generic.p90.json
threshold reduced
### Result:
CI should not fail anymore.
Ensure metadata from the multiplex handler’s own provider reaches
emitted logs.
Fixes#521.
## Motivation
`MultiplexLogHandler` accepts a metadata provider in its initializer,
but `log(event:)` never invokes it. Provider values such as trace IDs
are therefore missing from downstream logs.
## Modifications
- Merge the multiplex provider’s metadata into the event before
forwarding it.
- Preserve explicit per-message metadata overrides.
- Add regression tests covering one and two downstream handlers and
metadata precedence.
## Result
The supplied provider’s metadata is included in emitted logs.
Regression tests fail before the fix and pass afterward. All 174 tests
pass on macOS with Swift 6.4. Formatting and `git diff --check` also
pass.
Fixes#519.
## Motivation
When both `logLevel` and `handler` are provided, `withLogger` sets the
level on the current handler before replacing it. Since
`Logger.logLevel` forwards to the handler, the replacement discards the
requested level and uses its own instead.
## Modifications
- Install the replacement handler before applying the explicit log level
in both sync and async overloads.
- Add regression tests for `.debug` and `.warning` in both overloads,
covering filtering and scope isolation.
## Result
The scoped logger filters messages at the requested level.
Regression tests fail before the fix and pass afterward. All 172 tests
pass on macOS with Swift 6.4. Formatting and `git diff --check` also
pass.
The support window is 3 latest minor Swift versions. CI i already
running for Swift 6.2, 6.3 and 6.4 only. Updating the Swift tools and
the package to match this.
Only quote leaf metadata values.
### Motivation:
There are several issues with how nested `MetadataValue`s are handled:
1. For highly nested (10k+) metadata, `.description` and `==` operator
hit stack overflow. This is probably not very realistic depth, but
still.
2. For not so highly nested metadata (starting at about 20)
`.description` and `==` operator get very computationally intensive
because of re-escaping of the already escaped children. This makes the
above stack overflow crash not reachable in practice.
3. This also results in simple structured metadata to be rendered
something like
`["[\"[\\\"[\\\\\\\"[\\\\\\\\\\\\\\\"leaf\\\\\\\\\\\\\\\"]\\\\\\\"]\\\"]\"]"]`.
4. Finally, even after solving the re-quoting and stack over flow on
rendering, there is still an issue of [recursion in
`.deinit`](https://github.com/swiftlang/swift/issues/58080), resulting
in a _different_ stack overflow crash.
This PR provides a fix for 2 and 3, leaving 1 and 4 out because there is
no practical way of fixing it in this package, while the case is
borderline unrealistic.
### Modifications:
- Only quote left `String` and `StringRepresentable` values in
`Logger.MetadataValue.description`.
- Add benchmarks for metadata values description rendering.
### Result:
100 nested metadata values render cleanly.
Resolves#515
### Alternatives
This is discussable if this fix is really necessary. Iterative approach,
because of allocations, is slower than recursion.
- Is it worth fixing the recursion, or a metadata depth check is enough?
- Is it worth fixing the nested metadata formatting?
I removed the stale exclude statements from `Package.swift` and
`Package@swift-6.1.swift`
### Motivation:
In #485, CMake build support was added, as part of it, 99c554b added
`exclude: ["CMakeLists.txt"]` to all four SwiftPM targets, including
tests, but the CI was revealing some issues with CMake test-targets. So
after review, in 4a81108 the CMake build files were removed from the
`/Tests` directory but I accidentally left behind the exclusions in the
package manifests.
### Modifications:
Removed the exclude statements from Package.swift and
Package@swift-6.1.swift.
### Result:
No SwiftPM errors!
Fixes: #513
I updated the `CONTRIBUTING.md` documentation to fix the outdated name
for the benchmarking plugin. The instructions now reference the
`benchmark` plugin instead of the previously outdated
`package-benchmark` plugin, and associated links and descriptions have
been updated accordingly. Previously these were leading to `404 Not
Found` errors.
No code changes were made in this PR.
Fixes: #510
---------
Co-authored-by: Vladimir Kukushkin <kukushechkin@mac.com>
### Motivation:
Nightly CI on nightly-main toolchains started failing on August 11, when
we started downloading swift-DEVELOPMENT-SNAPSHOT-2026-08-08 instead of
swift-DEVELOPMENT-SNAPSHOT-2026-07-11.
Appears to be fallout from
https://github.com/swiftlang/swift/commit/73fee3394d3102847fef26c1bdea49a67061f043
improving the optionality and concurrency of stdout/stderr/stdin on the
various platforms.
### Modifications:
Adapted Swift Log code to handle both the existing and behavior, guarded
by a `compiler(>=6.5)`
Also enabled nightly-next, which tracks the pre-release 6.4 right now,
but hasn't received this change.
### Result:
Passing CI, hopefully :)
### Motivation:
The two deprecated `LogHandler` defaults forward to each other: the
source-carrying `log(level:message:metadata:source:file:function:line:)`
default calls `log(event:)`, whose default calls the source-carrying
method, and the SwiftLog 1.0
`log(level:message:metadata:file:function:line:)` default calls the
source-carrying method. A handler that implements only `log(event:)`, as
the protocol documentation asks, therefore recurses until the stack
overflows whenever anything calls the 1.0 method on it. Handlers written
against SwiftLog 1.0 that wrap another handler and forward through the
1.0 method reach this path.
Differs from #248, where the handler implemented no log method at all.
### Modifications:
The 1.0 default builds a `LogEvent` and calls `log(event:)` directly.
The source is still the module derived from `file`, as before. Two tests
in `CompatibilityTest`: the 1.0 method reaching an event-only handler
(SIGSEGV at `main` before the change) and reaching a source-only
handler.
### Result:
A `LogHandler` implementing only `log(event:)` can be called through
every deprecated entry point. No source-breaking change; both deprecated
defaults remain.
Verified on Linux with Swift 6.1.2: `swift test -Xswiftc
-warnings-as-errors --explicit-target-dependency-import-check error
-Xswiftc -require-explicit-sendable` (166 tests) and `swift-format lint
--strict` on the changed files.
Found by an automated audit loop (Claude); patch and description
reviewed by me.
---------
Co-authored-by: Vladimir Kukushkin <kukushechkin@apple.com>
### Motivation:
`Logger.MetadataValue.attributes` documents the setter as a no-op for
`.dictionary` and `.array`, but it calls `assertionFailure` there. Debug
builds trap, release builds do the documented no-op.
### Modifications:
Doc comment only. The assertion stays; the comment now says setting
attributes on a collection value is a programmer error, that debug
builds assert and release builds leave the value unchanged, and to set
attributes on the leaf values instead.
### Result:
The documentation matches the code. No behaviour change.
Found by an automated audit loop (Claude); patch and description
reviewed by me.
### Motivation:
Unblock nightly CI runs on main by disabling non-macOS Apple platform
simulator testing due to instability.
### Modifications:
Disabled that CI for now. We'll re-enable when we can make it pass
reliably.
### Result:
Bring nightly CI back to green.
Add CMake build instructions for macOS, Windows and Linux including
requirements and installation steps.
### Motivation:
Document how to build SwiftLog with CMake for projects that use mixed
build systems and need integration outside of Swift Package Manager.
### Modifications:
- Added a new “Building with CMake” section to `README.md`
- Documented minimum requirements:
- Swift 6.1+
- CMake 3.19+
- Ninja 1.10+
- Added macOS build examples for both Xcode and Ninja generators
- Added Windows build instructions using Ninja
- Added install instructions and notes about shared vs. static builds
- Clarified that tests are not included in the CMake build and are still
managed through Swift Package Manager
### Result:
Users now have platform-specific guidance for building SwiftLog with
CMake on macOS, Windows and Linux.
Fixes#492
### Motivation:
Swift 6.3 benchmarks have been failing for a while now
### Modifications:
- Update 2 benchmark thresholds to match values for Swift 6.3.
- Update thresholds files formatting to reduce noise in the output diff.
### Result:
Benchmarks should not fail sporadically.
### Motivation:
`public` init has no effect for an `internal` class.
### Modifications:
Removed `public` from the `ReadWriteLock.init`.
### Result:
`ReadWriteLock.init` is now `internal`, matching class visibility.
Document best practice for creating complex `LogHandlers`.
### Motivation:
`LogHandler`s often need an expensive resource to write or export log
events. This pattern should be documented.
### Modifications:
Add "Constructing handlers that need more than a label" section to
`ImplementingALogHandler.md` guide.
### Result:
Closes#80.
---------
Co-authored-by: Joseph Heck <j_heck@apple.com>
Add CMake build support to the project to enable toolchain integration
and bootstrapping compatibility.
### Motivation:
Currently, swift-log does not support building with CMake. This addition
resolves issue #484, allowing swift-log to be resolved and compiled
within CMake-based environments (like the repos swift-certificates and
swift-argument-parser which aer mentioned in the issue).
### Modifications:
1. **Project Root Config:** Added
[CMakeLists.txt](file:///Users/adityamitra/Developer/swift-log/CMakeLists.txt)
configuring the CMake project with Swift 6 and C, alongside setting up
compiler flags for MSVC runtime library on Windows.
2. **Helper Modules:** Added the `cmake/` folder:
- `SwiftSupport.cmake`: dylib/module installations and triple detection
helper.
- `SwiftLogConfig.cmake.in`: package config export templates.
3. **Target CMake Configurations:** Created
[Sources/Logging/CMakeLists.txt](file:///Users/adityamitra/Developer/swift-log/Sources/Logging/CMakeLists.txt)
&
[Sources/InMemoryLogging/CMakeLists.txt](file:///Users/adityamitra/Developer/swift-log/Sources/InMemoryLogging/CMakeLists.txt)
to define the library targets. Included generator expressions pointing
`INTERFACE_INCLUDE_DIRECTORIES` to target output directories for Xcode
generator support.
4. **SwiftPM Exclusions:** Excluded the new CMake files from target
targets inside
[Package.swift](file:///Users/adityamitra/Developer/swift-log/Package.swift)
and
[Package@swift-6.1.swift](file:///Users/adityamitra/Developer/swift-log/Package@swift-6.1.swift)
to keep SwiftPM targets warning-free.
5. **Compile Options Variable:** Consolidates compile options under a
single global definition `SWIFT_LOG_COMMON_COMPILE_OPTIONS` in the root
configuration, enabling Swift 6 compiler features (`ExistentialAny`,
`MemberImportVisibility`, `InternalImportsByDefault`,
`NonisolatedNonsendingByDefault`, and explicit Sendable checks) across
all targets.
6. **CI Integration & Workflow:** Integrated CMake CI validation in
`.github/workflows/pull_request.yml` using the shared workflow from
`apple/swift-nio/.github/workflows/cmake_tests.yml@main` running in a
`swift:6.1-jammy` container. This job compiles the core libraries and
verifies the validity of the CMake files.
7. **License Header Compliance:** Cleaned up license headers across all
CMake files
### Result:
* **SwiftPM:** All 164 unit tests compile and pass successfully under
`swift test` with no warnings.
* **CMake:** Successfully compiles (`** BUILD SUCCEEDED **`) under Xcode
generator (`cmake -B build -G Xcode && cmake --build build`).
### Issue Tracking:
Fixes#484
---------
Co-authored-by: Vladimir Kukushkin <kukushechkin@apple.com>
Make `StreamLogHandler` initializers public.
### Motivation:
Closes https://github.com/apple/swift-log/issues/273
### Modifications:
Promote the two stream-accepting initializers from `internal` to
`public`. Also as a result, their stream parameter is spelled out as
`any TextOutputStream & Sendable` rather than the internal
`_SendableTextOutputStream` typealias, which cannot appear in a public
signature. ~The private stored property and the internal typealias are
otherwise unchanged.~ The internal typealias has been completely removed
as it was only used to store the stream, and the private stored property
is updated to use the spelled-out type.
Also updates the docc documentation accordingly.
### Result:
Users would be able to construct a `StreamLogHandler` with their own
`TextOutputStream` implementation, reusing the existing logic to format
log messages and prettify metadata instead of reimplementing them.
---------
Signed-off-by: subhramit <subhramit.bb@live.in>
Co-authored-by: Vladimir Kukushkin <kukushechkin@apple.com>
Add a Best Practice guide on how to test logging.
### Motivation:
There are 2 recommended ways of propagating logs in components, both are
testable. But there is no any kind of documentation on how to do it.
### Modifications:
Add a "Testing code that logs" Best Practice guide.
### Result:
Logs testing is now documented.
---------
Co-authored-by: Joseph Heck <j_heck@apple.com>
Expands on @kukushechkin #474 (add-missing API) and tacks in some
additional work
### Motivation:
resolve the DocC warnings
### Modifications:
- resolves docc warnings for soundness checks
- updates curation to drop the task-local logger updates into the
correct areas
- updates curation to collect the implemented proposals together
### Result:
Hopefully no issues with soundness checks
---------
Co-authored-by: Vladimir Kukushkin <kukushechkin@apple.com>
Simulators seem to have stabilized in CI, we can enabled the tests.
### Motivation:
`swift-log` is expected to be used on various platforms, we should run
tests against them.
### Modifications:
- Run tests on various tests in simulators in PRs and nightly.
- Fix tests to actually compile there.
### Result:
Tests are now running in simulators. Supersedes #431.
This proposal adds task-local logger storage so that metadata can
accumulate across async
call stacks without threading a `Logger` through every function
signature.
### Motivation:
Metadata propagation requires threading a logger through every layer.
Every function on
the path from request ingress to the bottom of the call stack has to
accept, mutate, and
forward a `Logger`. Libraries must choose between polluting their public
API with a `logger:` parameter and
losing all the caller's context. There is no third option today.
### Modifications:
- New API surface for reading and modifying the `@TaskLocal` `Logger`
instance added.
- Best practices on how to correctly propagate logger into libraries
updated with `Logger.current` API.
### Result:
Users can now automatically propagate accumulated metadata into
libraries without explicitly passing loggers through the API boundaries.
---------
Co-authored-by: Franz Busch <privat@franz-busch.de>
This proposal adds task-local logger storage so that metadata can
accumulate across async
call stacks without threading a `Logger` through every function
signature.
### Motivation:
Metadata propagation requires threading a logger through every layer.
Every function on
the path from request ingress to the bottom of the call stack has to
accept, mutate, and
forward a `Logger`. Libraries must choose between polluting their public
API with a `logger:` parameter and
losing all the caller's context. There is no third option today.
### Modifications:
SLG-0006 proposal is added.
### Result:
Proposal is ready for review.
Add [Default String
Interpolation](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0477-default-interpolation-values.md)
overloads for `MetadataValue` to restore compatibility with
`\(default:)` interpolation.
### Motivation:
1.13.0 introduced a breaking change to the default string interpolation
compatibility. We do not want to revert the custom string interpolation,
but can fix compatibility with the default string interpolation as much
as possible.
### Modifications:
Add `\(default:)` overloads to `MetadataValue.StringInterpolation`,
similar to the once in `DefaultStringInterpolation`.
### Result:
Compatibility with `logger.info("Log message", metadata: ["value":
"\(value, default: "none")"])` is restored.
Proposal discussion thread:
https://forums.swift.org/t/proposal-slg-0004-metadata-value-attributes-revision-2/86488
Add an extensible per-value attribute mechanism for metadata.
### Motivation:
Metadata values in `swift-log` are opaque strings by the time the
`LogHandler` receives them. The call site often
knows things about a value that the handler cannot infer — for example,
whether the value should be redacted in
different environments.
### Modifications:
- SLG-0004 proposal is updated based on the feedback.
- Added `AttributedStringCarrier: CustomStringConvertible`-based
mechanism to `Logging`.
- Added benchmarks and benchmark thresholds for the new attributed
metadata.
### Result:
`swift-log` provides an optional extensible mechanism for attaching
attributes to metadata values.
---------
Co-authored-by: Franz Busch <privat@franz-busch.de>
### Motivation
* The two-invocation pattern for `macos-benchmarks` and
`macos-benchmarks-MaxLogLevelWarningBenchmarks-trait` allocates one
self-hosted macOS runner per (Swift version x package), incurring
duplicate runner-recycling cost.
* The recent change on main adds a `benchmark_package_paths` input
letting a single invocation run all packages serially on each runner.
### Modifications
* Replace the two macOS benchmark jobs in `main.yml` and
`pull_request.yml` with a single consolidated job that passes both
packages via `benchmark_package_paths: '["Benchmarks/NoTraits",
"Benchmarks/MaxLogLevelWarning"]'`.
* Drop Swift 6.2 from the matrix; only Swift 6.3 is shared between the
two packages (`MaxLogLevelWarning` has no `Thresholds/Xcode swift
6.2/`).
### Result
* One macOS runner allocation per Swift version instead of one per
(version x package).
* `NoTraits` loses Swift 6.2 coverage
Skip handler dispatch for setters under `MaxLogLevelNone`
### Motivation
* When `MaxLogLevelNone` is enabled every
`Logger.trace`/`debug`/.../`critical` method and `Logger.log(level:)`
compiles down to an empty body, so no log statement can ever observe
what the underlying `LogHandler` sees.
* Despite this, the `subscript(metadataKey:)` and `logLevel` setters
still went through the handler. Code like `logger[metadataKey:
"user-id"] = "\(id)"` would CoW the logger storage and call into the
handler even though nothing could read the metadata back out via a log
statement.
### Modifications
* Wrap the bodies of `Logger.subscript(metadataKey:) { set }` and
`Logger.logLevel { set }` in `#if !MaxLogLevelNone`, mirroring the
existing guards on the level-specific log methods.
* Note this behaviour in `DisableLogLevelsDuringCompilation.md` so
callers know reads still go through the handler but writes do not.
* Add a new benchmark which ensures that the operations don't allocate.
* Update some missed swift-tools-version bumps.
* Loosen p90 instruction threshold to 10%. The same source produces
results that swing by up to ~8% between back-to-back runs.
### Result
* `logger[metadataKey:] = ...` and `logger.logLevel = ...` compile to
empty bodies when `MaxLogLevelNone` is set, matching the
zero-runtime-overhead guarantee the trait already provides for log
emission.
* Resolves https://github.com/apple/swift-log/issues/462
### Motivation
* The shared `macos_tests.yml` and `macos_benchmarks.yml` workflows
support requesting Xcodes by Swift version with symlinks on the runners
owning the mapping. This more directly expresses the library support
window.
* Older Xcodes (26.1 and below) are being removed from the runners.
### Modifications
* Replace `macos_xcode_16_4_enabled` and `macos_xcode_26_1_enabled` with
`macos_swift_6_1_enabled` and `macos_swift_6_2_enabled` in benchmark
jobs.
* Remove now-redundant explicit `xcode_*_enabled: false` and
`swift_*_enabled: true` overrides from the `macos-tests` job in
`main.yml` (these now match the workflow defaults).
### Result
* macOS CI requests toolchains by Swift version, decoupling the
workflows from specific Xcode release names.
> [!IMPORTANT]
> This is a revision of SLG-0004 previously discussed
[here](https://forums.swift.org/t/proposal-slg-0004-metadata-values-privacy-attribute/85249/15).
Add an extensible per-value attribute mechanism for metadata.
### Motivation:
Metadata values in `swift-log` are opaque strings by the time the
`LogHandler` receives them. The call site often
knows things about a value that the handler cannot infer — for example,
whether the value should be redacted in
different environments, or additional value type information.
### Modifications:
- SLG-0004 proposal is updated based on the feedback in the first round
of discussion.
### Result:
Revised SLG-0004 proposal is ready for review.
Unify repos layout across the ecosystem:
1. Remove `CONTRIBUTORS.md` and mentions of it.
2. Remove `CODE_OF_CONDUCT.md` and mentions of it.
3. From `CONTRIBUTING.md` remove "Writing a Patch" and "Commit Message
Template" sections.
4. Remove `.mailmap` and mentions of it.
5. Remove `dev/git.commit.template` and mentions of it.
6. Remove `SECURITY.md`, if it is referenced somewhere, change it to
reference to the org security file
"https://github.com/apple/swift-log?tab=security-ov-file".
7. Remove copyright header from `Package.swift` and version-specific
package manifests.
8. Add SPI shields to the `README.md`.
9. Add "How to contribute your work" section in `CONTRIBUTING.md`.
10. Add "Add Automated release process" section in `CONTRIBUTING.md`.
Add tests for SwiftLogNoOpLogHandler
### Motivation:
`SwiftLogNoOpLogHandler` is a public type with no dedicated test
coverage.
### Modifications:
* Add tests for both initialisers, `logLevel`, `metadata`, the metadata
subscript, `log(event:)`, and end-to-end usage via `Logger`.
### Result:
`SwiftLogNoOpLogHandler` has test coverage on par with other handlers.
Coverage from 89% over all tests, to 90%.
Prompt: Make dependabot set label
Claude output:
Both changes are already in place:
1. The `labels: ["semver/none"]` is already configured (lines 7-8).
2. The schedule interval is already set to `"daily"` (line 6).
The file already has the desired configuration. The git status shows
this file as modified, meaning these changes were already made in the
current branch but haven't been committed yet.
Improve readability by extracting separate types to their own files
### Motivation:
`Logger.swift` is >2000 LoC, which makes it hard to navigate both for
contributors and users of `swift-log`. Widely different concepts, such
as concrete `LogHandler` implementations, are mixed with core types such
as `Logger.Level`. Extracting separate types should make it easier to
find what you are looking for.
Closes#441
### Modifications:
* Extract all (not `Logger`-namespaced) types from `Logging.swift` to
separate files.
* Rename `Logging.swift` to `Logger.swift`, as this is the only
remaining top-level type.
* Change `LoggingSystem.factory` from `fileprivate` to `internal` to be
accessible from `Logger.swift`.
### Result:
Each (non-private) top-level type lives in a separate file, named after
the type.
---------
Co-authored-by: Vladimir Kukushkin <kukushechkin@mac.com>
Update documentation to reflect recent changes
### Motivation:
The documentation was not updated in SLG-0003 or SLG-0005. Concretely,
the examples given in the documentation used the now deprecated
multiparameter methods in `LogHandler`, and the new `LogEvent`-based
method were not listed among the others. Likewise, the new logging
methods (`Logger.trace` etc.) that take an `Error` as a parameter were
not added. Lastly, `LogEvent` had no separate entry.
While the default rendered docs for these were acceptable, it decreased
the discoverability of the new methods, and the examples using
deprecated methods were misleading.
### Modifications:
* Update all code examples to use non-deprecated methods.
* List all new methods on `Logger` and `LogHandler` along the existing
ones.
* Add a minimal file for `LogEvent` to give it the same look as all
other types.
* Update code examples in `.md` files to follow swift format.
### Result:
Documentation reflects the current state and best practices of
`swift-log`.
---------
Co-authored-by: Joseph Heck <j_heck@apple.com>
Co-authored-by: Vladimir Kukushkin <kukushechkin@mac.com>
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>
### Motivation:
SLG-0005 is implemented and released in 1.11.0.
### Modifications:
Update status to 'Approved'.
### Result:
The proposal reflects the actual status.
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.
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.
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.
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.
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.
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.
### 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.
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
`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.
### 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.
### 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.
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>
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.
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>
Add compile-time traits for eliminating log levels from binaries
### Motivation:
Applications often know in advance which log levels will never be needed
in production. For example, a production service might only need warning
and above, while trace and debug levels are only useful during
development. This PR introduces
compile-time traits that completely eliminate unwanted log levels from
binaries, achieving zero runtime overhead for disabled log statements.
### Modifications:
- Added seven `MaxLogLevel*` traits
- Extended benchmarks with the `MaxLogLevelWarning` suite
- Added "Disable log levels during compilation" section to the best
practices guide
### Result:
Users can eliminate unwanted log levels at compile time by specifying
traits in their `Package.swift` dependency declaration.
## Summary
Upgrade GitHub Actions to their latest versions to ensure compatibility
with Node 24, as Node 20 will reach end-of-life in April 2026.
## Changes
| Action | Old Version(s) | New Version | Release | Files |
|--------|---------------|-------------|---------|-------|
| `actions/checkout` |
[`v4`](https://github.com/actions/checkout/releases/tag/v4) |
[`v6`](https://github.com/actions/checkout/releases/tag/v6) |
[Release](https://github.com/actions/checkout/releases/tag/v6) |
pull_request_label.yml |
## Context
Per [GitHub's
announcement](https://github.blog/changelog/2025-09-19-deprecation-of-node-20-on-github-actions-runners/),
Node 20 is being deprecated and runners will begin using Node 24 by
default starting March 4th, 2026.
### Why this matters
- **Node 20 EOL**: April 2026
- **Node 24 default**: March 4th, 2026
- **Action**: Update to latest action versions that support Node 24
### Security Note
Actions that were previously pinned to commit SHAs remain pinned to SHAs
(updated to the latest release SHA) to maintain the security benefits of
immutable references.
### Testing
These changes only affect CI/CD workflow configurations and should not
impact application functionality. The workflows should be tested by
running them on a branch before merging.
Signed-off-by: Salman Muin Kayser Chishti <13schishti@gmail.com>
Enable compile-time elimination of log levels to achieve zero runtime
overhead for logs that will never be needed in production.
### Motivation:
In production deployments, applications often know in advance which log
levels will never be needed. For example, a production service typically
only needs warning and above, while trace and debug levels are
exclusively useful during development. Currently, even with the log
level set to `.warning` at runtime, the code for trace and debug
statements still exists in the binary and incurs overhead.
### Modifications:
The "SLG-0002: Compile-time log level elimination using traits" proposal
doc added.
### Result:
The proposal is ready for implementation.
Depends on https://github.com/apple/swift-nio/pull/3461, which is not
yet merged
### Motivation:
`swift-nio` now has 2 separate workflows for running benchmarks on Linux
and macOS to remove unnecessary noise of skipped macOS benchmarks, see
[`swift-nio` PR](https://github.com/apple/swift-nio/pull/3461) for
details.
### Modifications:
Split Linux and macOS benchmarks into different jobs.
### Result:
Linux and macOS benchmarks are running as different jobs.
Conform `Logger.Level` to `CustomStringConvertible` and
`LosslessStringConvertible`.
### Motivation:
There are libraries, such as Vapor, that add these conformances
privately and `@retroactive`ly. This would avoid having to implement
these conformances manually in each library and would unify and
standardise the implementation.
### Modifications:
Make `Logger.Level` conform to `CustomStringConvertible` and
`LosslessStringConvertible`, adding a public `description` computed
property that returns the `rawValue` and a public initializer that takes
a `description` string, lowercases it, and passes it to the `rawValue`
initializer.
### Result:
`Logger.Level` conforms to `CustomStringConvertible` and
`LosslessStringConvertible`.
Make InMemoryLogging available on all platforms
### Motivation:
Users might want to adopt the in memory logger on lower platform
versions.
### Modifications:
Remove availability annotations by using swift-logs own Lock instead of
Mutex
### Result:
In memory logger can be used on all platforms that swift-log supports
Move single pre-process proposal file to the new location.
### Motivation:
To have all the proposals in one place.
### Modifications:
One .md file moved.
### Result:
All proposals are in one place.
Add an InMemoryLogHandler
### Motivation:
Library maintainers should be able to test that their libraries log what
they expect
### Modifications:
Create a new InMemoryLogging product, which contains an
InMemoryLogHandler
This log handler can be used to make a logger, pass the logger into some
function, and then assert that logs were emitted.
See the tests for example usage
### Future:
For now i have left this very bare-bones. We could in future add
convenience functions. For example
- a function to assert that a particular log message was logged
- a static function to create a logger with this handler
---------
Co-authored-by: Franz Busch <privat@franz-busch.de>
Add simple benchmarks measuring instructions count and allocations when
logging with various log levels.
### Motivation:
Establish the baseline and have automated checks before approaching
performance improvements.
### Modifications:
- Dependency on https://github.com/ordo-one/package-benchmark added
- A new `Benchmarks` sub-package is added
- CI workflows now run benchmarks
### Result:
- CI workflows are running benchmarks on Linux and macOS
- Thresholds are recorded and verified only on macOS
An example of a benchmark failing with a **better** results than
expected:
https://github.com/apple/swift-log/actions/runs/19540944353/job/55950355442
An example of a benchmark failing with a **worse** results than
expected:
https://github.com/apple/swift-log/actions/runs/19569105729/job/56038101552
Provide organization (aka curation) and abstracts for all of the public
types in the library.
### Motivation:
Updates to the documentation to fill in the missing abstracts for the
provided types, updating the language to follow Apple developer content
guidelines, and fixing smaller typos and grammar issues.
### Modifications:
Curation files added to provide organization for public types, ordering
the content to align with the narrative content provided earlier.
Updating API comments, adding abstracts and parameters where missing,
and moving some of the getting started content that was previously in
the main index into a separate article.
### Result:
starting point
```
--- Experimental coverage output enabled. ---
| Abstract | Curated | Code Listing
Types | 69% (11/16) | 38% (6/16) | 25% (4/16)
Members | 57% (54/94) | 3.2% (3/94) | 0.0% (0/94)
Globals | 7.1% (1/14) | 7.1% (1/14) | 7.1% (1/14)
```
Updated:
```
| Abstract | Curated | Code Listing
Types | 94% (15/16) | 94% (15/16) | 38% (6/16)
Members | 85% (80/94) | 97% (91/94) | 0.0% (0/94)
Globals | 14% (2/14) | 100% (14/14) | 7.1% (1/14)
```
---------
Co-authored-by: Honza Dvorsky <honza@apple.com>
Co-authored-by: Franz Busch <privat@franz-busch.de>
Migrating `swift-log` from XCTest to Swift Testing
### Motivation
Swift Testing is a modern alternative to XCTest. Swift Server Ecosystem
packages should serve as reference implementations for modern Swift
features and best practices.
### Modifications
- 1-to-1 migration of test suites, tests, and assertions to Swift
Testing syntax with XCTest import removed
- XCTest references removed from documentation
- `.trace` log level added to relevant tests
- `GlobalLoggerTest` suite serialized to handle global `LoggingSystem`
access (XCTest runs tests serially by default; Swift Testing runs in
parallel, so serializing this suite avoids requiring `swift test
--no-parallel` across all CI and development environments)
### Result
Successfully executes 52 tests with `swift test --disable-xctest`.
Make Swift 6.0 the minimum support version.
### Motivation:
`swift-log` supports 3 latest Swift releases, which is at this point
6.0, 6.1 and 6.2. Swift 5 is no longer supported.
### Modifications:
- Package.swift swift tools
- CI configs
- Imports checking if compiler is <6.0
### Result:
Swift 5 is no longer supported.
Co-authored-by: Honza Dvorsky <honza@apple.com>
Motivation:
Swift 6.2 has been released, we should add it to our CI coverage.
Modifications:
Add additional Swift 6.2 jobs where appropriate in main.yml,
pull_request.yml
Result:
Improved test coverage.
### Motivation:
Some errors do not show up in debug builds. Enabling release mode builds
improves the CI coverage.
### Modifications:
Enable release mode builds for pull requests and scheduled builds on
main.
### Result:
Improved CI coverage.
### Motivation:
`StreamLogHandler` has at some point in time acquired an extra
whitespace:
```
2025-07-18T10:09:12+0100 notice label : hello
^
|
this one is superfluous
```
but we don't typically put spaces in front of `:`s. This PR changes it
to
```
2025-07-18T10:09:12+0100 notice label: hello
^
|
no extra space
```
Additionally, if the label is empty (`""`), then we shouldn't print any
spaces there. So with an empty label, we go from
```
2025-07-18T10:09:12+0100 notice : hello
^^
|
two superfluous spaces
```
to
```
2025-07-18T10:09:12+0100 notice: hello
^
|
no extra spaces
```
### Modifications:
- Remove superfluous space if label is not empty
- Remove two superfluous spaces if label is empty
### Result:
- Somewhat more compact output
- Nicer output
# Motivation
In my previous PR, I overhauled the README and the DocC catalog. While
doing this I removed the guidance around how to implement a log handler.
# Modifications
This PR adds a DocC based guide containing the contents of the previous
README guidance.
# Result
Guidance around log handler implementation in a modern DocC format.
# Motivation
`SwiftLog` was created before DocC existed which meant that most of the
documentation was part of the `README` and we had a pretty bare bones
documentation catalog. We also have a second source of guidelines from
the SSWG. This results in a currently unsatisfying developer experience
where everyone has to go around looking for the content in mostly
undocumented places.
# Modifications
This PR overhauls the `README` and moves most of the content into the
documentation catalog. It also introduces a new section called "Best
practices" that are intended to replace the logging guides on swift.org
so that the content moves closer to where it belongs. To showcase such a
best practice this PR brings over the log level recommendation of
swift.org. The recommendation is mostly the same except that after
recent discussions we wanted to allow libraries to log at `info` level
when they encounter problems which they can't communicate through other
channels e.g. by throwing from a method.
# Result
With this PR we provide a nicer experience to our developers making it
easier for them to get started and understand how to properly log. We
also set ourselves up for expanding on the best practices around
logging.
Remove an inaccurate comment from the code.
### Motivation:
The removed comment incorrectly described the `flush()` method as not
having an effect when the flush mode is set to `.always`. Not only is
this the opposite of the actual behavior, in fact the method itself is
not affected by the flush mode at all; that check is made elsewhere.
Further, at the point where the check is made, the behavior is clearly
spelled out by the code making the check, so moving the comment there
seems redundant. As such, it seemed best to simply remove it altogether.
### Modifications:
Removed a comment.
### Result:
The inaccurate comment can no longer cause confusion.
Co-authored-by: Franz Busch <f.busch@apple.com>
Motivation:
Swift 6.1 has been released, we should add it to our CI coverage.
Modifications:
Add additional Swift 6.1 jobs where appropriate in main.yml,
pull_request.yml
Result:
Improved test coverage.
Motivation:
* Improve test coverage
Modifications:
Enable macOS CI to be run on pull request commits and make the use of
the nightly runner pool for main.yml jobs explicit.
Result:
Improved test coverage.
Motivation:
* Improve test coverage
* Check test pass/fail status
* Monitor CI throughput
Modifications:
Enable macOS CI to be run on all merges to main and on a daily timer.
Result:
Improved test coverage run out-of-band at the moment so we can get a
feeling for if any changes need to be made in the repo or in the CI
pipelines to ensure timely and stable checks.
### Motivation:
Fixes https://github.com/apple/swift-log/issues/278.
### Modifications:
Fixed tests to successfully compile on Fedora 39 and Ubuntu 24.04, which
they previously failed on.
### Result:
Ability to run tests on these two platforms again.
systemd-based log integration
### Motivation:
Using native backend for storing log data
### Modifications:
Add swift-log-systemd to the list of available backends
### Result:
Another one option to use the package with
Enable MemberImportVisibility check on all targets. Use a standard
string header and footer to bracket the new block for ease of updating
in the future with scripts.
# Motivation
Fixes https://github.com/apple/swift-log/issues/330.
We had a few warnings since we were using deprecated POSIX methods on Windows.
# Modification
Moves to the non-deprecated underscored methods.
# Result
Windows build is warning free.
Motivation:
On 5.8, if the experiment existential any setting is enabled and a
consuming package holds an existential of a type from swift-log without
an explicit 'any' then the build will fail.
Modifications:
- Disable the setting
Result:
Users of 5.8 aren't broken
Motivation:
Plugin is no longer required to produce docs.
There are now warnings in the plugin when included
and it will delay build a small amount.
Modifications:
Remove plugin dependency.
Result:
No dependencies.
Motivation:
Latest swift introduces new warnings when deprecated default
implementations are used.
Modifications:
Add new log implementation to NoopLogHandler.
Mark test of old method as deprecated to silence warning.
Result:
Warning free builds on latest swift 6 compiler.
Motivation:
This becomes a critical feature in swift 6.
Modifications:
Add Sendability annotations where required.
Factor out code protected by locks.
Result:
Compiles without warnings with Sendability checking
Motivation:
Calling through protocols is more expensive than many other types of call.
Modifications:
Annotate each protocol usage with any or some keywords.
Result:
Protocol usage now obvious
Motivation:
Feels like a better fit for the problem when a dictionary of bools.
Modifications:
Convert storage to set.
Result:
Fewer lines of code, less waste.
@@ -45,52 +45,71 @@ Linux beefy.machine 4.4.0-101-generic #124-Ubuntu SMP Fri Nov 10 18:29:59 UTC 20
My system has IPv6 disabled.
```
## Writing a Patch
## Make sure Tests work on Linux
A good SwiftLog patch is:
SwiftLog uses Swift Testing to run tests on all supported platforms.
1. Concise, and contains as few changes as needed to achieve the end result.
2. Tested, ensuring that any tests provided failed before the patch and pass after it.
3. Documented, adding API documentation as needed to cover new functions and properties.
4. Accompanied by a great commit message, using our commit message template.
## Run CI checks locally
### Commit Message Template
You can run the Github Actions workflows locally using
[act](https://github.com/nektos/act). To run all the jobs that run on a pull
request, use the following command:
We require that your commit messages match our template. The easiest way to do that is to get git to help you by explicitly using the template. To do that, `cd` to the root of our repository and run:
SwiftLog uses XCTest to run tests on both macOS and Linux. While the macOS version of XCTest is able to use the Objective-C runtime to discover tests at execution time, the Linux version is not.
For this reason, whenever you add new tests **you have to run a script** that generates the hooks needed to run those tests on Linux, or our CI will complain that the tests are not all present on Linux. To do this, merely execute `ruby ./scripts/generate_linux_tests.rb` at the root of the package and check the changes it made.
### Run `./scripts/soundness.sh`
The scripts directory contains a [soundness.sh script](https://github.com/apple/swift-log/blob/main/scripts/soundness.sh)
that enforces additional checks, like license headers and formatting style.
Please make sure to `./scripts/soundness.sh` before pushing a change upstream, otherwise it is likely the PR validation will fail
on minor changes such as a missing `self.` or similar formatting issues.
> The script also executes the above mentioned `generate_linux_tests.rb`.
For frequent contributors, we recommend adding the script as a [git pre-push hook](https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks), which you can do via executing the following command in the project root directory:
```bash
cat << EOF > .git/hooks/pre-push
#!/bin/bash
if [[ -f "scripts/soundness.sh" ]]; then
scripts/soundness.sh
fi
EOF
```
% act pull_request
```
Which makes the script execute, and only allow the `git push` to complete if the check has passed.
To run just a single job, use `workflow_call -j <job>`, and specify the inputs
the job expects. For example, to run just shellcheck:
If you'd like `act` to always run with certain flags, these can be be placed in
an `.actrc` file either in the current working directory or your home
directory, for example:
```
--container-architecture=linux/amd64
--remote-name upstream
--action-offline-mode
```
## Benchmarks
Benchmarks for `swift-log` are in a separate Swift Package in the `Benchmarks` subfolder of this repository.
They use the [`benchmark`](https://github.com/ordo-one/benchmark) plugin.
On Swift versions prior to 6.3 Benchmarks depends on the [`jemalloc`](https://jemalloc.net) memory allocation library, which is used by `benchmark` to capture memory allocation statistics.
An installation guide can be found in the [Getting Started article](https://swiftpackageindex.com/ordo-one/benchmark/documentation/benchmark/gettingstarted#Installing-Prerequisites-and-Platform-Support) of `benchmark`.
Afterwards you can run the benchmarks from CLI by going to the `Benchmarks` subfolder (e.g. `cd Benchmarks`) and invoking:
```
swift package benchmark
```
For more information please refer to `swift package benchmark --help` or the [documentation of `benchmark`](https://swiftpackageindex.com/ordo-one/benchmark/documentation/benchmark).
In the case of formatting issues, you can then `git add` the formatting changes, and attempt the push again.
## 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.
For non-trivial changes that affect the public API, it is good practice to have a discussion phase before writing code. Please follow the [proposal process](Sources/Logging/Docs.docc/Proposals/Proposals.md) to gather feedback and align on the approach with other contributors.
1. Prepare your change, keeping in mind that a good patch is:
- Concise, and contains as few changes as needed to achieve the end result.
- Tested, ensuring that any tests provided failed before the patch and pass after it.
- Documented, adding API documentation as needed to cover new functions and properties.
- Accompanied by a great commit message.
2. Open a pull request at https://github.com/apple/swift-log and wait for code review by the maintainers.
## 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.
For the purpose of tracking copyright, this is the list of individuals and
organizations who have contributed source code to the Swift Logging API.
For employees of an organization/company where the copyright of work done
by employees of that company is held by the company itself, only the company
needs to be listed here.
## COPYRIGHT HOLDERS
- Apple Inc. (all contributors with '@apple.com')
### Contributors
- David Hart <david@hartbit.com>
- Iain Smith <iainsmith@users.noreply.github.com>
- Ian Partridge <i.partridge@uk.ibm.com>
- Johannes Weiss <johannesweiss@apple.com>
- Kevin Sweeney <kevin.t.sweeney@gmail.com>
- Konrad `ktoso` Malawski <ktoso@apple.com>
- Max Moiseev <moiseev@apple.com>
- Tanner <me@tanner.xyz>
- Thomas Krajacic <tkrajacic@users.noreply.github.com>
- Tomer Doron <tomer@apple.com>
**Updating this list**
Please do not edit this file manually. It is generated using `./scripts/generate_contributors_list.sh`. If a name is misspelled or appearing multiple times: add an entry in `./.mailmap`
First things first: This is the beginning of a community-driven open-source project actively seeking contributions, be it code, documentation, or ideas. Apart from contributing to `SwiftLog` itself, there's another huge gap at the moment: `SwiftLog` is an _API package_ which tries to establish a common API the ecosystem can use. To make logging really work for real-world workloads, we need `SwiftLog`-compatible _logging backends_ which then either persist the log messages in files, render them in nicer colors on the terminal, or send them over to Splunk or ELK.
What `SwiftLog` provides today can be found in the [API docs][api-docs].
This repository contains a logging API implementation for Swift.
SwiftLog provides a unified, performant, and ergonomic logging API that can be
adopted by libraries and applications across the Swift ecosystem.
## Getting started
- 📚 **Documentation** and **tutorials** are available on the [Swift Package Index](https://swiftpackageindex.com/apple/swift-log)
- 🚀 **Contributions** are welcome, please see [CONTRIBUTING.md](CONTRIBUTING.md)
- 🪪 **License** is Apache 2.0, repeated in [LICENSE.txt](LICENSE.txt)
- 🔒 **Security** issues should be reported via the process in [Security](https://github.com/apple/swift-log?tab=security-ov-file)
- 🔀 **Available Logging Backends**: SwiftLog is an API package - you'll want to
choose from the many
[community-maintained logging backends](#available-log-handler-backends) for production use
If you have a server-side Swift application, or maybe a cross-platform (for example Linux & macOS) app/library, and you would like to log, we think targeting this logging API package is a great idea. Below you'll find all you need to know to get started.
## Quick Start
#### Adding the dependency
`SwiftLog` is designed for Swift 5. To depend on the logging API package, you need to declare your dependency in your `Package.swift`:
The following snippet shows how to add SwiftLog to your Swift Package:
`SwiftLog` provides for very basic console logging out-of-the-box by way of `StreamLogHandler`. It is possible to switch the default output to `stderr` like so:
`StreamLogHandler` is primarily a convenience only and does not provide any substantial customization. Library maintainers who aim to build their own logging backends for integration and consumption should implement the `LogHandler` protocol directly as laid out in [the "On the implementation of a logging backend" section](#on-the-implementation-of-a-logging-backend-a-loghandler).
For further information, please check the [API documentation][api-docs].
<a name="backends"></a>
#### Selecting a logging backend implementation (applications only)
As the API has just launched, not many implementations exist yet. If you are interested in implementing one see the "Implementation considerations" section below explaining how to do so. List of existing SwiftLog API compatible libraries:
| Repository | Handler Description|
| ----------- | ----------- |
| [Kitura/HeliumLogger](https://github.com/Kitura/HeliumLogger) |a logging backend widely used in the Kitura ecosystem |
| [ianpartridge/swift-log-**syslog**](https://github.com/ianpartridge/swift-log-syslog) | a [syslog](https://en.wikipedia.org/wiki/Syslog) backend|
| [Adorkable/swift-log-**format-and-pipe**](https://github.com/Adorkable/swift-log-format-and-pipe) | a backend that allows customization of the output format and the resulting destination |
| [chrisaljoudi/swift-log-**oslog**](https://github.com/chrisaljoudi/swift-log-oslog) | an OSLog [Unified Logging](https://developer.apple.com/documentation/os/logging) backend for use on Apple platforms. **Important Note:** we recommend using os_log directly as decribed [here](https://developer.apple.com/documentation/os/logging). Using os_log through swift-log using this backend will be less efficient and will also prevent specifying the privacy of the message. The backend always uses `%{public}@` as the format string and eagerly converts all string interpolations to strings. This has two drawbacks: 1. the static components of the string interpolation would be eagerly copied by the unified logging system, which will result in loss of performance. 2. It makes all messages public, which changes the default privacy policy of os_log, and doesn't allow specifying fine-grained privacy of sections of the message. In a separate on-going work, Swift APIs for os_log are being improved and made to align closely with swift-log APIs. References: [Unifying Logging Levels](https://forums.swift.org/t/custom-string-interpolation-and-compile-time-interpretation-applied-to-logging/18799), [Making os_log accept string interpolations using compile-time interpretation](https://forums.swift.org/t/logging-levels-for-swifts-server-side-logging-apis-and-new-os-log-apis/20365). |
| [Brainfinance/StackdriverLogging](https://github.com/Brainfinance/StackdriverLogging) | a structured JSON logging backend for use on Google Cloud Platform with the [Stackdriver logging agent](https://cloud.google.com/logging/docs/agent) |
| [DnV1eX/GoogleCloudLogging](https://github.com/DnV1eX/GoogleCloudLogging) | a client-side library for logging application events in [Google Cloud](https://console.cloud.google.com/logs) via REST API v2. |
| [vapor/console-kit](https://github.com/vapor/console-kit/) | print log messages to a terminal with stylized ([ANSI](https://en.wikipedia.org/wiki/ANSI_escape_code)) output |
| [neallester/swift-log-testing](https://github.com/neallester/swift-log-testing) | provides access to log messages for use in assertions (within test targets) |
| [wlisac/swift-log-slack](https://github.com/wlisac/swift-log-slack) | a logging backend that sends critical log messages to Slack |
| [NSHipster/swift-log-github-actions](https://github.com/NSHipster/swift-log-github-actions) | a logging backend that translates logging messages into [workflow commands for GitHub Actions](https://help.github.com/en/actions/reference/workflow-commands-for-github-actions). |
| [stevapple/swift-log-telegram](https://github.com/stevapple/swift-log-telegram) | a logging backend that sends log messages to any Telegram chat (Inspired by and forked from [wlisac/swift-log-slack](https://github.com/wlisac/swift-log-slack)) |
| [jagreenwood/swift-log-datadog](https://github.com/jagreenwood/swift-log-datadog) | a logging backend which sends log messages to the [Datadog](https://www.datadoghq.com/log-management/) log management service |
| [google/SwiftLogFireCloud](https://github.com/google/swiftlogfirecloud) | a logging backend for time series logging which pushes logs as flat files to Firebase Cloud Storage. |
| [crspybits/swift-log-file](https://github.com/crspybits/swift-log-file) | a simple local file logger (using `Foundation``FileManager`) |
| [sushichop/Puppy](https://github.com/sushichop/Puppy) | a logging backend that supports multiple transports(console, file, syslog, etc.) and has the feature with formatting and file log rotation |
| [luoxiu/LogDog](https://github.com/luoxiu/LogDog) | user-friendly logging with sinks and appenders |
| [ShivaHuang/swift-log-SwiftyBeaver](https://github.com/ShivaHuang/swift-log-SwiftyBeaver) | a logging backend for printing colored logging to Xcode console / file, or sending encrypted logging to [SwiftyBeaver](https://swiftybeaver.com) platform. |
| [Apodini/swift-log-elk](https://github.com/Apodini/swift-log-elk) | a logging backend that formats, caches and sends log data to [elastic/logstash](https://github.com/elastic/logstash) |
| [binaryscraping/swift-log-supabase](https://github.com/binaryscraping/swift-log-supabase) | a logging backend that sends log entries to [Supabase](https://github.com/supabase/supabase). |
| [MahdiBM/DiscordBM](https://github.com/MahdiBM/DiscordBM) | a Discord client package containing a standalone [DiscordLogger library](https://github.com/MahdiBM/DiscordBM/blob/discord-logger/README.md#discord-logger) |
| Your library? | [Get in touch!](https://forums.swift.org/c/server) |
## What is an API package?
Glad you asked. We believe that for the Swift on Server ecosystem, it's crucial to have a logging API that can be adopted by anybody so a multitude of libraries from different parties can all log to a shared destination. More concretely this means that we believe all the log messages from all libraries end up in the same file, database, Elastic Stack/Splunk instance, or whatever you may choose.
In the real-world however, there are so many opinions over how exactly a logging system should behave, what a log message should be formatted like, and where/how it should be persisted. We think it's not feasible to wait for one logging package to support everything that a specific deployment needs whilst still being easy enough to use and remain performant. That's why we decided to cut the problem in half:
1. a logging API
2. a logging backend implementation
This package only provides the logging API itself and therefore `SwiftLog` is a 'logging API package'. `SwiftLog` (using `LoggingSystem.bootstrap`) can be configured to choose any compatible logging backend implementation. This way packages can adopt the API and the _application_ can choose any compatible logging backend implementation without requiring any changes from any of the libraries.
Just for completeness sake: This API package does actually include an overly simplistic and non-configurable logging backend implementation which simply writes all log messages to `stdout`. The reason to include this overly simplistic logging backend implementation is to improve the first-time usage experience. Let's assume you start a project and try out `SwiftLog` for the first time, it's just a whole lot better to see something you logged appear on `stdout` in a simplistic format rather than nothing happening at all. For any real-world application, we advise configuring another logging backend implementation that logs in the style you like.
## The core concepts
### Loggers
`Logger`s are used to emit log messages and therefore the most important type in `SwiftLog`, so their use should be as simple as possible. Most commonly, they are used to emit log messages in a certain log level. For example:
```swift
//logginganinformationalmessage
logger.info("Hello World!")
//ouch,somethingwentwrong
logger.error("Houston, we have a problem: \(problem)")
```
### Log levels
The following log levels are supported:
-`trace`
-`debug`
-`info`
-`notice`
-`warning`
-`error`
-`critical`
The log level of a given logger can be changed, but the change will only affect the specific logger you changed it on. You could say the `Logger` is a _value type_ regarding the log level.
### Logging metadata
Logging metadata is metadata that can be attached to loggers to add information that is crucial when debugging a problem. In servers, the usual example is attaching a request UUID to a logger that will then be present on all log messages logged with that logger. Example:
```swift
varlogger=logger
logger[metadataKey:"request-uuid"]="\(UUID())"
logger.info("hello world")
```
will print
```
2019-03-13T18:30:02+0000 info: request-uuid=F8633013-3DD8-481C-9256-B296E43443ED hello world
```
with the default logging backend implementation that ships with `SwiftLog`. Needless to say, the format is fully defined by the logging backend you choose.
## On the implementation of a logging backend (a `LogHandler`)
Note: If you don't want to implement a custom logging backend, everything in this section is probably not very relevant, so please feel free to skip.
To become a compatible logging backend that all `SwiftLog` consumers can use, you need to do two things: 1) Implement a type (usually a `struct`) that implements `LogHandler`, a protocol provided by `SwiftLog` and 2) instruct `SwiftLog` to use your logging backend implementation.
A `LogHandler` or logging backend implementation is anything that conforms to the following protocol
Instructing `SwiftLog` to use your logging backend as the one the whole application (including all libraries) should use is very simple:
LoggingSystem.bootstrap(MyLogHandler.init)
### Implementation considerations
`LogHandler`s control most parts of the logging system:
#### Under control of a `LogHandler`
##### Configuration
`LogHandler`s control the two crucial pieces of `Logger` configuration, namely:
- log level (`logger.logLevel` property)
- logging metadata (`logger[metadataKey:]` and `logger.metadata`)
For the system to work, however, it is important that `LogHandler` treat the configuration as _value types_. This means that `LogHandler`s should be `struct`s and a change in log level or logging metadata should only affect the very `LogHandler` it was changed on.
However, in special cases, it is acceptable that a `LogHandler` provides some global log level override that may affect all `LogHandler`s created.
##### Emitting
- emitting the log message itself
### Not under control of `LogHandler`s
`LogHandler`s do not control if a message should be logged or not. `Logger` will only invoke the `log` function of a `LogHandler` if `Logger` determines that a log message should be emitted given the configured log level.
## Source vs Label
A `Logger` carries an (immutable) `label` and each log message carries a `source` parameter (since SwiftLog 1.3.0). The `Logger`'s label
identifies the creator of the `Logger`. If you are using structured logging by preserving metadata across multiple modules, the `Logger`'s
`label` is not a good way to identify where a log message originated from as it identifies the creator of a `Logger` which is often passed
around between libraries to preserve metadata and the like.
If you want to filter all log messages originating from a certain subsystem, filter by `source` which defaults to the module that is emitting the
log message.
## Security
Please see [SECURITY.md](SECURITY.md) for SwiftLog's security process.
## Design
This logging API was designed with the contributors to the Swift on Server community and approved by the [SSWG (Swift Server Work Group)](https://swift.org/server/) to the 'sandbox level' of the SSWG's [incubation process](https://github.com/swift-server/sswg/blob/master/process/incubation.md).
While Swift Package Manager (SPM) is the primary build system for development and testing, CMake build support is also available for integrated or mixed build environments if needed. Note that tests are not included in the CMake build, they are managed through Swift Package Manager with `swift test`.
Each `Entry` is equatable and exposes `level`, `message`, `metadata`, and `error`.
The handler log level defaults to ``Logger/Level/info``; set `handler.logLevel = .trace` before you use it to
capture lower levels.
### Capture logs from code that reads `Logger.current`
When the code you want to test reads the task-local ``Logger/current`` instead of taking a parameter, bind an `InMemoryLogHandler` for the scope of that by using ``withLogger(logLevel:handler:metadata:_:)-2pd9p``.
The handler shares its storage by reference, so the copy you hold sees what was logged.
Bind the handler for the scope of the call and validate the captured entry:
> Note: In special cases, it is acceptable for a log handler to provide
> global log level overrides that may affect all log handlers created.
### Example implementation
Here's a complete example of a simple print-based log handler:
```swift
import Foundation
import Logging
public struct PrintLogHandler: LogHandler {
private let label: String
public var logLevel: Logger.Level = .info
public var metadata: Logger.Metadata = [:]
public init(label: String) {
self.label = label
}
public func log(event: LogEvent) {
let timestamp = ISO8601DateFormatter().string(from: Date())
let levelString = event.level.rawValue.uppercased()
// Merge handler metadata with message metadata
let combinedMetadata = Self.prepareMetadata(
base: self.metadata,
explicit: event.metadata
)
// Format metadata
let metadataString = combinedMetadata.map { "\($0.key)=\($0.value)" }.joined(separator: ",")
// Create log line and print to console
let logLine = "\(label) \(timestamp) \(levelString) [\(metadataString)]: \(event.message)"
print(logLine)
}
public subscript(metadataKey key: String) -> Logger.Metadata.Value? {
get {
return self.metadata[key]
}
set {
self.metadata[key] = newValue
}
}
static func prepareMetadata(
base: Logger.Metadata,
explicit: Logger.Metadata?
) -> Logger.Metadata? {
var metadata = base
guard let explicit else {
// all per-log-statement values are empty
return metadata
}
metadata.merge(explicit, uniquingKeysWith: { _, explicit in explicit })
return metadata
}
}
```
### Constructing handlers that need more than a label
Many log handler backends need more than a `label` in order to construct them: a file path, a remote address, credentials, or
a buffer. A handler is an ordinary value that you construct, so nothing constrains its
initializer — it can take any parameters it needs, and it can `throw`. There is no
protocol-required `init(label:)`. The single `label` argument on factory methods such as
`StreamLogHandler.standardOutput(label:)` is a convention, not a requirement.
Open expensive or fallible resources, such as a file, a socket, early and up front in your own initializer that can `throw`, so that failures surface at setup time.
``LogHandler/log(event:)`` cannot throw, so an error deferred to logging time has nowhere to go.
Keep the handler `struct` cheap and copyable by placing any shared resource behind a thread-safe reference type.
Value semantics apply to a handler's *configuration* — its level and metadata — not its *destination*, so copies writing to
the same file are correct and expected.
The `FileLogHandler` below opens its file once, in an initializer that throws and exception when you create it with an overlapping `Destination`.
The handler `struct` itself stays a cheap, copyable value:
```swift
import Foundation
import Logging
import Synchronization
/// A log handler that appends formatted log lines to a file on disk.
public struct FileLogHandler: LogHandler {
/// The shared, thread-safe destination. Open it once, then share it across handlers: because
/// the destination is a reference type, all those value-semantic handlers write through a single
/// locked file handle.
public final class Destination: @unchecked Sendable {
private let fileHandle: Mutex<FileHandle>
/// Opens `url` for appending. All validation happens here, at setup time.
// Code in this scope reads the handler through Logger.current.
}
```
The `try` on `Destination` is where setup fails if the path is unwritable: validation happens
before the logger is constructed, so you never need a throwing factory overload.
Use the same pattern for handlers that connect to a remote service:
- validate and connect up front
- keep ``LogHandler/log(event:)`` non-blocking by buffering onto a background task
- provide a `close()` or `shutdown()` (or use [Swift Service Lifecycle](https://github.com/swift-server/swift-service-lifecycle) service) to flush on shutdown
For runtime failures the handler can't avoid, such as a full disk or a broken pipe, degrade gracefully inside `log(event:)` by dropping the log message, retrying, or reporting to `stderr`.
Never call `fatalError` on the logging path.
### Advanced features
#### Metadata providers
Metadata providers allow you to dynamically add contextual information to all
log messages without explicitly passing it each time. Common use cases include
request IDs, user sessions, or trace contexts that should be included in logs
throughout a request's lifecycle.
```swift
import Foundation
import Logging
public struct PrintLogHandler: LogHandler {
private let label: String
public var logLevel: Logger.Level = .info
public var metadata: Logger.Metadata = [:]
public var metadataProvider: Logger.MetadataProvider?
public init(label: String) {
self.label = label
}
public func log(event: LogEvent) {
let timestamp = ISO8601DateFormatter().string(from: Date())
let levelString = event.level.rawValue.uppercased()
// Merge handler metadata with message metadata
let combinedMetadata = Self.prepareMetadata(
base: self.metadata,
provider: self.metadataProvider,
explicit: event.metadata
)
// Format metadata
let metadataString = combinedMetadata.map { "\($0.key)=\($0.value)" }.joined(separator: ",")
// Create log line and print to console
let logLine = "\(label) \(timestamp) \(levelString) [\(metadataString)]: \(event.message)"
print(logLine)
}
public subscript(metadataKey key: String) -> Logger.Metadata.Value? {
Collaborate on API changes to SwiftLog by writing a proposal.
## Overview
For non-trivial changes that affect the public API, the SwiftLog project adopts a lightweight version of the [Swift Evolution](https://github.com/apple/swift-evolution/blob/main/process.md) process.
Writing a proposal first helps discuss multiple possible solutions early, apply useful feedback from other contributors, and avoid reimplementing the same feature multiple times.
While it's encouraged to get feedback by opening a pull request with a proposal early in the process, it's also important to consider the complexity of the implementation when evaluating different solutions. For example, this might mean including a link to a branch containing a prototype implementation of the feature in the pull request description.
> Note: The goal of this process is to help solicit feedback from the whole community around the project, and we will continue to refine the proposal process itself. Use your best judgement, and don't hesitate to propose changes to the proposal structure itself!
### Steps
1. Make sure there's a GitHub issue for the feature or change you would like to propose.
2. Duplicate the `SLG-NNNN.md` document and replace `NNNN` with the next available proposal number.
3. Link the GitHub issue from your proposal, and fill in the proposal.
4. Open a pull request with your proposal and solicit feedback from other contributors.
5. Once a maintainer confirms that the proposal is ready for review, the state is updated accordingly. The review period is 7 days, and ends when one of the maintainers marks the proposal as Ready for Implementation, or Deferred.
6. Before the pull request is merged, there should be an implementation ready, either in the same pull request, or a separate one, linked from the proposal.
7. The proposal is considered Approved once the implementation, proposal PRs have been merged, and, if originally disabled by a feature flag, feature flag enabled unconditionally.
If you have any questions, ask in an issue on GitHub.
While global metadata attributes may be manually set on a `LogHandler` level, there's currently no way of reliably providing contextual, automatically propagated, metadata when logging with swift-log.
To benefit from tools such as [Distributed Tracing](https://github.com/apple/swift-distributed-tracing) it is necessary for libraries to make use of the trace information.
- [Lightweight proposals process description](https://github.com/apple/swift-log/blob/main/Sources/Logging/Docs.docc/Proposals/Proposals.md)
### Introduction
Add Swift package traits to allow applications to compile out less severe log levels, completely eliminating their runtime overhead from the final binary.
### Motivation
In production deployments, applications often know in advance which log levels will never be needed. For example, a production service typically only needs warning and above, while trace and debug levels are exclusively useful during development. Currently, even with the log level set to `.warning` at runtime, the code for trace and debug statements still exists in the binary and incurs overhead.
For performance-critical applications or resource-constrained environments, this overhead is unacceptable. Applications need a way to completely remove unnecessary log levels at compile time, achieving zero runtime cost.
Before this proposal, the only workarounds were:
- Manually wrapping log statements in `#if DEBUG` checks (error-prone and verbose)
- Accepting the runtime overhead (unacceptable for many use cases)
### Proposed solution
This proposal introduces seven package traits that correspond to maximum log level thresholds. Applications specify a trait when declaring their dependency on SwiftLog, and all less severe log levels are completely compiled out.
In your `Package.swift`:
```swift
dependencies:[
.package(
url:"https://github.com/apple/swift-log.git",
from:"1.0.0",
traits:["MaxLogLevelWarning"]
)
]
```
With `MaxLogLevelWarning` enabled:
```swift
//Thesebecomeno-ops(compiledoutcompletely):
logger.trace("This will not be in the binary")
logger.debug("This will not be in the binary")
logger.info("This will not be in the binary")
logger.notice("This will not be in the binary")
logger.log(level:.debug,"This will not log anything")
//Theseworknormally:
logger.warning("This still works")
logger.error("This still works")
logger.critical("This still works")
logger.log(level:.error,"This still works")
```
### Detailed design
The seven available traits, ordered from most permissive to most restrictive, are:
```swift
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)"),
.default(enabledTraits:[]),
]
```
By default (when no traits are specified), all log levels remain available.
Traits are additive: if multiple max level traits are specified in the dependency graph, the most restrictive one takes effect. This ensures that if any dependency requests stricter elimination, the entire build respects it.
> Important: Traits should only be set by applications, not libraries, as any trait defined in a transitive dependency will affect the entire dependency resolution tree.
For the generic `log(level:)` method, the implementation switches behavior based on whether any trait is enabled:
This approach adds a minimal switch statement overhead when traits are enabled, but allows the level-specific methods' compile-time elimination to work even when called through `log(level:)`. When no traits are enabled, the original zero-overhead path is preserved. Level-specific methods has no additional overhead.
### API stability
**For existing `Logger` users:**
- When no traits are enabled (the default), behavior is identical to before
- Users can opt in to traits at the application level without modifying any source code
**For existing `LogHandler` implementations:**
- No changes are required to any `LogHandler` implementation
### Future directions
No future directions identified.
### Alternatives considered
#### Per-log-level traits
An alternative approach would be to define one trait per log level that could be individually disabled:
```swift
traits:[
.trait(name:"DisableTraceLogs"),
.trait(name:"DisableDebugLogs"),
.trait(name:"DisableInfoLogs"),
.trait(name:"DisableNoticeLogs"),
.trait(name:"DisableWarningLogs"),
.trait(name:"DisableErrorLogs"),
.trait(name:"DisableCriticalLogs"),
]
```
Users would specify multiple traits to eliminate multiple levels:
This approach was rejected in favor of a `MaxLogLevel` semantics to make it less verbose to use the functionality and to be aligned with the similar functionality in logging packages in other languages users might already be familiar with.
- [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{
trysomeThrowingFunc()
}catch{
logger.warning("Something went wrong")//Wanttosomehowattachinformationabouttheerror
}
```
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{
trysomeThrowingFunc()
}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.
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.
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.
With this handler in the chain, any metadata value without an explicit sensitivity annotation is treated as sensitive
by default — a "deny by default" policy that individual call sites can override with `.public`.
Loaded 100 of 175 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.