Compare commits

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

### Motivation:

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

### Modifications:

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

### Result:

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

---------

Co-authored-by: Vladimir Kukushkin <kukushechkin@mac.com>
2026-04-14 06:03:57 -07:00
dependabot[bot]andVladimir Kukushkin 6f3fbace66 Bump swiftlang/github-workflows/.github/workflows/soundness.yml from 0.0.8 to 0.0.9 (#437)
Bumps
[swiftlang/github-workflows/.github/workflows/soundness.yml](https://github.com/swiftlang/github-workflows)
from 0.0.8 to 0.0.9.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/swiftlang/github-workflows/releases">swiftlang/github-workflows/.github/workflows/soundness.yml's
releases</a>.</em></p>
<blockquote>
<h2>0.0.9</h2>
<h2>What's Changed</h2>
<ul>
<li>When splitting lines for the cross-PR checkout also split on \r\n by
<a href="https://github.com/ahoppen"><code>@​ahoppen</code></a> in <a
href="https://redirect.github.com/swiftlang/github-workflows/pull/249">swiftlang/github-workflows#249</a></li>
<li>Fix template injection by <a
href="https://github.com/justice-adams-apple"><code>@​justice-adams-apple</code></a>
in <a
href="https://redirect.github.com/swiftlang/github-workflows/pull/247">swiftlang/github-workflows#247</a></li>
<li>Remove tailing comma in matrix JSON by <a
href="https://github.com/plemarquand"><code>@​plemarquand</code></a> in
<a
href="https://redirect.github.com/swiftlang/github-workflows/pull/254">swiftlang/github-workflows#254</a></li>
<li>Update default Xcode versions in workflow to 16.4, 26.3, and 26.4 by
<a href="https://github.com/shahmishal"><code>@​shahmishal</code></a> in
<a
href="https://redirect.github.com/swiftlang/github-workflows/pull/255">swiftlang/github-workflows#255</a></li>
</ul>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/swiftlang/github-workflows/compare/0.0.8...0.0.9">https://github.com/swiftlang/github-workflows/compare/0.0.8...0.0.9</a></p>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/swiftlang/github-workflows/commit/f84da042883848ad67aadd051dc322eec18660d3"><code>f84da04</code></a>
Update default Xcode versions in workflow to 16.4, 26.3, and 26.4 (<a
href="https://redirect.github.com/swiftlang/github-workflows/issues/255">#255</a>)</li>
<li><a
href="https://github.com/swiftlang/github-workflows/commit/47c9717a9218ab60fe9fc6e957980d55fe949f1d"><code>47c9717</code></a>
Remove tailing comma in matrix JSON (<a
href="https://redirect.github.com/swiftlang/github-workflows/issues/254">#254</a>)</li>
<li><a
href="https://github.com/swiftlang/github-workflows/commit/8e529b937e15ba0a65af9b492393704fe3f16bdf"><code>8e529b9</code></a>
Fix template injection (<a
href="https://redirect.github.com/swiftlang/github-workflows/issues/247">#247</a>)</li>
<li><a
href="https://github.com/swiftlang/github-workflows/commit/58677410ce8ef88844850c908bcd830ad108c812"><code>5867741</code></a>
When splitting lines for the cross-PR checkout also split on \r\n (<a
href="https://redirect.github.com/swiftlang/github-workflows/issues/249">#249</a>)</li>
<li>See full diff in <a
href="https://github.com/swiftlang/github-workflows/compare/0.0.8...0.0.9">compare
view</a></li>
</ul>
</details>
<br />


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

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

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

---

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

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


</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Vladimir Kukushkin <kukushechkin@mac.com>
2026-04-13 14:50:09 +01:00
Samuel Murray 41f6c72707 Retroactively update status of SLG-0005 to Approved (#438)
### Motivation:

SLG-0005 is implemented and released in 1.11.0.

### Modifications:

Update status to 'Approved'.

### Result:

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

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

Modifications:

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

Result:

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

### Motivation:

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

### Modifications:

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

### Result:

Proposal is ready for review.

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

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

Modifications:

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

Result:

Improved test coverage.
2026-04-01 14:18:23 +01:00
21 changed files with 1171 additions and 151 deletions

No files matched your search

+4 -4
View File
@@ -14,19 +14,19 @@ jobs:
name: Unit tests
uses: apple/swift-nio/.github/workflows/unit_tests.yml@main
with:
linux_6_0_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
linux_6_1_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
linux_6_2_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
linux_6_3_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
linux_nightly_next_arguments_override: "--explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
linux_nightly_main_arguments_override: "--explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
windows_6_0_enabled: true
windows_6_1_enabled: true
windows_6_2_enabled: true
windows_6_3_enabled: true
windows_nightly_next_enabled: true
windows_nightly_main_enabled: true
windows_6_0_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
windows_6_1_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
windows_6_2_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
windows_6_3_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
windows_nightly_next_arguments_override: "--explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
windows_nightly_main_arguments_override: "--explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
@@ -89,8 +89,8 @@ jobs:
name: Release builds
uses: apple/swift-nio/.github/workflows/release_builds.yml@main
with:
windows_6_0_enabled: true
windows_6_1_enabled: true
windows_6_2_enabled: true
windows_6_3_enabled: true
windows_nightly_next_enabled: true
windows_nightly_main_enabled: true
+5 -5
View File
@@ -10,7 +10,7 @@ on:
jobs:
soundness:
name: Soundness
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@0.0.8
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@0.0.9
with:
license_header_check_project_name: "Swift Logging API"
@@ -18,19 +18,19 @@ jobs:
name: Unit tests
uses: apple/swift-nio/.github/workflows/unit_tests.yml@main
with:
linux_6_0_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
linux_6_1_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
linux_6_2_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
linux_6_3_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
linux_nightly_next_arguments_override: "--explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
linux_nightly_main_arguments_override: "--explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
windows_6_0_enabled: true
windows_6_1_enabled: true
windows_6_2_enabled: true
windows_6_3_enabled: true
windows_nightly_next_enabled: true
windows_nightly_main_enabled: true
windows_6_0_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
windows_6_1_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
windows_6_2_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
windows_6_3_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
windows_nightly_next_arguments_override: "--explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
windows_nightly_main_arguments_override: "--explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
@@ -79,9 +79,9 @@ jobs:
name: Release builds
uses: apple/swift-nio/.github/workflows/release_builds.yml@main
with:
windows_6_0_enabled: true
windows_6_1_enabled: true
windows_6_2_enabled: true
windows_6_3_enabled: true
windows_nightly_next_enabled: true
windows_nightly_main_enabled: true
@@ -1,4 +1,4 @@
{
"instructions" : 1605,
"instructions" : 1651,
"objectAllocCount" : 0
}
}
@@ -1,4 +1,4 @@
{
"instructions" : 1608,
"instructions" : 1651,
"objectAllocCount" : 0
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
// swift-tools-version: 6.0
// swift-tools-version:6.1
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
@@ -1,4 +1,4 @@
{
"instructions" : 981,
"instructions" : 984,
"objectAllocCount" : 0
}
}
@@ -1,4 +1,4 @@
{
"instructions" : 1351,
"instructions" : 1368,
"objectAllocCount" : 0
}
}
@@ -1,4 +1,4 @@
{
"instructions" : 893,
"objectAllocCount" : 0
}
}
@@ -1,4 +1,4 @@
{
"instructions" : 1605,
"instructions" : 1649,
"objectAllocCount" : 0
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
// swift-tools-version: 6.0
// swift-tools-version:6.1
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
-61
View File
@@ -1,61 +0,0 @@
// swift-tools-version:6.0
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Logging API open source project
//
// Copyright (c) 2018-2019 Apple Inc. and the Swift Logging API project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Swift Logging API project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import PackageDescription
let package = Package(
name: "swift-log",
products: [
.library(name: "Logging", targets: ["Logging"]),
.library(name: "InMemoryLogging", targets: ["InMemoryLogging"]),
],
targets: [
.target(
name: "Logging",
dependencies: []
),
.target(
name: "InMemoryLogging",
dependencies: ["Logging"]
),
.testTarget(
name: "LoggingTests",
dependencies: ["Logging"]
),
.testTarget(
name: "InMemoryLoggingTests",
dependencies: ["InMemoryLogging", "Logging"]
),
]
)
for target in package.targets
where [.executable, .test, .regular].contains(
target.type
) {
var settings = target.swiftSettings ?? []
// https://github.com/apple/swift-evolution/blob/main/proposals/0335-existential-any.md
// Require `any` for existential types.
settings.append(.enableUpcomingFeature("ExistentialAny"))
// https://github.com/swiftlang/swift-evolution/blob/main/proposals/0444-member-import-visibility.md
settings.append(.enableUpcomingFeature("MemberImportVisibility"))
// https://github.com/swiftlang/swift-evolution/blob/main/proposals/0409-access-level-on-imports.md
settings.append(.enableUpcomingFeature("InternalImportsByDefault"))
target.swiftSettings = settings
}
@@ -46,6 +46,8 @@ public struct InMemoryLogHandler: LogHandler {
public var level: Logger.Level
/// The message which was logged.
public var message: Logger.Message
/// The error which was logged.
public var error: (any Error)?
/// The metadata which was logged.
public var metadata: Logger.Metadata
@@ -54,18 +56,49 @@ public struct InMemoryLogHandler: LogHandler {
self.message = message
self.metadata = metadata
}
public init(level: Logger.Level, message: Logger.Message, error: (any Error)?, metadata: Logger.Metadata) {
self.level = level
self.message = message
self.error = error
self.metadata = metadata
}
public static func == (lhs: InMemoryLogHandler.Entry, rhs: InMemoryLogHandler.Entry) -> Bool {
lhs.level == rhs.level
&& lhs.message == rhs.message
&& errorsEqual(lhs.error, rhs.error)
&& lhs.metadata == rhs.metadata
}
private static func errorsEqual(_ lhs: (any Error)?, _ rhs: (any Error)?) -> Bool {
switch (lhs, rhs) {
case (nil, nil):
return true
case let (l?, r?):
return "\(l)" == "\(r)" && String(reflecting: type(of: l)) == String(reflecting: type(of: r))
default:
return false
}
}
}
private final class LogStore: @unchecked Sendable {
private var _entries: [Entry] = []
private let lock = Lock()
fileprivate func append(level: Logger.Level, message: Logger.Message, metadata: Logger.Metadata) {
fileprivate func append(
level: Logger.Level,
message: Logger.Message,
error: (any Error)?,
metadata: Logger.Metadata
) {
self.lock.withLockVoid {
self._entries.append(
Entry(
level: level,
message: message,
error: error,
metadata: metadata
)
)
@@ -100,7 +133,7 @@ public struct InMemoryLogHandler: LogHandler {
// ..merge in metadata from this log call, overwriting existing keys
mergedMetadata = mergedMetadata.merging(event.metadata ?? [:]) { $1 }
self.logStore.append(level: event.level, message: event.message, metadata: mergedMetadata)
self.logStore.append(level: event.level, message: event.message, error: event.error, metadata: mergedMetadata)
}
@available(*, deprecated, renamed: "log(event:)")
@@ -6,7 +6,7 @@ Add standardized way of attaching data from `Error` instances to log entries.
- Proposal: SLG-0003
- Author(s): [Samuel Murray](https://github.com/samuelmurray)
- Status: **Ready for Implementation**
- Status: **Approved**
- Issue: [apple/swift-log#291](https://github.com/apple/swift-log/issues/291)
- Implementation:
- [apple/swift-log#425](https://github.com/apple/swift-log/pull/425)
@@ -0,0 +1,467 @@
# SLG-0004: Metadata values privacy attribute
Introduce an attributed metadata system that allows attaching attributes to metadata values, with privacy level as the first attribute enabling developers to mark metadata as `.private` or `.public`.
## Overview
- Proposal: SLG-0004
- Author(s): [Vladimir Kukushkin](https://github.com/kukushechkin)
- Status: **Deferred**
- Issue: https://github.com/apple/swift-log/issues/204
- Implementation:
- [apple/swift-log#418](https://github.com/apple/swift-log/pull/418)
- Related links:
- [Lightweight proposals process description](https://github.com/apple/swift-log/blob/main/Sources/Logging/Docs.docc/Proposals/Proposals.md)
- [Review discussion](https://forums.swift.org/t/proposal-slg-0004-metadata-values-privacy-attribute/85249/16)
### Introduction
This proposal introduces an **attributed metadata system** that allows attaching attributes to metadata values. Privacy level is the first concrete attribute, enabling developers to mark metadata values as `.private` or `.public` so `LogHandler` implementations can redact sensitive values before logging.
### Motivation
SwiftLog lacks a mechanism to attach attributes to metadata values. This prevents marking metadata as sensitive and limits future extensibility for other metadata attributes.
Applications need privacy controls for:
- Compliance with privacy regulations.
- Backend integration with privacy-aware logging systems.
- Systematic control over what data appears in logs.
Beyond privacy, an attributed metadata system provides a foundation for future extensions such as retention policies, data classification, or other metadata attributes.
### Proposed solution
Introduce new `AttributedMetadata` data type, enabling users to mark metadata values with `.private` and `.public` privacy label:
```swift
// Add privacy level to metadata values obtained through a metadata provider
let serviceIp = "127.0.0.1"
var logger = Logger(label: "my-app", metadataProvider: .init {[
"service.ip": "\(serviceIp, privacy: .private)",
]})
// Add privacy level to metadata values attached to a `Loghandler` instance
let requestId = UUID()
logger[attributedMetadataKey: "request.id"] = "\(requestId, privacy: .private)"
// Mark sensitive values as private and non-sensitive as public at logging call site
let userId = UUID()
let action = "login"
logger.info("User action", attributedMetadata: [
"user.id": "\(userId, privacy: .private)",
"action": "\(action)" // default is .public for ease of adoption
])
```
This allows `Logger` users to mark certain metadata values as "I only trust LogHandlers, who know how to handle sensitive data, to see this value".
### Detailed design
#### Attributed Metadata
To support privacy labels and enable future extensibility, we introduce a generalized **attributed metadata** system. This provides a foundation for attaching arbitrary attributes to metadata values, with privacy labels being the first concrete use case:
```swift
// Plain metadata (existing)
let metadataValue: MetadataValue = .string("value")
logger.info("Message", metadata: ["key": metadataValue])
// Attributed metadata (new) — a value with attributes
logger.info("Message", attributedMetadata: [
"key": AttributedMetadataValue(value: metadataValue, attributes: ...)
])
```
The attributed metadata system instroduces new public API:
1. **`AttributedMetadataValue`**: Wraps a standard `MetadataValue` with associated attributes.
2. **`MetadataValueAttributes`**: Container for attributes.
3. **`AttributedMetadata`**: Dictionary type mapping `String` keys to attributed values.
4. **Parallel logging API**: New log methods accepting `attributedMetadata` parameter.
This design separates the transport mechanism (attributed metadata) from specific attribute semantics (privacy labels), allowing future extensions without breaking existing attributed metadata code.
#### Privacy levels
With attributed metadata as the foundation, privacy labels are implemented as the first concrete attribute:
```swift
extension Logger {
/// A metadata value with associated privacy attributes.
///
/// `AttributedMetadataValue` wraps a standard `MetadataValue` with privacy attributes,
/// allowing you to mark metadata as private or public for privacy-aware logging.
///
/// ## Creating Attributed Metadata
///
/// Use string interpolation with privacy parameter:
///
/// ```swift
/// // Preferred: String interpolation with privacy level specified
/// let userId = "12345"
/// let action = "login"
/// logger.info("User action", attributedMetadata: [
/// "user.id": "\(userId, privacy: .private)",
/// "action": "\(action, privacy: .public)" // explicit .public for non-sensitive data
/// ])
///
/// // Direct creation
/// let attributed = Logger.AttributedMetadataValue(
/// .string("12345"),
/// privacy: .private
/// )
/// ```
///
/// ## Important Limitations
///
/// - **No nested privacy**: When marking a dictionary or array as private, all contained
/// values are treated with the same privacy level. Fine-grained privacy within nested
/// structures is not currently supported.
///
/// - **Metadata only**: Privacy levels apply only to metadata values, not to log messages.
/// Avoid including sensitive data in log message string interpolation.
public struct AttributedMetadataValue: CustomStringConvertible, Sendable {
/// The redaction marker used for private values.
internal static let redactionMarker = "<private>"
public let value: MetadataValue
public let attributes: MetadataValueAttributes
/// String representation redacts private values to the redaction marker.
public var description: String {
attributes.privacy == .public ? value.description : Self.redactionMarker
}
public init(_ value: MetadataValue, attributes: MetadataValueAttributes)
public init(_ value: MetadataValue, privacy: PrivacyLevel)
}
extension AttributedMetadataValue {
/// Attributes that can be associated with metadata values.
public struct MetadataValueAttributes: CustomStringConvertible, Hashable, Sendable {
/// Privacy level for metadata values.
///
/// Privacy levels allow you to mark metadata values as either private (sensitive data that should be
/// protected) or public (safe to log in any context).
///
/// ## Usage
///
/// Use string interpolation with the privacy parameter to create attributed metadata values:
///
/// ```swift
/// let userId = "12345"
/// let action = "login"
/// logger.info("User action", attributedMetadata: [
/// "user.id": "\(userId, privacy: .private)",
/// "action": "\(action, privacy: .public)",
/// "ip": "\(ipAddress, privacy: .private)"
/// ])
/// ```
@frozen
public enum PrivacyLevel: Sendable, CaseIterable, Equatable, Hashable, CustomStringConvertible {
/// Private data that should be redacted in non-secure contexts.
case `private`
/// Public data safe for general logging.
case `public`
}
/// The privacy level of this metadata value.
public var privacy: PrivacyLevel
/// Create metadata value attributes with the specified privacy level.
///
/// - Parameter privacy: The privacy level for this metadata. Defaults to `.public`.
public init(privacy: PrivacyLevel = .public)
}
/// The underlying metadata value without privacy attributes.
public var value: MetadataValue
/// The privacy attributes associated with this metadata value.
public var attributes: MetadataValueAttributes
/// Create an attributed metadata value with the specified attributes.
///
/// - Parameters:
/// - value: The metadata value to wrap.
/// - attributes: The attributes for this value.
public init(_ value: MetadataValue, attributes: MetadataValueAttributes)
/// Convenience initializer for creating attributed metadata with a privacy level.
///
/// - Parameters:
/// - value: The metadata value to wrap.
/// - privacy: The privacy level for this value.
public init(_ value: MetadataValue, privacy: PrivacyLevel)
}
/// Metadata dictionary with privacy attributes.
///
/// A dictionary mapping string keys to ``AttributedMetadataValue`` instances, used with
/// the `attributedMetadata` parameter of logging methods.
///
/// ## Example
///
/// ```swift
/// let userId = "12345"
/// let requestId = "req-789"
/// let metadata: Logger.AttributedMetadata = [
/// "user.id": "\(userId, privacy: .private)",
/// "request.id": "\(requestId, privacy: .public)",
/// "action": "purchase" // String literal defaults to .public
/// ]
/// logger.info("User action", attributedMetadata: metadata)
/// ```
public typealias AttributedMetadata = [String: AttributedMetadataValue]
}
```
#### String interpolation for attributed metadata
```swift
extension Logger.AttributedMetadataValue: ExpressibleByStringLiteral, ExpressibleByStringInterpolation {
/// Custom string interpolation that captures privacy levels from interpolated values.
///
/// This enables syntax like:
/// ```swift
/// logger.info("User action", attributedMetadata: [
/// "user.id": "\(userId, privacy: .private)",
/// "action": "\(action, privacy: .public)"
/// ])
/// ```
public struct StringInterpolation: StringInterpolationProtocol {
public init(literalCapacity: Int, interpolationCount: Int)
public mutating func appendLiteral(_ literal: String)
/// Interpolation with explicit privacy parameter.
public mutating func appendInterpolation<T>(_ value: T, privacy: Logger.PrivacyLevel = .public)
where T: CustomStringConvertible
}
/// Creates an attributed metadata value from a string literal (defaults to .public).
public init(stringLiteral value: String)
/// Creates an attributed metadata value from string interpolation.
public init(stringInterpolation: StringInterpolation)
}
```
#### New Logger methods
```swift
extension Logger {
// Attributed metadata storage
var attributedMetadata: Logger.AttributedMetadata { get set }
subscript(attributedMetadataKey: String) -> Logger.AttributedMetadataValue? { get set }
// Log family of methods
public func log(level: Level, _ message: @autoclosure () -> Message,
attributedMetadata: @autoclosure () -> AttributedMetadata?,
source: @autoclosure () -> String? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line)
public func trace(_ message: @autoclosure () -> Message,
attributedMetadata: @autoclosure () -> AttributedMetadata?,
source: @autoclosure () -> String? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line)
public func debug(_ message: @autoclosure () -> Message,
attributedMetadata: @autoclosure () -> AttributedMetadata?,
source: @autoclosure () -> String? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line)
public func info(_ message: @autoclosure () -> Message,
attributedMetadata: @autoclosure () -> AttributedMetadata?,
source: @autoclosure () -> String? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line)
public func notice(_ message: @autoclosure () -> Message,
attributedMetadata: @autoclosure () -> AttributedMetadata?,
source: @autoclosure () -> String? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line)
public func warning(_ message: @autoclosure () -> Message,
attributedMetadata: @autoclosure () -> AttributedMetadata?,
source: @autoclosure () -> String? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line)
public func error(_ message: @autoclosure () -> Message,
attributedMetadata: @autoclosure () -> AttributedMetadata?,
source: @autoclosure () -> String? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line)
public func critical(_ message: @autoclosure () -> Message,
attributedMetadata: @autoclosure () -> AttributedMetadata?,
source: @autoclosure () -> String? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line)
}
```
#### AttributedMetadata support in LogHandler protocol
```swift
protocol LogHandler {
func log(level: Logger.Level, message: Logger.Message,
attributedMetadata: Logger.AttributedMetadata?, source: String,
file: String, function: String, line: UInt)
var attributedMetadata: Logger.AttributedMetadata { get set }
subscript(attributedMetadataKey: String) -> Logger.AttributedMetadataValue? { get set }
}
// Default implementations provided for backward compatibility
extension LogHandler {
// Default attributed metadata log method - redacts private values using helper
public func log(level: Logger.Level, message: Logger.Message,
attributedMetadata: Logger.AttributedMetadata?,
source: String, file: String, function: String, line: UInt) {
let processedMetadata = attributedMetadata.flatMap(Self.attributedToPlain)
self.log(level: level, message: message, metadata: processedMetadata,
source: source, file: file, function: function, line: line)
}
// Default attributed metadata storage - uses helpers for conversion
public var attributedMetadata: Logger.AttributedMetadata {
get { self.metadata.mapValues(Self.plainToAttributed) }
set { self.metadata = newValue.mapValues(Self.attributedToPlain) }
}
public subscript(attributedMetadataKey key: String) -> Logger.AttributedMetadataValue? {
get {
guard let plainValue = self[metadataKey: key] else { return nil }
return Self.plainToAttributed(plainValue)
}
set {
if let attributedValue = newValue {
self[metadataKey: key] = Self.attributedToPlain(attributedValue)
} else {
self[metadataKey: key] = nil
}
}
}
}
```
#### AttributedMetadata support in MetadataProvider
```swift
extension Logger.MetadataProvider {
/// Creates a new metadata provider that returns attributed metadata.
///
/// Attributed metadata providers allow you to specify privacy levels and other
/// attributes for each metadata value. When accessed through the plain ``get()``
/// method (for backward compatibility), private values are redacted to `"<private>"`.
///
/// ### Example
///
/// ```swift
/// let provider = Logger.MetadataProvider {
/// [
/// "request-id": "\(RequestContext.current.id, privacy: .public)",
/// "user-id": "\(RequestContext.current.userId, privacy: .private)"
/// ]
/// }
/// ```
///
/// - Parameter provideAttributed: A closure that extracts attributed metadata from the current execution context.
/// - Returns: A metadata provider that returns attributed metadata.
@_disfavoredOverload
public static func init(_ provideAttributed: @escaping @Sendable () -> AttributedMetadata) -> MetadataProvider
/// Returns attributed metadata if this is an attributed provider.
///
/// Handlers supporting attributed metadata should call this first,
/// falling back to `get()` if it returns nil.
public func getAttributed() -> AttributedMetadata?
}
```
### API stability
- All existing APIs unchanged.
- Plain and attributed metadata APIs coexist.
- No deprecation planned.
- Adoption is optional and incremental on both application and Log Handler sides.
- Default implementation ensures existing handlers work; logging private metadata is an application concern requiring a compatible `LogHandler`.
### Future directions
- Add more attributes (e.g., value data type, etc) and potential future unification of plain and attributed metadata APIs.
- Introduce "custom attributes", allowing applications to define application-specific attributes to work with application-specific log handlers.
### Alternatives considered
1. **Key-based redaction:** Configure which keys should be treated as private rather than marking each value:
```swift
logger.privateKeys = ["user.id", "password", "email"]
logger.info("User action", metadata: [
"user.id": "12345", // Automatically private
"action": "login" // Automatically public
])
```
Advantages:
- Simpler API (no new types).
- Centralized configuration.
- Safer at scale (new sensitive fields update all logs automatically).
- Easier migration.
**Not chosen because:**
- **Privacy belongs to data, not identifiers:** The same private data might be logged under different keys ("email", "user.email", "contact"), and the same key might contain different data with different privacy requirements in different contexts. Key-based redaction creates a synchronization problem—developers must maintain a separate list of "private keys" that stays in sync with actual logging code across the codebase, with no compile-time or review-time verification.
- **Code review visibility:** With value-based privacy, reviewers see privacy decisions at the call site: `"email": user.email.private()` makes it immediately clear that data is sensitive. With key-based redaction, reviewers must cross-reference a separate configuration file, making security review significantly harder.
- **No synchronization needed:** Value-based privacy is self-contained—privacy travels with the data at the point of use. No separate configuration to maintain, no risk of configuration drift, no runtime surprises when a key is missing from the private keys list.
- **Pattern complexity:** Supporting patterns/regex adds complexity and potential performance concerns.
The current design prioritizes **explicitness and data-centric privacy** over **configuration-based simplicity**. Privacy decisions are made where data is logged, making them visible during code review and keeping privacy attributes coupled to the data they protect.
2. **Convenience methods (`.private()` and `.public()`):** Add extension methods to `String` and `MetadataValue` for creating attributed metadata:
```swift
extension String {
public func `private`() -> Logger.AttributedMetadataValue
public func `public`() -> Logger.AttributedMetadataValue
}
logger.info("User action", attributedMetadata: [
"user.id": "12345".private(),
"action": "login".public()
])
```
**Not chosen because:**
- **Consistency with existing patterns:** `Logger.Message` and `Logger.MetadataValue` already use string interpolation extensively.
- **Natural syntax:** `"\(value, privacy: .private)"` reads clearly and fits Swift's interpolation conventions.
- **Less API surface:** No need for multiple extension methods across different types.
Metadata values already support string interpolation in SwiftLog. Rather than inventing additional API surface area with new methods, we leverage the existing string interpolation infrastructure with a custom `StringInterpolation` type. This provides:
3. **Default privacy level to `.private`:** Make attributed metadata values default to `.private` privacy level when no explicit privacy parameter is provided:
```swift
logger.info("User action", attributedMetadata: [
"user.id": "\(userId, privacy: .private)", // Explicit private (redundant with default)
"action": "\(action, privacy: .public)" // Must explicitly mark as public
])
```
Advantages:
- Security-by-default: requires explicit opt-out for logging non-sensitive data.
- Safer for accidental inclusion of sensitive data.
**Not chosen because:**
Privacy should be an explicit opt-in action from the user. The current design (defaulting to `.public`) prioritizes **ease of adoption** over **security-by-default**:
- Easier adoption - less boilerplate for common non-sensitive metadata.
- Matches the mental model that "most data is safe to log".
- Lower friction for migration from plain metadata.
- Forces developers to think about privacy only for sensitive data, rather than requiring `.public` annotations everywhere.
4. **Pass all metadata to non-privacy-aware handlers:** Security risk; current design filters private data by default.
5. **Message-level privacy:** Less granular than metadata-level privacy and requires message handling changes.
6. **Privacy level handling configuration** to be an attribute of the `Logger` instead of LogHandler configuration. This would centralize the configuration across various `LogHandler` implementations. However, existing `LogHandler` already have configurations and they might want to customize the behavior even further.
7. **Handler metadata merging:** LogHandlers are responsible for merging their own `metadata` property, `metadataProvider` output, and the explicit `attributedMetadata` parameter. This is consistent with how plain metadata works - handlers control merging. Plain handler metadata and provider values should be treated as public (`.public` privacy level). Attributed metadata from the log call takes precedence.
8. **Add a third `.auto`/`.default` privacy attribute value:** Libraries and applications can mark a metadata value as `privacy: .default` and rely on the `LogHandler` to configure what the default is. While this might've been a solution to overcome default `.public` values for all the attributed metadata, in reality it is confusing from the semantic point of view. If someone wants to mark something as `.default`, because this _might_ be sensitive, then it should be marked as `.private` or not logged at all. If something does not need to be marked as `.private`, then it is `.public`. A custom `LogHandler` with an allow list of metadata keys/messages/modules can be used as an escape hatch in case the application does not trust its dependencies.
@@ -8,7 +8,7 @@ handler implementations.
- Proposal: SLG-0005
- Author(s): [Vladimir Kukushkin](https://github.com/kukushechkin)
- Status: **Ready for Implementation**
- Status: **Approved**
- Issue: [apple/swift-log#421](https://github.com/apple/swift-log/issues/421)
- Implementation:
- [apple/swift-log#423](https://github.com/apple/swift-log/pull/423)
+38
View File
@@ -26,6 +26,9 @@ public struct LogEvent: Sendable {
/// The message of this event.
public var message: Logger.Message
/// The error associated with this event, if any.
public var error: (any Error)?
/// The metadata associated with this event, if any.
public var metadata: Logger.Metadata? {
get { self._metadata }
@@ -75,9 +78,44 @@ public struct LogEvent: Sendable {
file: String,
function: String,
line: UInt
) {
self.init(
level: level,
message: message,
error: nil,
metadata: metadata,
source: source,
file: file,
function: function,
line: line
)
}
/// Creates a new log event.
///
/// - Parameters:
/// - level: The log level of this event.
/// - message: The message of this event.
/// - error: The error associated with this event, if any.
/// - metadata: The metadata associated with this event, if any.
/// - source: The source where this log event originated. When `nil`, ``source`` is derived lazily
/// from ``file`` on first access so handlers that never read it pay no allocation cost.
/// - file: The file this log event originates from.
/// - function: The function this log event originates from.
/// - line: The line this log event originates from.
public init(
level: Logger.Level,
message: Logger.Message,
error: (any Error)?,
metadata: Logger.Metadata?,
source: String?,
file: String,
function: String,
line: UInt
) {
self.level = level
self.message = message
self.error = error
self._metadata = metadata
self._source = source
self.file = file
+438 -54
View File
@@ -97,6 +97,127 @@ public struct Logger {
}
extension Logger {
/// Log a message using the log level and source that you provide.
///
/// If the `logLevel` passed to this method is more severe than the `Logger`'s ``logLevel``, the library
/// logs the message, otherwise nothing will happen.
///
/// NOTE: This method adds a constant overhead over calling level-specific methods.
///
/// - parameters:
/// - level: The severity level of the `message`.
/// - message: The message to be logged. The `message` parameter supports any string interpolation literal.
/// - error: An `Error` related to the event.
/// - metadata: One-off metadata to attach to this log message.
/// - source: The source this log message originates from. The value defaults
/// to the module that emits the log message.
/// - file: The file this log message originates from. There's usually no need to pass it explicitly, as it
/// defaults to `#fileID`.
/// - function: The function this log message originates from. There's usually no need to pass it explicitly, as
/// it defaults to `#function`.
/// - line: The line this log message originates from. There's usually no need to pass it explicitly, as it
/// defaults to `#line`.
@inlinable
public func log(
level: Logger.Level,
_ message: @autoclosure () -> Logger.Message,
error: @autoclosure () -> (any Error)? = nil,
metadata: @autoclosure () -> Logger.Metadata? = nil,
source: @autoclosure () -> String? = nil,
file: String = #fileID,
function: String = #function,
line: UInt = #line
) {
#if MaxLogLevelDebug || MaxLogLevelInfo || MaxLogLevelNotice || MaxLogLevelWarning || MaxLogLevelError || MaxLogLevelCritical || MaxLogLevelNone
// A constant overhead is added for dynamic log level calls if one of the traits is enabled.
// This allows picking the necessary implementation with compiled out body in runtime.
switch level {
case .trace:
self.trace(
message(),
error: error(),
metadata: metadata(),
source: source(),
file: file,
function: function,
line: line
)
case .debug:
self.debug(
message(),
error: error(),
metadata: metadata(),
source: source(),
file: file,
function: function,
line: line
)
case .info:
self.info(
message(),
error: error(),
metadata: metadata(),
source: source(),
file: file,
function: function,
line: line
)
case .notice:
self.notice(
message(),
error: error(),
metadata: metadata(),
source: source(),
file: file,
function: function,
line: line
)
case .warning:
self.warning(
message(),
error: error(),
metadata: metadata(),
source: source(),
file: file,
function: function,
line: line
)
case .error:
self.error(
message(),
error: error(),
metadata: metadata(),
source: source(),
file: file,
function: function,
line: line
)
case .critical:
self.critical(
message(),
error: error(),
metadata: metadata(),
source: source(),
file: file,
function: function,
line: line
)
}
#else
// If no logs are excluded in the compile time, we can avoid checking the log level that extra time and go log it.
self._log(
level: level,
message(),
error: error(),
metadata: metadata(),
source: source(),
file: file,
function: function,
line: line
)
#endif
}
/// Log a message using the log level and source that you provide.
///
/// If the `logLevel` passed to this method is more severe than the `Logger`'s ``logLevel``, the library
@@ -126,37 +247,16 @@ extension Logger {
function: String = #function,
line: UInt = #line
) {
#if MaxLogLevelDebug || MaxLogLevelInfo || MaxLogLevelNotice || MaxLogLevelWarning || MaxLogLevelError || MaxLogLevelCritical || MaxLogLevelNone
// A constant overhead is added for dynamic log level calls if one of the traits is enabled.
// This allows picking the necessary implementation with compiled out body in runtime.
switch level {
case .trace:
self.trace(message(), metadata: metadata(), source: source(), file: file, function: function, line: line)
case .debug:
self.debug(message(), metadata: metadata(), source: source(), file: file, function: function, line: line)
case .info:
self.info(message(), metadata: metadata(), source: source(), file: file, function: function, line: line)
case .notice:
self.notice(message(), metadata: metadata(), source: source(), file: file, function: function, line: line)
case .warning:
self.warning(message(), metadata: metadata(), source: source(), file: file, function: function, line: line)
case .error:
self.error(message(), metadata: metadata(), source: source(), file: file, function: function, line: line)
case .critical:
self.critical(message(), metadata: metadata(), source: source(), file: file, function: function, line: line)
}
#else
// If no logs are excluded in the compile time, we can avoid checking the log level that extra time and go log it.
self._log(
self.log(
level: level,
message(),
error: nil,
metadata: metadata(),
source: source(),
file: file,
function: function,
line: line
)
#endif
}
/// Log a message using the log level and source that you provide.
@@ -180,6 +280,7 @@ extension Logger {
package func _log(
level: Logger.Level,
_ message: @autoclosure () -> Logger.Message,
error: @autoclosure () -> (any Error)? = nil,
metadata: @autoclosure () -> Logger.Metadata? = nil,
source: @autoclosure () -> String? = nil,
file: String = #fileID,
@@ -191,6 +292,7 @@ extension Logger {
event: LogEvent(
level: level,
message: message(),
error: error(),
metadata: metadata(),
source: source(),
file: file,
@@ -206,6 +308,8 @@ extension Logger {
/// If the `logLevel` passed to this method is more severe than the `Logger`'s ``logLevel``, the library
/// logs the message, otherwise nothing will happen.
///
/// NOTE: This method adds a constant overhead over calling level-specific methods.
///
/// - parameters:
/// - level: The log level to log the `message`.
/// - message: The message to be logged. The `message` parameter supports any string interpolation literal.
@@ -259,6 +363,47 @@ extension Logger {
}
extension Logger {
/// Log a message at the 'trace' log level with the source that you provide.
///
/// If ``Level/trace`` is at least as severe as this logger's ``logLevel`` the system logs the message;
/// otherwise nothing will happen.
///
/// - parameters:
/// - message: The message to be logged. The `message` parameter supports any string interpolation literal.
/// - error: An `Error` related to the event.
/// - metadata: One-off metadata to attach to this log message.
/// - source: The source this log message originates from. The value defaults
/// to the module that emits the log message.
/// - file: The file this log message originates from. There's usually no need to pass it explicitly, as it
/// defaults to `#fileID`.
/// - function: The function this log message originates from. There's usually no need to pass it explicitly, as
/// it defaults to `#function`.
/// - line: The line this log message originates from. There's usually no need to pass it explicitly, as it
/// defaults to `#line`.
@inlinable
public func trace(
_ message: @autoclosure () -> Logger.Message,
error: @autoclosure () -> (any Error)? = nil,
metadata: @autoclosure () -> Logger.Metadata? = nil,
source: @autoclosure () -> String? = nil,
file: String = #fileID,
function: String = #function,
line: UInt = #line
) {
#if !MaxLogLevelDebug && !MaxLogLevelInfo && !MaxLogLevelNotice && !MaxLogLevelWarning && !MaxLogLevelError && !MaxLogLevelCritical && !MaxLogLevelNone
self._log(
level: .trace,
message(),
error: error(),
metadata: metadata(),
source: source(),
file: file,
function: function,
line: line
)
#endif
}
/// Log a message at the 'trace' log level with the source that you provide.
///
/// If ``Level/trace`` is at least as severe as this logger's ``logLevel`` the system logs the message;
@@ -284,17 +429,15 @@ extension Logger {
function: String = #function,
line: UInt = #line
) {
#if !MaxLogLevelDebug && !MaxLogLevelInfo && !MaxLogLevelNotice && !MaxLogLevelWarning && !MaxLogLevelError && !MaxLogLevelCritical && !MaxLogLevelNone
self._log(
level: .trace,
self.trace(
message(),
error: nil,
metadata: metadata(),
source: source(),
file: file,
function: function,
line: line
)
#endif
}
/// Log a message at the 'trace' log level.
@@ -322,6 +465,47 @@ extension Logger {
self.trace(message(), metadata: metadata(), source: nil, file: file, function: function, line: line)
}
/// Log a message at the 'debug' log level with the source that you provide.
///
/// If ``Level/debug`` is at least as severe as this logger's ``logLevel`` the system logs the message;
/// otherwise nothing will happen.
///
/// - parameters:
/// - message: The message to be logged. The `message` parameter supports any string interpolation literal.
/// - error: An `Error` related to the event.
/// - metadata: One-off metadata to attach to this log message.
/// - source: The source this log message originates from. The value defaults
/// to the module that emits the log message.
/// - file: The file this log message originates from. There's usually no need to pass it explicitly, as it
/// defaults to `#fileID`.
/// - function: The function this log message originates from. There's usually no need to pass it explicitly, as
/// it defaults to `#function`.
/// - line: The line this log message originates from. There's usually no need to pass it explicitly, as it
/// defaults to `#line`.
@inlinable
public func debug(
_ message: @autoclosure () -> Logger.Message,
error: @autoclosure () -> (any Error)? = nil,
metadata: @autoclosure () -> Logger.Metadata? = nil,
source: @autoclosure () -> String? = nil,
file: String = #fileID,
function: String = #function,
line: UInt = #line
) {
#if !MaxLogLevelInfo && !MaxLogLevelNotice && !MaxLogLevelWarning && !MaxLogLevelError && !MaxLogLevelCritical && !MaxLogLevelNone
self._log(
level: .debug,
message(),
error: error(),
metadata: metadata(),
source: source(),
file: file,
function: function,
line: line
)
#endif
}
/// Log a message at the 'debug' log level with the source that you provide.
///
/// If ``Level/debug`` is at least as severe as this logger's ``logLevel`` the system logs the message;
@@ -347,17 +531,15 @@ extension Logger {
function: String = #function,
line: UInt = #line
) {
#if !MaxLogLevelInfo && !MaxLogLevelNotice && !MaxLogLevelWarning && !MaxLogLevelError && !MaxLogLevelCritical && !MaxLogLevelNone
self._log(
level: .debug,
self.debug(
message(),
error: nil,
metadata: metadata(),
source: source(),
file: file,
function: function,
line: line
)
#endif
}
/// Log a message at the 'debug' log level.
@@ -385,6 +567,47 @@ extension Logger {
self.debug(message(), metadata: metadata(), source: nil, file: file, function: function, line: line)
}
/// Log a message at the 'info' log level with the source that you provide.
///
/// If ``Level/info`` is at least as severe as this logger's ``logLevel`` the system logs the message;
/// otherwise nothing will happen.
///
/// - parameters:
/// - message: The message to be logged. The `message` parameter supports any string interpolation literal.
/// - error: An `Error` related to the event.
/// - metadata: One-off metadata to attach to this log message.
/// - source: The source this log message originates from. The value defaults
/// to the module that emits the log message.
/// - file: The file this log message originates from. There's usually no need to pass it explicitly, as it
/// defaults to `#fileID`.
/// - function: The function this log message originates from. There's usually no need to pass it explicitly, as
/// it defaults to `#function`.
/// - line: The line this log message originates from. There's usually no need to pass it explicitly, as it
/// defaults to `#line`.
@inlinable
public func info(
_ message: @autoclosure () -> Logger.Message,
error: @autoclosure () -> (any Error)? = nil,
metadata: @autoclosure () -> Logger.Metadata? = nil,
source: @autoclosure () -> String? = nil,
file: String = #fileID,
function: String = #function,
line: UInt = #line
) {
#if !MaxLogLevelNotice && !MaxLogLevelWarning && !MaxLogLevelError && !MaxLogLevelCritical && !MaxLogLevelNone
self._log(
level: .info,
message(),
error: error(),
metadata: metadata(),
source: source(),
file: file,
function: function,
line: line
)
#endif
}
/// Log a message at the 'info' log level with the source that you provide.
///
/// If ``Level/info`` is at least as severe as this logger's ``logLevel`` the system logs the message;
@@ -410,17 +633,15 @@ extension Logger {
function: String = #function,
line: UInt = #line
) {
#if !MaxLogLevelNotice && !MaxLogLevelWarning && !MaxLogLevelError && !MaxLogLevelCritical && !MaxLogLevelNone
self._log(
level: .info,
self.info(
message(),
error: nil,
metadata: metadata(),
source: source(),
file: file,
function: function,
line: line
)
#endif
}
/// Log a message at the 'info' log level.
@@ -448,6 +669,47 @@ extension Logger {
self.info(message(), metadata: metadata(), source: nil, file: file, function: function, line: line)
}
/// Log a message at the 'notice' log level with the source that you provide.
///
/// If ``Level/notice`` is at least as severe as this logger's ``logLevel`` the system logs the message;
/// otherwise nothing will happen.
///
/// - parameters:
/// - message: The message to be logged. The `message` parameter supports any string interpolation literal.
/// - error: An `Error` related to the event.
/// - metadata: One-off metadata to attach to this log message.
/// - source: The source this log message originates from. The value defaults
/// to the module that emits the log message.
/// - file: The file this log message originates from. There's usually no need to pass it explicitly, as it
/// defaults to `#fileID`.
/// - function: The function this log message originates from. There's usually no need to pass it explicitly, as
/// it defaults to `#function`.
/// - line: The line this log message originates from. There's usually no need to pass it explicitly, as it
/// defaults to `#line`.
@inlinable
public func notice(
_ message: @autoclosure () -> Logger.Message,
error: @autoclosure () -> (any Error)? = nil,
metadata: @autoclosure () -> Logger.Metadata? = nil,
source: @autoclosure () -> String? = nil,
file: String = #fileID,
function: String = #function,
line: UInt = #line
) {
#if !MaxLogLevelWarning && !MaxLogLevelError && !MaxLogLevelCritical && !MaxLogLevelNone
self._log(
level: .notice,
message(),
error: error(),
metadata: metadata(),
source: source(),
file: file,
function: function,
line: line
)
#endif
}
/// Log a message at the 'notice' log level with the source that you provide.
///
/// If ``Level/notice`` is at least as severe as this logger's ``logLevel`` the system logs the message;
@@ -473,17 +735,15 @@ extension Logger {
function: String = #function,
line: UInt = #line
) {
#if !MaxLogLevelWarning && !MaxLogLevelError && !MaxLogLevelCritical && !MaxLogLevelNone
self._log(
level: .notice,
self.notice(
message(),
error: nil,
metadata: metadata(),
source: source(),
file: file,
function: function,
line: line
)
#endif
}
/// Log a message at the 'notice' log level.
@@ -511,6 +771,47 @@ extension Logger {
self.notice(message(), metadata: metadata(), source: nil, file: file, function: function, line: line)
}
/// Log a message at the 'warning' log level with the source that you provide.
///
/// If ``Level/warning`` is at least as severe as this logger's ``logLevel`` the system logs the message;
/// otherwise nothing will happen.
///
/// - parameters:
/// - message: The message to be logged. The `message` parameter supports any string interpolation literal.
/// - error: An `Error` related to the event.
/// - metadata: One-off metadata to attach to this log message.
/// - source: The source this log message originates from. The value defaults
/// to the module that emits the log message.
/// - file: The file this log message originates from. There's usually no need to pass it explicitly, as it
/// defaults to `#fileID`.
/// - function: The function this log message originates from. There's usually no need to pass it explicitly, as
/// it defaults to `#function`.
/// - line: The line this log message originates from. There's usually no need to pass it explicitly, as it
/// defaults to `#line`.
@inlinable
public func warning(
_ message: @autoclosure () -> Logger.Message,
error: @autoclosure () -> (any Error)? = nil,
metadata: @autoclosure () -> Logger.Metadata? = nil,
source: @autoclosure () -> String? = nil,
file: String = #fileID,
function: String = #function,
line: UInt = #line
) {
#if !MaxLogLevelError && !MaxLogLevelCritical && !MaxLogLevelNone
self._log(
level: .warning,
message(),
error: error(),
metadata: metadata(),
source: source(),
file: file,
function: function,
line: line
)
#endif
}
/// Log a message at the 'warning' log level with the source that you provide.
///
/// If ``Level/warning`` is at least as severe as this logger's ``logLevel`` the system logs the message;
@@ -536,17 +837,15 @@ extension Logger {
function: String = #function,
line: UInt = #line
) {
#if !MaxLogLevelError && !MaxLogLevelCritical && !MaxLogLevelNone
self._log(
level: .warning,
self.warning(
message(),
error: nil,
metadata: metadata(),
source: source(),
file: file,
function: function,
line: line
)
#endif
}
/// Log a message at the 'warning' log level.
@@ -574,6 +873,47 @@ extension Logger {
self.warning(message(), metadata: metadata(), source: nil, file: file, function: function, line: line)
}
/// Log a message at the 'error' log level with the source that you provide.
///
/// If ``Level/error`` is at least as severe as this logger's ``logLevel`` the system logs the message;
/// otherwise nothing will happen.
///
/// - parameters:
/// - message: The message to be logged. The `message` parameter supports any string interpolation literal.
/// - error: An `Error` related to the event.
/// - metadata: One-off metadata to attach to this log message.
/// - source: The source this log message originates from. The value defaults
/// to the module that emits the log message.
/// - file: The file this log message originates from. There's usually no need to pass it explicitly, as it
/// defaults to `#fileID`.
/// - function: The function this log message originates from. There's usually no need to pass it explicitly, as
/// it defaults to `#function`.
/// - line: The line this log message originates from. There's usually no need to pass it explicitly, as it
/// defaults to `#line`.
@inlinable
public func error(
_ message: @autoclosure () -> Logger.Message,
error: @autoclosure () -> (any Error)? = nil,
metadata: @autoclosure () -> Logger.Metadata? = nil,
source: @autoclosure () -> String? = nil,
file: String = #fileID,
function: String = #function,
line: UInt = #line
) {
#if !MaxLogLevelCritical && !MaxLogLevelNone
self._log(
level: .error,
message(),
error: error(),
metadata: metadata(),
source: source(),
file: file,
function: function,
line: line
)
#endif
}
/// Log a message at the 'error' log level with the source that you provide.
///
/// If ``Level/error`` is at least as severe as this logger's ``logLevel`` the system logs the message;
@@ -599,17 +939,15 @@ extension Logger {
function: String = #function,
line: UInt = #line
) {
#if !MaxLogLevelCritical && !MaxLogLevelNone
self._log(
level: .error,
self.error(
message(),
error: nil,
metadata: metadata(),
source: source(),
file: file,
function: function,
line: line
)
#endif
}
/// Log a message at the 'error' log level.
@@ -637,6 +975,47 @@ extension Logger {
self.error(message(), metadata: metadata(), source: nil, file: file, function: function, line: line)
}
/// Log a message at the 'critical' log level with the source that you provide.
///
/// If ``Level/critical`` is at least as severe as this logger's ``logLevel`` the system logs the message;
/// otherwise nothing will happen.
///
/// - parameters:
/// - message: The message to be logged. The `message` parameter supports any string interpolation literal.
/// - error: An `Error` related to the event.
/// - metadata: One-off metadata to attach to this log message.
/// - source: The source this log message originates from. The value defaults
/// to the module that emits the log message.
/// - file: The file this log message originates from. There's usually no need to pass it explicitly, as it
/// defaults to `#fileID`.
/// - function: The function this log message originates from. There's usually no need to pass it explicitly, as
/// it defaults to `#function`.
/// - line: The line this log message originates from. There's usually no need to pass it explicitly, as it
/// defaults to `#line`.
@inlinable
public func critical(
_ message: @autoclosure () -> Logger.Message,
error: @autoclosure () -> (any Error)? = nil,
metadata: @autoclosure () -> Logger.Metadata? = nil,
source: @autoclosure () -> String? = nil,
file: String = #fileID,
function: String = #function,
line: UInt = #line
) {
#if !MaxLogLevelNone
self._log(
level: .critical,
message(),
error: error(),
metadata: metadata(),
source: source(),
file: file,
function: function,
line: line
)
#endif
}
/// Log a message at the 'critical' log level with the source that you provide.
///
/// If ``Level/critical`` is at least as severe as this logger's ``logLevel`` the system logs the message;
@@ -662,17 +1041,15 @@ extension Logger {
function: String = #function,
line: UInt = #line
) {
#if !MaxLogLevelNone
self._log(
level: .critical,
self.critical(
message(),
error: nil,
metadata: metadata(),
source: source(),
file: file,
function: function,
line: line
)
#endif
}
/// Log a message at the 'critical' log level.
@@ -1684,7 +2061,8 @@ public struct StreamLogHandler: LogHandler {
let effectiveMetadata = StreamLogHandler.prepareMetadata(
base: self.metadata,
provider: self.metadataProvider,
explicit: event.metadata
explicit: event.metadata,
error: event.error,
)
let prettyMetadata: String?
@@ -1726,13 +2104,14 @@ public struct StreamLogHandler: LogHandler {
internal static func prepareMetadata(
base: Logger.Metadata,
provider: Logger.MetadataProvider?,
explicit: Logger.Metadata?
explicit: Logger.Metadata?,
error: (any Error)?,
) -> Logger.Metadata? {
var metadata = base
let provided = provider?.get() ?? [:]
guard !provided.isEmpty || !((explicit ?? [:]).isEmpty) else {
guard !provided.isEmpty || !((explicit ?? [:]).isEmpty) || error != nil else {
// all per-log-statement values are empty
return nil
}
@@ -1745,6 +2124,11 @@ public struct StreamLogHandler: LogHandler {
metadata.merge(explicit, uniquingKeysWith: { _, explicit in explicit })
}
if let error {
metadata["error.message"] = "\(error)"
metadata["error.type"] = "\(String(reflecting: type(of: error)))"
}
return metadata
}
@@ -69,6 +69,53 @@ struct InMemoryLogHandlerTests {
)
}
@Test
func errorEquality() throws {
let (logHandler, logger) = self.makeTestLogger()
logger.info("hello", error: TestError.first)
let entry = try #require(logHandler.entries.first)
#expect(
entry
== InMemoryLogHandler.Entry(
level: .info,
message: "hello",
error: TestError.first,
metadata: [:],
)
)
#expect(
entry
!= InMemoryLogHandler.Entry(
level: .info,
message: "hello",
error: nil,
metadata: [:],
)
)
#expect(
entry
!= InMemoryLogHandler.Entry(
level: .info,
message: "hello",
error: TestError.second,
metadata: [:]
)
)
#expect(
entry
!= InMemoryLogHandler.Entry(
level: .info,
message: "hello",
error: Nested.TestError.first,
metadata: [:]
)
)
}
@Test
func clear() {
let (logHandler, logger) = self.makeTestLogger()
@@ -95,4 +142,15 @@ struct InMemoryLogHandlerTests {
)
return (logHandler, logger)
}
enum TestError: Error {
case first
case second
}
struct Nested {
enum TestError: Error {
case first
}
}
}
+58 -2
View File
@@ -387,6 +387,7 @@ struct LoggingTest {
enum TestError: Error {
case boom
case withMessage(String)
}
@Test func dictionaryMetadata() {
@@ -515,6 +516,7 @@ struct LoggingTest {
logger.debug(self.dontEvaluateThisString())
logger.info(self.dontEvaluateThisString())
logger.warning(self.dontEvaluateThisString())
logger.warning(self.dontEvaluateThisString(), error: TestError.withMessage("\(self.dontEvaluateThisString())"))
logger.log(level: .warning, self.dontEvaluateThisString())
}
@@ -567,6 +569,19 @@ struct LoggingTest {
#expect(logger2.handler is CustomHandler, "expected custom log handler")
}
@Test func errorParameter() {
let testLogging = TestLogging()
let logger = Logger(
label: "\(#function)",
factory: {
testLogging.make(label: $0)
}
)
logger.log(level: .info, "hello world!", error: TestError.boom)
testLogging.history.assertExist(level: .info, message: "hello world!", error: TestError.boom)
}
@Test func allLogLevelsExceptCriticalCanBeBlocked() {
let testLogging = TestLogging()
@@ -623,7 +638,48 @@ struct LoggingTest {
testLogging.history.assertExist(level: .critical, message: "yes: critical")
}
@Test func allLogLevelByFunctionRefWithSource() {
@Test func allLogLevelByFunctionRefWithSourceAndError() {
let testLogging = TestLogging()
var logger = Logger(
label: "\(#function)",
factory: {
testLogging.make(label: $0)
}
)
logger.logLevel = .trace
let trace = logger.trace(_:error:metadata:source:file:function:line:)
let debug = logger.debug(_:error:metadata:source:file:function:line:)
let info = logger.info(_:error:metadata:source:file:function:line:)
let notice = logger.notice(_:error:metadata:source:file:function:line:)
let warning = logger.warning(_:error:metadata:source:file:function:line:)
let error = logger.error(_:error:metadata:source:file:function:line:)
let critical = logger.critical(_:error:metadata:source:file:function:line:)
trace("yes: trace", TestError.boom, [:], "foo", #file, #function, #line)
debug("yes: debug", TestError.boom, [:], "foo", #file, #function, #line)
info("yes: info", TestError.boom, [:], "foo", #file, #function, #line)
notice("yes: notice", TestError.boom, [:], "foo", #file, #function, #line)
warning("yes: warning", TestError.boom, [:], "foo", #file, #function, #line)
error("yes: error", TestError.boom, [:], "foo", #file, #function, #line)
critical("yes: critical", TestError.boom, [:], "foo", #file, #function, #line)
testLogging.history.assertExist(level: .trace, message: "yes: trace", error: TestError.boom, source: "foo")
testLogging.history.assertExist(level: .debug, message: "yes: debug", error: TestError.boom, source: "foo")
testLogging.history.assertExist(level: .info, message: "yes: info", error: TestError.boom, source: "foo")
testLogging.history.assertExist(level: .notice, message: "yes: notice", error: TestError.boom, source: "foo")
testLogging.history.assertExist(level: .warning, message: "yes: warning", error: TestError.boom, source: "foo")
testLogging.history.assertExist(level: .error, message: "yes: error", error: TestError.boom, source: "foo")
testLogging.history.assertExist(
level: .critical,
message: "yes: critical",
error: TestError.boom,
source: "foo"
)
}
@Test func allLogLevelByFunctionRefWithSourceWithoutError() {
let testLogging = TestLogging()
var logger = Logger(
@@ -659,7 +715,7 @@ struct LoggingTest {
testLogging.history.assertExist(level: .critical, message: "yes: critical", source: "foo")
}
@Test func allLogLevelByFunctionRefWithoutSource() {
@Test func allLogLevelByFunctionRefWithoutSourceOrError() {
let testLogging = TestLogging()
var logger = Logger(
+48 -8
View File
@@ -90,13 +90,20 @@ internal struct TestLogHandler: LogHandler {
self.logger.log(
level: event.level,
event.message,
error: event.error,
metadata: metadata,
source: event.source,
file: event.file,
function: event.function,
line: event.line
)
self.recorder.record(level: event.level, metadata: metadata, message: event.message, source: event.source)
self.recorder.record(
level: event.level,
metadata: metadata,
message: event.message,
error: event.error,
source: event.source
)
}
private var _logLevel: Logger.Level?
@@ -167,10 +174,16 @@ internal class Recorder: History {
private let lock = NSLock()
private var _entries = [LogEntry]()
func record(level: Logger.Level, metadata: Logger.Metadata?, message: Logger.Message, source: String) {
func record(
level: Logger.Level,
metadata: Logger.Metadata?,
message: Logger.Message,
error: (any Error)? = nil,
source: String
) {
self.lock.withLock {
self._entries.append(
LogEntry(level: level, metadata: metadata, message: message.description, source: source)
LogEntry(level: level, metadata: metadata, message: message.description, error: error, source: source)
)
}
}
@@ -179,6 +192,7 @@ internal class Recorder: History {
level: Logger.Level,
metadata: Logger.Metadata?,
message: Logger.Message,
error: (any Error)? = nil,
source: String,
file: String,
function: String,
@@ -190,6 +204,7 @@ internal class Recorder: History {
level: level,
metadata: metadata,
message: message.description,
error: error,
source: source,
file: file,
function: function,
@@ -240,6 +255,7 @@ internal struct LogEntry {
let level: Logger.Level
let metadata: Logger.Metadata?
let message: String
let error: (any Error)?
let source: String
let file: String
let function: String
@@ -249,6 +265,7 @@ internal struct LogEntry {
level: Logger.Level,
metadata: Logger.Metadata?,
message: String,
error: (any Error)?,
source: String,
file: String = "",
function: String = "",
@@ -257,6 +274,7 @@ internal struct LogEntry {
self.level = level
self.metadata = metadata
self.message = message
self.error = error
self.source = source
self.file = file
self.function = function
@@ -268,6 +286,7 @@ extension History {
func assertExist(
level: Logger.Level,
message: String,
error: (any Error)? = nil,
metadata: Logger.Metadata? = nil,
source: String? = nil,
file: String = #filePath,
@@ -276,10 +295,10 @@ extension History {
column: Int = #column
) {
let source = source ?? Logger.currentModule(fileID: "\(fileID)")
let entry = self.find(level: level, message: message, metadata: metadata, source: source)
let entry = self.find(level: level, message: message, error: error, metadata: metadata, source: source)
#expect(
entry != nil,
"entry not found: \(level), \(source), \(String(describing: metadata)), \(message)",
"entry not found: \(level), \(source), \(String(describing: metadata)), \(message), \(String(describing: error))",
sourceLocation: SourceLocation(fileID: fileID, filePath: file, line: line, column: column)
)
}
@@ -287,6 +306,7 @@ extension History {
func assertNotExist(
level: Logger.Level,
message: String,
error: (any Error)? = nil,
metadata: Logger.Metadata? = nil,
source: String? = nil,
file: String = #filePath,
@@ -295,15 +315,21 @@ extension History {
column: Int = #column
) {
let source = source ?? Logger.currentModule(fileID: "\(fileID)")
let entry = self.find(level: level, message: message, metadata: metadata, source: source)
let entry = self.find(level: level, message: message, error: error, metadata: metadata, source: source)
#expect(
entry == nil,
"entry was found: \(level), \(source), \(String(describing: metadata)), \(message)",
"entry was found: \(level), \(source), \(String(describing: metadata)), \(message), \(String(describing: error))",
sourceLocation: SourceLocation(fileID: fileID, filePath: file, line: line, column: column)
)
}
func find(level: Logger.Level, message: String, metadata: Logger.Metadata? = nil, source: String) -> LogEntry? {
func find(
level: Logger.Level,
message: String,
error: (any Error)? = nil,
metadata: Logger.Metadata? = nil,
source: String
) -> LogEntry? {
self.entries.first { entry in
if entry.level != level {
return false
@@ -311,6 +337,9 @@ extension History {
if entry.message != message {
return false
}
if !errorsEqual(error, entry.error) {
return false
}
if let lhs = entry.metadata, let rhs = metadata {
if lhs.count != rhs.count {
return false
@@ -337,6 +366,17 @@ extension History {
return true
}
}
private func errorsEqual(_ lhs: (any Error)?, _ rhs: (any Error)?) -> Bool {
switch (lhs, rhs) {
case (nil, nil):
return true
case let (l?, r?):
return "\(l)" == "\(r)" && String(reflecting: type(of: l)) == String(reflecting: type(of: r))
default:
return false
}
}
}
/// MDC stands for Mapped Diagnostic Context
+5
View File
@@ -29,12 +29,14 @@ struct SendableTest {
let message1 = Logger.Message(stringLiteral: "critical 1")
let message2 = Logger.Message(stringLiteral: "critical 2")
let metadata: Logger.Metadata = ["key": "value"]
let error = TestError()
let task = Task.detached {
logger.info("info")
logger.critical(message1)
logger.critical(message2)
logger.warning(.init(stringLiteral: "warning"), metadata: metadata)
logger.warning("error", error: error)
}
await task.value
@@ -42,5 +44,8 @@ struct SendableTest {
testLogging.history.assertExist(level: .critical, message: "critical 1", metadata: [:])
testLogging.history.assertExist(level: .critical, message: "critical 2", metadata: [:])
testLogging.history.assertExist(level: .warning, message: "warning", metadata: metadata)
testLogging.history.assertExist(level: .warning, message: "error", error: error)
}
final class TestError: Error {}
}