### Motivation:
`MultiplexLogHandler.metadataProvider`'s setter only forwards the new
provider to the underlying handlers. Since #522, `log(event:)` also
merges the provider passed to `init(_:metadataProvider:)` on top of the
underlying handlers' metadata, so after a set that old provider still
overrides the new one for conflicting keys, setting `nil` doesn't remove
it, and the getter keeps returning it.
This shows up through `Logger(label:metadataProvider:)`, which calls the
factory and then sets `handler.metadataProvider`. If the bootstrapped
factory returns a `MultiplexLogHandler` with its own provider, the
provider the library passed is silently overridden. With a plain handler
the same code uses the library's provider, which is what
`Logger(label:metadataProvider:)` documents ("the custom metadata
provider this logger should invoke, instead of the system wide
bootstrapped one").
### Modifications:
- In the setter, also replace the multiplex handler's own provider with
the new value. It is still forwarded to the underlying handlers as
before.
- Document the setter.
- Add regression tests: setting a provider replaces the initializer's
provider for one and two handlers, and setting `nil` clears it (both the
getter and emitted logs). Another test covers an underlying handler that
doesn't support metadata providers.
I kept forwarding to the underlying handlers and replace the multiplex
handler's own provider as well, rather than clearing it. Clearing it
would drop provider metadata for underlying handlers that use the
default `metadataProvider` implementation in the
`Logger(label:metadataProvider:)` case, which works today.
### Result:
After `handler.metadataProvider = p`, logs and the getter use `p`. After
`handler.metadataProvider = nil`, no provider metadata is added. In the
common setup where the factory passes its provider into the
`MultiplexLogHandler` initializer, the number of provider calls per log
stays the same. When the multiplex handler had no provider of its own, a
set now also applies the provider once at the multiplex level, so
underlying handlers without provider support get its metadata too.
The new tests fail on main and pass with this change. All tests pass
locally on macOS (Swift 6.3.3), and `swift format lint` is clean on the
changed files. I couldn't run the benchmarks locally.
This change was drafted with Claude Code (claude-opus-5-5); the test
results above are from the runs described.
When a module name (via `-module-alias`) is a raw identifier (SE-0451),
`#fileID` formats the module component enclosed in backticks (for
example, `` `/a/b/c`/File.swift ``). If the raw identifier contains '/',
splitting on the first '/' in `#fileID` truncates the module name at the
slash inside the backticks.
When `#fileID` starts with a backtick, advance past the matching closing
backtick before searching for the '/' separator that ends the module
name, preserving the enclosing backticks.
Fixes#498
## Problem
`MultiplexLogHandler` had inconsistent metadata priority:
- `subscript(metadataKey:)` reads the value from the **first** handler
that has the key (documented: "the first handler's values are more
important")
- `metadata` (full dictionary) merged handlers **last-wins**, so the
value came from the **last** handler with that key
## Fix
The `metadata` getter now merges handlers in their initialization order,
keeping the already-stored value on conflicts — the **first handler
wins**, matching the subscript and the docs.
The multiplex handler's own `metadataProvider` still takes priority over
all underlying handlers/providers, matching its documented role ("runs
after all metadata providers of the multiplexed handlers").
## Testing
- Updated `multiplexLogHandlerMetadata_readingHandlerMetadata` and
`multiplexMetadataProviderSet`, which encoded the last-wins behavior
- Extended `multiplexMetadataProviderSet` with subscript-vs-dictionary
consistency checks (both must give the first handler's value on
conflicting keys, including provider-provided metadata)
- Full suite: 174 tests in 17 suites, all passing
---------
Co-authored-by: awaisdev <awais@airtechsolutions.pk>
Co-authored-by: awaisdev5765 <awaisdev5765@users.noreply.github.com>
Co-authored-by: Vladimir Kukushkin <kukushechkin@apple.com>
There's an unnecessary optional return here that prevents the example
from compiling.
### Motivation:
It took me a moment to figure out how to fix this, but in the end it was
very straightforward. The `prepareMetadata` doesn't ever need to return
nil.
### Modifications:
A small type change fixes the compilation errors in `log(event:)`
### Result:
The example in the documentation can now be used unmodified.
`StreamLogHandler` timestamps only have second precision, so when
several log lines land in the same second you can't tell what order they
happened in.
This adds an **opt-in** setting for millisecond precision. The default
output doesn't change, since some users parse it.
**Changes**
- Adds `public var timestampPrecision: TimestampPrecision = .seconds` to
`StreamLogHandler`.
- Adds a nested `TimestampPrecision` enum (`@nonexhaustive`, `Sendable`)
with `.seconds` and `.milliseconds`.
- With `.milliseconds`, the timestamp includes a 3-digit millisecond
field:
- default (`.seconds`): `2021-11-06T18:47:14+0300 info myapp: message`
- `.milliseconds`: `2021-11-06T18:47:14.123+0300 info myapp: message`
- How each platform reads the time:
- Darwin, Linux and Android use `clock_gettime(CLOCK_REALTIME)`.
- Windows uses `_ftime64_s`.
- WASI only has second resolution (`CLOCK_REALTIME` isn't importable
there), so `.milliseconds` always prints `.000`. The doc comments say
so.
- Both new symbols are added to the DocC reference page.
**Tests**
- The default precision is `.seconds`.
- `.milliseconds` produces the expected format (checked with a regex).
- Milliseconds are always zero-padded to 3 digits.
- The existing output-format tests are unchanged and still pass, which
confirms the default format.
Fixes#212
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.
* minimal DocC markdown to order Logger.Levels
Motivation:
When viewed in documentation generated by DocC, the enumeration levels
are ordered alphabetically, removintg the implied ordering in the
source. The written overview of the enum relies on that ordering to make
sense.
Modifications:
Adding a single file that provides structure to Logging/Logger/Levels
within DocC generated documentation.
Result:
When imported into a project that leverages Swift 5.6 (such as Vapor),
the generated documentation for the levels provided by
Logging/Logger/Levels are displayed in the order intended/expected by
the documentation.
* Adding a Swift 5.6 version of Package.swift
Motivation:
Per DocC team, an updated version is required for the DocC changes
to be picked up and reflected in generated dcumentation, even for
upstream projects already using swift 5.6 or later.
Modifications:
Adding Package.Swift@5.6 with the swift version updated.
Result:
Hopefully, documentation updates in DocC generated content will be
reflected.
* Updating linuxmain test generation for <swift5.6
Motivation:
To appease CI, added #if statements into generated LinuxMain
content to handle conditional compilation with Swift 5.6 and later.
Modifications:
Added #if statements to test generating script and re-ran the script
Result:
CI will hopefully pass.
* also guard the LinuxMain file
* Force using test discovery on 5.6+ even though tools version is latest
but LinuxMain exists
* cleanup
* simplify docc links
* formatting revert
* ignore Package-swift5.6.swift from soundness license check
Co-authored-by: Konrad `ktoso` Malawski <konrad_malawski@apple.com>
motivation: adjust to swift 5.6
changes:
* define sendable shims for protocols and structs that may be used in async context
* adjust tests
* add a test to make sure no warning are emitted
motivation: source-kitten has changed how its invoked
changes:
* invoke source-kitten with the correct flags
* make location of source-kitten source checkout more robust
This adds support for running the tests on Windows. However, running
the tests on Windows requires SPM currently. While it is possible to
enable executing tests with CMake, the expectation is that SPM builds
would be the most common and CMake is largely used for bootstrapping.
The changes here require alterations to remove the POSIX threading to
get the thread ID. Additionally, pipes on Windows are not similar to
pipes on Unix platforms. Finally, we must add Windows to the platform
list, which is temporary (it would be better to use test discovery in
SPM).
Windows recommends the safety extension usage which in this case
explicitly allow you to be informed of failures. This just avoids an
annoying warning when using logging in projects.
Motivation:
`LogHandler` facotories are given a label as input and return a
`LogHandler`. Since the no-op handler doesn't care about the label
callers must provide a thunk: `{ _ in SwiftLogNoOpLogHandler() }`.
That's fine but slightly more annoying to type than it needs to be.
Modifications:
- Add `SwiftLogNoOpLogHandler.init(_: String)`
Result:
Users can create a logger with the no-op handler with:
```swift
Logger(label: "foo", factory: SwiftLogNoOpLogHandler.init)
```
instead of:
```swift
Logger(label: "foo", factory: { _ in SwiftLogNoOpLogHandler() })
```
Motivation:
Right now, we use the full path (`#file`) for the logging as well as for
parsing out the module name (which goes into `source` by default).
This has two problems:
1. The file names contain the build server's full path, ie. aren't
portable across different compiles (and are very long).
2. The module name parsing fails if we log from a file that's not in a
directory named just like the module.
Modification:
Switch `#file` for `#fileID`. This changes a bunch of things:
- `source` is always the module name by default (great!)
- `file` changes from `/the/full/path/on/disk` to `ModuleName/FileBaseName.swift` (I think better, but it's a change)
Result:
`source` is more correct, `file` will be different.
Replaced `fputs` with `fwrite`, added test and made spelling corrections
Motivation:
If a 0 byte is logged, `fputs` would not output the content after the 0 byte making it harder to debug (see #180). `fwrite` uses a count argument so content after 0 byte can be logged.
Modifications:
Replaced `fputs` with the correct call to `fwrite`. Added helper internal func `contiguousUTF8(_ string: String) -> String.UTF8View`. Added `testStdioOutputStreamWrite()` to test ability to log content after 0 byte.
Result:
Improved debugging experience
Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
Motivation:
When using the same Logger across an application in combination
with the default StreamLogHandler, it may be difficult to differentiate
between logs produced by different modules. ServiceLifecycle works around
this by prepending the log message with [Lifecycle], which is what I'd like
to do StreamLogHandler by default, leveraging the source log parameter.
Modifications:
StreamLogHandler will include the source in brackets right before
the log message when writing a log.
Result:
Logs from different modules are easily differentiable when produced
using the same Logger instance.
Motivation:
When using the recently re-introduced source-less version of trace, the function parameter that reaches the underlying LogHandler is wrong.
Modifications:
Pass the function parameter to trace with source parameter.
Result:
With these changes, the function parameter that reaches the underlying LogHandler has the correct value.
Motivation:
- When `source:` was added in #135, the API was accidentally broken
despite source compatability.
Modifications:
- Add back source-less API calls which defer to the decls with source.
- Note we can't deprecate the calls we're adding back:
`log.info("some message")` refers to the implementation we're adding
back rather and would therefore require users to explicitly specify a source
to suppress the deprecation warning message.
Result:
- API is no longer broken.
Co-authored-by: Konrad `ktoso` Malawski <ktoso@apple.com>
motivation: we are not actually using symbolicate-linux-fatal in any meaningful way in CI and it's pinned to the master branch which has been removed
changes: remove symbolicate-linux-fatal fetching from Docker
Motivation:
The stream log handler doesn't print metadata in a stable order. While
swift-log is an API package and shouldn't provide all the bells and
whistles for formatting logs, it should make the default log handler
at least somewhat sensible.
Modifications:
- Sort the metadata by key when 'prettifying' it
Result:
- The stream log handler emits logs with metadata in a stable order
- Resolves#128
* =multiplex #139 more properly handle logLevel in multiplex handler
* swift 5.0 needs explicit return
* no need to loop over the settings
* =metadata MultiplexLogHandler now consistently handles metadata read/write
* Apply suggestions from code review
Co-authored-by: Cory Benfield <lukasa@apple.com>
Co-authored-by: George Barnett <gbrntt@gmail.com>
Co-authored-by: Cory Benfield <lukasa@apple.com>
Co-authored-by: George Barnett <gbrntt@gmail.com>
* Update comments in Locks.swift to correctly reflect the Windows implementation and to correctly describe the operation of the `ReadWriteLock`.
* Add error messages to the preconditions on pthread function call return values. Copied from NIO's `Lock` implementation.
* In `Lock`, create the underlying mutex (where applicable) using `PTHREAD_MUTEX_ERRORCHECK`. Copied from NIO's `Lock` implementation. Performance loss is minor on Xenial, Bionic, CentOS, and AmazonLinux; no loss was measurable on Focal at all.
* On Windows, correctly set the `shared` flag in `ReadWriteLock` so the correct `ReleaseSRWLock*()` function is called in `unlock()`. It appears that in practice Windows does not actually care whether the correct release function is called for the type of lock the thread was holding, but this is undocumented (along with most other semantics of `SRWLOCK`) and thus can not be relied upon.
* Fix formatting (that's what I get for copy-pasting from NIO verbatim)
Motivation:
Swift 5.3 will keep `#file` == `#filePath` but starts warning if you
pass `#file` to an argument that's `#filePath` defaulted (XCTest).
Modification:
- Replace `#file` with `(#file)` to silence the warning. In Swift 5.3
`#file` == `#filePath`.
Result:
No warnings
Motivation:
The current docstring seems to be missing some words that indicate
when a 'trace' log level is more appropriate than a 'debug' log
level. This was brought up in https://github.com/vapor/docs/issues/463
and has been fixed there. This PR is being submitted to the upstream
project as a courtesy.
Modifications:
This PR adds a clause to the docstring of the 'trace' log level to
clearly indicate when this log level shuld be used.
Result:
The docstring for the 'trace' log level will mirror the structure of
the docstring for the 'debug' log level, but will include a clear
opinion of when the 'trace' log level is appropriate.
Signed-off-by: zach wick <zach@zachwick.com>
Motivation:
SwiftLog is meant as a base logging library so users will often overload
certain functions with their own specialised and opinionated overloads.
Modification:
Add a test as demonstration.
Result:
More tests.
motivation: docs scripts is broken on selinux due to restriction on ssh-agent
changes: change the jazzy worksapce to a directory accessible by the CI node so we can push from the agent instead of from the docker container
The README file links to an implementation of a backend that uses os_log.
However, 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 also changes the default privacy scheme used by os_log and make all message
private, which runs the risk of no message getting logged. Update the
README to capture this drawback. Also, link to the on-going effort on
improving os_log Swift APIs and aligning it with swift-log.
motivation: more secured ci setup
changes:
* enable :z selinux flag on bind mounts so we can enable selinux on ci
* drop potentially exploitable capabilities from docker-compose
motivation: better ci testing
changes:
* add api breakage script to test api breakage in ci
* add "shell" utility docker-compose task to run api breakage script
* change test task to treat warning as errors
* prepare to test with thread sanitizer in 5.1
motivation: support swift 5.1
changes:
* add docker compose file for swift 5.1, will add CI job once merged
* update swiftformat version to 0.40.12
* fix warning in tests
* add flush api to default stdout/stderr logger
motivation: default logger may not flush the streams on crush, so need to make flushing moe explicit
changes:
* add a constructor argument to control flushing behaviour, default to "everytime"
* add a "flush" method to allow user defined flush timing. this api is now internal but we could expose it if there is a need
* add tests
* fixup
* better documentation around MetadataValue being expressible by literals
Motivation:
In many examples, I could see that users seem to construct metadata
values using the explicit enum cases `.string("foo")`, `.array(...)`, as
well as `.dictionary(...)`. It's much more readable and easier to type
to just use `"foo"`, `["bar", "buz"]`, and `["qux": "quux"]` and rely on
the `ExpressibleBy...Literal` conformances.
Modifications:
Add the docs and examples.
Result:
Hopefully, users will read the docs and write more idiomatic code.
* Update Logging.swift
motivaiton: unified format
changes:
* use official docker image 🎉
* fix outstanding formatting issues
* add a call to swiftformat as part of sanity script
* fix sanity script language check debugging statements
LoggingFormatAndPipe provides a Swift Logging API Handler which allows you to customized both your log messages' formats as well as their destinations.
motivation: @ianpartridge implemented a backend for syslog (awesome :-)) so we should link to it so people are easily able to discover it (and any other future implementations we'd want to link to).
Expose `StreamLogHandler` to the public which replaces the previously internal `StdoutLogHandlers`. Users can choose now the output stream, while `stdout` is the default.
### Motivation:
As discussed on #51 and #60
### Modifications:
Rename `StdoutLogHandler` to `StreamLogHandler` and provide 2 factory methods `standardOutput(label:)` and `standardError(label:)` for using during bootstrapping.
### Result:
Users who adopt other logging backends during `LoggingSystem` bootstrapping will still be able to use the default log handler to get very basic console output to their choice of `stdout` or `stderr`.
### Example:
```
// Log to both stderr and stdout for good measure
LoggingSystem.bootstrap {
MultiplexLogHandler([
FancyLoggingBackend(label: $0),
StreamLogHandler.standardError(label: $0),
StreamLogHandler.standardOutput(label: $0)
])
}
```
Motivation:
Users ask for a CocoaPod. Unfortunately, the CocodPod `SwiftLog` is
already taken, so I went for `SwiftLogAPI`.
Modification:
Add a podspec generator.
Result:
Happier users.
Motivation:
Allowing readers of the API documentation to drill into the implementation of documented declarations can be educational and helpful for debugging, among several other reasons.
Modifications:
Add --github-file-prefix appending the current version in order to keep stable links. This means that documentation generated from any non-release revision may resolve incorrectly. This can be refined in the doc generation script later if it is deemed problematic by resolving to the commit sha if it doesn't exactly align with the version.
Result:
Users will be able to click a 'Show on GitHub' for all documented API declarations.
motivation: use consistent formatting
changes: update generate_linux_tests to match the formatting rules we use: `swiftformat --self insert --patternlet inline --stripunusedargs unnamed-only --comments ignore`
The original issue that was https://bugs.swift.org/browse/SR-9687 has been closed as duplicate of https://bugs.swift.org/browse/SR-9686
Perhaps it would be less confusing for others reading the code if we linked to the not-closed issue?
Not a big deal, just something I noticed; if we want to continue to link to the original issue that's fine too.
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).
## How to contribute your work
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`
A Logging API package for Swift. Version `1.0.0` requires Swift 5.0 but in due course we will also tag a mostly compatible version for Swift 4 (which will be tagged `0.x`) to ease your transition towards Swift 5.
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 `swift-log` itself, there's another huge gap at the moment: `swift-log` 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 `swift-log`-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.
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.
What `swift-log` provides today can be found in the [API docs][api-docs].
- 📚 **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
## Great, what's the tl;dr
## Quick Start
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.
#### Adding the dependency
`swift-log` is designed for Swift 5, the `1.0.0` release requires Swift 5 (however we will soon tag a `0.x` version that will work with Swift 4 for the transition period). 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:
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.
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`.
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 `swift-log` is a 'logging API package'. `swift-log` (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 `swift-log` 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 `swift-log`, 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, they match the [syslog severity levels](https://en.wikipedia.org/wiki/Syslog#Severity_level):
-`debug`
-`info`
-`notice`
-`warning`
-`error`
-`critical`
-`alert`
-`emergency`
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 `swift-log`. 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 `swift-log` consumers can use, you need to do two things: 1) Implement a type (usually a `struct`) that implements `LogHandler`, a protocol provided by `swift-log` and 2) instruct `swift-log` to use your logging backend implementation.
A `LogHandler` or logging backend implementation is anything that conforms to the following protocol
Instructing `swift-log` 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.
## 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).
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.
Most notably, loggers should participate in tracing by including some trace metadata (such as e.g. a `trace-id`) when logging, as it transparently enables developers to benefit from log correlation using those IDs.
Today, the only supported way of providing such metadata is to pass them along to each log call explicitly:
```swift
logger.info("first this ...",metadata:["trace-id":MyTracingLibrary.currentTraceID])
logger.info("... now this",metadata:["trace-id":MyTracingLibrary.currentTraceID])
```
This comes with a couple of downsides:
### Error-prone and repetitive
It's easy to forget passing this metadata to _all_ log statements, resulting in an inconsistent debugging experience as these log statements cannot be found using correlation IDs.
The repetitiveness and verboseness of logging multiple metadata in-line quickly becomes annoying and vastly decreases the signal-to-noise ratio of Swift code trying to be a good citizen and making use of log correlation techniques such as distributed tracing.
### Impossible to implement for libraries
A large portion of logs are not generated by the end-user but by libraries such as AsyncHTTPClient, Vapor etc.
These libraries, by design, don't know about the specific metadata keys that should be included in the logs.
Those keys are after all runtime dependent, and may change depending on what tracing system is configured by the end user.
For example, a specific `Tracer` implementation would use a type representing a trace ID, and has a way of extracting
that trace ID from a [Swift Distributed Tracing Baggage](https://github.com/apple/swift-distributed-tracing-baggage). But other libraries can't know about this _specific_ trace ID and therefore would not be
able to pass such values along to their log statements.
## Proposed solution
To support this kind of runtime-generated metadata in `swift-log`, we need to extend the logging APIs in an open-ended way, to allow any kinds of metadata to be provided from the asynchronous context (i.e. task local values).
We also have a desire to keep `swift-log` a "zero dependencies" library, as it intends only to focus on describing a logging API, and not incur any additional dependencies, so it can be used in the most minimal of projects.
To solve this, we propose the extension of swift-log APIs with a new concept: _metadata providers_.
`MetadataProvider` is a struct nested in the `Logger` type, sitting alongside `MetadataValue` and the `Metadata`.
Its purpose is to _provide_`Logger.Metadata` from the asynchronous context, by e.g. looking up various task-local values,
and converting them into `Logger.Metadata`. This is performed by calling the `get()` function, like so:
which _overrides_ the default bootstrapped metadata provider.
> NOTE: Setting the metadata provider on the logger directly means the `LoggingSystem` metadata provider
> is skipped (if defined), following how an explicitly passed handler `factory`
> overrides the `LoggingSystem`s `factory`.
Once a metadata provider was set up, when a log statement is about to be emitted, the log handler implementation shall
invoke it whenever it is about to emit a log statement. This must be done from the same asynchronous context as the log statement
was made; I.e. if a log handler were to asynchronously–in a _detached_ task–create the actual log message, the invocation of
the metadata provider still _must_ be performed before passing the data over to the other detached task.
Usually, metadata providers will reach for the task's Swift Distributed Tracing [`Baggage`](https://github.com/apple/swift-distributed-tracing-baggage) which is the mechanism that swift-distributed-tracing
and instrumentation libraries use to propagate metadata across asynchronous, as well as process, boundaries. Handlers
may also inspect other task-local values, however they should not expect other libraries to be able to propagage those
as well as they will propagate `Baggage` values.
Those metadata will then be included in the log statement, e.g. like this:
```swift
varbaggage=Baggage.topLevel
baggage.spanContext=SpanContext()
Baggage.withValue(baggage){
test()
}
functest(){
log.info("Test",metadata:["oneOff":"42"])
//info[traceID:abc,spanID:123,onOff:42]Test
}
```
### Multiple `MetadataProvider`s using `MetadataProvider.multiplex(_:)`
Borrowing the concept from log handlers, metadata providers also have a multiplexing implementation.
It is defined as an extension on `MetadataProvider` and is useful in cases where users want to utilize
Metadata keys are unique, so in case multiple metadata providers return the same key,
the last provider in the array _wins_ and provides the value.
Note that it is possible to query the `LoggingSystem` for the configured, system-wide, metadata provider,
and combine it using a `multiplex` provider if the system-wide provider should not be replaced, but augmented
by additional providers.
### Understanding Swift Distributed Tracing `Baggage`
The `Baggage` type is more than just a fancy type-safe container for your values which are meant to be carried across
using a single, well-known, [task-local value](https://developer.apple.com/documentation/swift/tasklocal).
Values stored in `Baggage` are intended to be carried _across process boundaries_, and e.g. libraries such as HTTP clients,
or other RPC mechanisms, or even messaging systems implement distributed tracing [instruments](https://github.com/apple/swift-distributed-tracing/blob/main/Sources/Instrumentation/Instrument.swift)
which `inject` and `extract` baggage values into their respective carrier objects, e.g. an `HTTPRequest` in the case of an HTTP client.
In other words, whenever intending to propagate information _across processes_ utilize the `Baggage` type to carry it,
and ensure to provide an `Instrument` that is able to inject/extract the values of interest into the carrier types you are interested in.
To learn more about baggage and instrumentation, refer to the [Swift Distributed Tracing](https://github.com/apple/swift-distributed-tracing/) library documentation.
#### When to use `Baggage` vs. `Logger[metadataKey:]`
While `Baggage` is context-dependent and changes depending on where the log methods are being called from, the metadata set on a `Logger` is static and not context-dependent. E.g, if you wanted to add things like an instance ID or a subsystem name to a `Logger`, that could be seen as static information and set via `Logger[metadataKey:]`.
```swift
varlogger=Logger(label:"org.swift.my-service")
logger[metadataKey:"instanceId"]="123"
logger.info("Service started.")
//[instanceId:123]Servicestarted.
```
On the other hand, things like a trace ID are dynamic and context-dependent, therefore would be obtained via `Baggage`:
```swift
logger.info("Product fetched.")
//[traceId:42]Productfetched.
```
Inline-metadata is suitable for one-offs such as a `productId` or a `paymentMethod` in an online store service, but are not enough to corralate the following log statements, i.e. tying them both to the same request:
### MetadataProviders as a function of `Baggage -> Metadata`
This was considered and fully developed, however it would cause swift-log to have a dependency on the instrumentation type `Baggage`,
which was seen as in-conflict-with the interest of swift-log remaining a zero-dependency library.
`Baggage`_is_ the well known type that is intended to be used for any kind of distributed systems instrumentation and tracing,
however it adds additional complexity and confusion for users who are not interested in this domain. For example, developers
may be confused about why `Baggage` and `Logger.Metadata` look somewhat similar, but behave very differently. This complexity
is inherent to the two types actually being _very_ different, however we do not want to overwhelm newcomers or developers
who are only intending to use swift-log within process. Such developers do not need to care about the added complexities
of distributed systems.
The tradeoff we take here is that every metadata provider will have to perform its own task-local (and therefore also thread-local),
access in order to obtain the `Baggage` value, rather than the lookup being able to be performed _once_ and shared between
multiple providers when a multiplex provider was configured in the system. We view this tradeoff as worth taking, as the cost
of actually formatting the metadata usually strongly dominates the cost of the task-local lookup.
### Removing `LogHandler.Metadata` in favor of `Baggage`
Removing logger metadata is not a good option because it serves a slightly different style of metadata than the baggage.
Baggage is intended for contextual, task-local, metadata which is _carried across multiple libraries_. The values stored in baggage are well-typed, and must declare keys for accessing values in a baggage, this works well for multiple pieces of an application needing to reach for specific baggage items: everyone aware of the `traceID` key, is able to query the baggage for this key (`baggage.traceID`) and obtain a well-typed value. This comes with a higher cost on declaring keys though, as well as a global namespace for those - which is desirable for such kinds of metadata.
This is not the same usage pattern as emitting a plain structured log where we'd like to include the name of an item we just queried:
In this example, the key/value pair for `"item"` is pretty ad-hoc, and we never need to refer to it elsewhere in the program. It never is queried by other pieces of the application, nor would it be useful to set it in baggage metadata, as the only purpose of the `item` key here is to log, and forget about it.
### Explicitly passing `Baggage` always
Baggage is designed for use cases like distributed tracing, or similar instrumentation patterns where "all" participating code may need to reach for it.
Specifically in logging, this means that _every_ call site for _every_ log statement would have to pass it explicitly resulting in annoying noisy code:
Imagine we don't have metadata providers, we'd have to manually set trace IDs on loggers which doesn't really work as all libraries involved would need to know about the same specific trace ID. Even if we inverted the dependency to have `Tracing` depend on `Logging` so that we'd be able to define something like "Tracing, please populate this logger with metadata", we'd have to make sure this thing is called in all places to avoid dropping contextual metadata.
Instead of having `swift-log` depend on `swift-distributed-tracing-baggage` we could also create extensions for `Logger` inside `swift-distributed-tracing` and have users call these new overloaded methods instead:
```swift
extensionLogger{
functinfo(_message:...,baggage:Baggage?){
//...
}
}
```
Such extensions could work like the currently-proposed APIs, but the risk of users calling the wrong methods is incredibly high and we cannot overload the existing methods' signatures because of ambiguity of call-sides without explicit Baggage being passed:
Also, this extension-based contextual metadata would require basically everyone in Server-side Swift to adapt their usage of `Logging` to use these extensions instead. With the proposed APIs, we'd only need to modify `Logging` and any NIO-based libraries such as `AsyncHTTPClient`, `Vapor`, etc. and not every single log statement in every application.
- [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.
The default for `log(event:)` forwards all event fields to the old flat-parameter method,
preserving the behavior of existing handlers with no source changes required.
The default implementation is marked as deprecated to encourage handler authors to migrate to `log(event:)`.
Handlers that still rely on the forwarding bridge will see a deprecation warning at compile time, signaling that
they should adopt the new method directly.
```swift
extensionLogHandler{
@available(*,deprecated,message:"You should implement this method instead of using the default implementation")
publicfunclog(event:LogEvent){
self.log(
level:event.level,
message:event.message,
metadata:event.metadata,
source:event.source,
file:event.file,
function:event.function,
line:event.line
)
}
}
```
### API stability
**For existing `Logger` users:** No changes. All existing call sites continue to compile and behave identically.
**For existing `LogHandler` implementations:** Implementations of
`log(level:message:metadata:source:file:function:line:)` continue to work without any source changes. The
default implementation of `log(event:)` forwards to the old method.
### Future directions
Future proposals can add new fields to `LogEvent` with sensible defaults — a richer metadata
type, or an attached `Error` (as a follow-up for [SLG-0003 proposal](https://forums.swift.org/t/proposal-slg-0003-standardized-error-metadata-via-logger-convenience/84518/39)) —
without touching the `LogHandler` protocol and without requiring any changes to
existing handler implementations. This is the primary motivation for this proposal.
The [SLG-0004 proposal](https://github.com/apple/swift-log/pull/416) introduces an `AttributedMetadata` type that wraps
`Logger.Metadata` with additional context. Adding it to `LogEvent` as a new optional field would be
source-compatible, and the existing `metadata` field could become a computed property that projects from
`attributedMetadata` when present, keeping old handlers fully functional without modification.
### Alternatives considered
#### Adding parameters with default values to the existing method
Adding new parameters with default values avoids introducing a new method, but still constitutes a
source-breaking change: every existing `LogHandler` implementation that implements the method explicitly
must add the new parameter. The whole point of this proposal is to avoid that pattern indefinitely.
- [Lightweight proposals process description](https://github.com/apple/swift-log/blob/main/Sources/Logging/Docs.docc/Proposals/Proposals.md)
### Introduction
A short, one-sentence overview of the feature or change.
### Motivation
Describe the problems that this proposal aims to address, and what workarounds adopters have to employ currently, if any.
### Proposed solution
Describe your solution to the problem. Provide examples and describe how they work. Show how your solution is better than current workarounds.
This section should focus on what will change for the _adopters_ of SwiftLog.
### Detailed design
Describe the implementation of the feature, a link to a prototype implementation is encouraged here.
This section should focus on what will change for the _contributors_ to SwiftLog.
### API stability
Discuss the API implications, making sure to considering all of:
- existing ``Logger`` users,
- existing ``LogHandler`` implementations.
### Future directions
Discuss any potential future improvements to the feature.
### Alternatives considered
Discuss the alternative solutions considered, even during the review process itself.
Loaded 100 of 158 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.