169 Commits
Author SHA1 Message Date
0z5a c7413d967b Make MultiplexLogHandler.metadataProvider setter replace the initializer's provider (#537)
### 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.
2026-11-17 13:24:42 +00:00
Tony Allevato 34b131f794 Support raw-identifier module names in Logger.currentModule. (#535)
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.
2026-11-10 14:27:30 +00:00
e3da040787 Fix metadata priority in MultiplexLogHandler.metadata (#530)
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>
2026-11-03 10:57:38 +00:00
Matt Massicotte 209524e4da Remove unnecessary optional so example compiles (#501)
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.
2026-11-03 10:14:16 +00:00
Krishna Permi c44b210eee Add opt-in millisecond precision to StreamLogHandler timestamp (#483)
`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
2026-11-03 09:56:27 +00:00
om singhal c9c6bb9d27 Mutate the logger's handler in place on metadata writes (#529)
Give `Logger.handler` a `_modify` accessor and replace its `get` with
`_read`, so metadata writes update the stored handler instead of a copy.

### Motivation:

`Logger.handler` only has `get` and `set`. A write such as
`logger[metadataKey: "k"] = "v"` gets a copy of the handler, writes to
it while the stored handler still shares the metadata dictionary, and
sets it back. So every write copies the whole dictionary, and
`withLogger(mergingMetadata:)` does that once per key.

### Modifications:

- Give `Logger.handler` `_read`, `set` and `_modify` accessors. `_read`
yields the stored handler. `_modify` keeps the existing uniqueness check
on the storage and then yields the stored handler, so metadata and log
level writes change it in place. `set` keeps the same check for plain
`logger.handler = newHandler` assignments, which are cheaper through a
setter than through `_modify`.
- Add a test handler that counts copies of its metadata, with tests for
direct writes and for `withLogger(mergingMetadata:)`. Without the change
they report 10 copies instead of 0, and 5 instead of 1.

### Result:

A metadata write on a logger that owns its storage no longer copies the
dictionary. A copied logger still copies once on its first write, so
value semantics are unchanged.

1,000 metadata writes with a handler that keeps metadata in a plain
dictionary, debug build, three runs each:

| Keys on the logger | Before | After |
|---|---|---|
| 10 | 7.2 to 8.1 ms | 0.46 to 0.50 ms |
| 1,000 | 20.2 to 20.6 ms | 0.46 to 0.55 ms |
| 10,000 | 134.0 to 134.4 ms | 0.47 to 0.50 ms |
| 100,000 | 1.29 to 1.30 s | 0.32 to 0.35 ms |

`withLogger(mergingMetadata:)` with 10,000 keys went from 0.64 to 0.65 s
down to 2.9 to 3.1 ms. `StreamLogHandler` still rebuilds its pretty
metadata string on every write; this change does not touch that.

All 176 tests pass on macOS with Swift 6.4, and `swift format lint
--strict` and `swift package diagnose-api-breaking-changes` are clean.
Once yielding accessors land, `_read` and `_modify` can become `yielding
borrow` and `yielding mutate`.

Fixes #526.
2026-10-22 10:30:03 +01:00
Chris Leonard 4038b6a4f7 Fix metadata provider handling when multiplexing log events (#522)
Ensure metadata from the multiplex handler’s own provider reaches
emitted logs.

Fixes #521.

## Motivation

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

## Modifications

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

## Result

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

Regression tests fail before the fix and pass afterward. All 174 tests
pass on macOS with Swift 6.4. Formatting and `git diff --check` also
pass.
2026-10-07 15:03:40 +00:00
Chris Leonard 109c380c23 Fix explicit log level when replacing a task-local logger's handler (#520)
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.
2026-10-07 10:47:39 +01:00
Vladimir Kukushkin c29472f010 Bump minimal Swift tools version to 6.2 (#518)
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.
2026-10-02 16:39:23 +00:00
Vladimir Kukushkin 9c9acde6dc Fix nested metadata values handling (#516)
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?
2026-09-23 10:13:24 +01:00
Honza Dvorsky 9c6fb14227 Fix referencing WASILibc.stdout/stderr in Swift 6.5+ (#507)
### 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 :)
2026-09-08 11:02:37 +01:00
Jeff LenamonandVladimir Kukushkin 53d00853e6 Route the SwiftLog 1.0 default log method to log(event:) (#503)
### 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>
2026-09-07 13:29:33 +01:00
Jeff Lenamon c5ece24786 Document that setting attributes on a collection value is a programmer error (#504)
### 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.
2026-09-04 09:08:57 +00:00
Vladimir Kukushkin 3ffafb9722 Make ReadWriteLock.init internal (#496)
### 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.
2026-08-04 14:02:34 +02:00
Vladimir KukushkinandJoseph Heck 7af2de138f Document how to construct log handlers that need more than a label (#490)
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>
2026-07-24 17:59:05 +01:00
mitraandVladimir Kukushkin e83726cb15 Add CMake support for Swift targets and test configurations (#485)
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>
2026-07-22 17:25:43 +01:00
Subhramit BasuandVladimir Kukushkin 1895d78a91 Make StreamLogHandler initializers public (#477)
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>
2026-06-25 16:24:26 +01:00
Vladimir KukushkinandJoseph Heck 8a6b9eab84 Add testing logs best practice (#475)
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>
2026-06-25 11:23:03 +01:00
Joseph HeckandVladimir Kukushkin c4e96785bf Add missing api refs (#478)
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>
2026-06-25 11:00:42 +01:00
Vladimir Kukushkin 54ec9e35cd Update implemented proposals status (#476)
Match proposals status in the docs and the implementation reality.
2026-06-24 16:51:39 +01:00
Vladimir KukushkinandFranz Busch a878e7f8f4 [SLG-0006]: task-local logger implementation (#459)
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>
2026-06-23 15:15:37 +01:00
Vladimir Kukushkin ca61184698 [SLG-0006]: task-local logger proposal (#460)
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.
2026-06-11 06:47:52 -07:00
Vladimir Kukushkin 92448c359f Add (default:) string interpolation overloads (#471)
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.
2026-06-09 17:01:25 +02:00
Vladimir Kukushkin 2aed77ae5e Match DefaultStringInterpolation appendInterpolation overloads (#469)
Custom `MetadataValue.StringInterpolation` broke compatibility with
`DefaultStringInterpolation`. Rearrange `appendInterpolation` overloads
to match `DefaultStringInterpolation` to maintain backward
compatibility.

### Motivation:

Custom `MetadataValue.StringInterpolation` broke compatibility with
`DefaultStringInterpolation`. Rearrange `appendInterpolation` overloads
to match `DefaultStringInterpolation` to maintain backward
compatibility.

### Modifications:

`MetadataValue.StringInterpolation` `appendInterpolation` overloads
changed.

### Result:

Code relying on matching correct `DefaultStringInterpolation`
`appendInterpolation` overload compiles.
2026-05-28 13:35:14 +01:00
Vladimir KukushkinandFranz Busch 7dc6101ae4 [SLG-0004]: metadata value attributes implementation (#453)
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>
2026-05-22 16:06:57 +01:00
Rick Newton-Rogers 1069d31898 Skip handler dispatch for setters under MaxLogLevelNone (#465)
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
2026-05-21 13:55:40 +01:00
Vladimir Kukushkin eca81998f5 [SLG-0004]: metadata value attributes proposal (revision 2) (#440)
> [!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.
2026-05-13 15:38:57 +02:00
Samuel MurrayandVladimir Kukushkin 25598b609a Improve readability by extracting separate types to their own files (#444)
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>
2026-04-17 10:49:49 +01:00
8ba97a9cf5 Update documentation to reflect recent changes (#445)
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>
2026-04-17 09:12:32 +01:00
Samuel MurrayandVladimir Kukushkin 5073617dac SLG-0003: Error parameter implementation (#425)
Add new methods on `Logger` that allows the caller to attach `Error`s to
log events, which will be propagated to the `LogHandler` as-is.

### Motivation:

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

### Modifications:

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

### Result:

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

---------

Co-authored-by: Vladimir Kukushkin <kukushechkin@mac.com>
2026-04-14 06:03:57 -07:00
Samuel Murray 41f6c72707 Retroactively update status of SLG-0005 to Approved (#438)
### Motivation:

SLG-0005 is implemented and released in 1.11.0.

### Modifications:

Update status to 'Approved'.

### Result:

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

### Motivation:

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

### Modifications:

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

### Result:

Proposal is ready for review.

Review result: the proposal is not accepted and needs rework.
2026-04-02 17:10:43 +01:00
Mads Odgaard f4f84c9f26 Avoid using CFilePointer typealias in default logger (#433)
Rewrites the default log handler to avoid typing out what the C file
pointer looks like on different platforms.

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

### Motivation:

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

### Modifications:

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

### Result:

Further changes to the `LogEvent` with new information passed from the
`Logger` to a `LogHandler` does not require changes in the `LogHandler`
API. As a bonus, `LogEvent` makes `source` a computable variable,
improving performance for log handlers who do not need the default
source created based on the log file location.
2026-03-27 13:13:04 +00:00
Vladimir Kukushkin c9ceb519e7 [SLG-0005]: LogEvent LogHandler API proposal (#424)
Replace the flat-parameter
`log(level:message:metadata:source:file:function:line:)` method on
`LogHandler` with
`log(event: LogEvent)`, enabling forward-compatible evolution of the
`LogHandler` interface without breaking existing
handler implementations.

### Motivation:

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

### Modifications:

- SLG-0005 proposal added.

### Result:

Proposal is ready for implementation.
The reason the proposal has
2026-03-20 12:16:20 +00:00
Samuel MurrayandVladimir Kukushkin b93451412b Update proposal SLG-0003 after public review (#419)
Motivation:

The public review of the original proposal

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

Modifications:

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

Co-authored-by: Vladimir Kukushkin <kukushechkin@mac.com>
2026-03-12 12:19:26 +00:00
scottmarchant 8fb4e7147d chore: update Lock implementation with latest changes from swift-nio (#408)
Ports changes to `Lock` from swift-nio to swift-log.

### Motivation:

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

### Modifications:

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

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

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

### Result:

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

### Motivation:

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

### Modifications:

The "SLG-0003" proposal doc added.

### Result:

The proposal is ready for review.

---------

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

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

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

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

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

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

### Motivation:

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

### Modifications:

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

### Result:

Codebase is updated with the modern practices.
2026-01-30 08:58:47 +01:00
Kenta KuboandFranz Busch 8f634e4e68 Add support for FreeBSD and OpenBSD (#387)
I've added support for FreeBSD. I've only tested this PR on FreeBSD, but
I believe it should also work on OpenBSD.

### Motivation:

closes #372 

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

### Modifications:

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

### Result:

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

### Checks:

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

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

Environment:

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

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

---------

Co-authored-by: Franz Busch <f.busch@apple.com>
2026-01-19 16:37:43 +00:00
Konrad `ktoso` MalawskiandVladimir Kukushkin 0d9c9ae808 Change document title to 'SLG-0001: Metadata Providers' (#400)
Co-authored-by: Vladimir Kukushkin <kukushechkin@mac.com>
2026-01-15 19:55:51 +09:00
scottmarchant a92ccc626c feat: Update lock implementation to more closely align with swift-nio implementation (#398) 2026-01-15 08:08:44 +00:00
Vladimir Kukushkin 7ee16e4656 The SLG-0002 implementation is merged, update the proposal status (#399)
Just bumping the status before making the release.
2026-01-14 13:04:51 +00:00
Vladimir Kukushkin 1ccd2c5a27 [SLG-0002] Implementation: Compile-time log level elimination using traits (#389)
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.
2026-01-13 14:23:51 +00:00
Vladimir Kukushkin bc386b95f2 [SLG-0002]: Compile-time log level elimination using traits (#391)
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.
2025-12-11 12:31:11 +00:00
Francesco Paolo Severino cdaa5ac879 Conform Logger.Level to CustomStringConvertible and LosslessStringConvertible (#395)
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`.
2025-12-08 20:11:23 +01:00
hamzahrmalik b1fa4ef41f Make InMemoryLogging available on all platforms (#394)
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
2025-12-04 11:52:31 +00:00
Max Desiatov f3a82f1119 Fix Android build error with @preconcurrency import Android (#393) 2025-12-04 08:33:10 +09:00
Vladimir Kukushkin 6b380c9f4b Move pre-process proposal to the proposals folder (#392)
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.
2025-12-03 16:27:10 +01:00
Vladimir Kukushkin 3612813963 Introduce proposals process to SwiftLog (#388) 2025-11-28 09:48:55 +09:00