From eca81998f52d757e22b3bfbff650025091453bc0 Mon Sep 17 00:00:00 2001 From: Vladimir Kukushkin Date: Wed, 13 May 2026 14:38:57 +0100 Subject: [PATCH] [SLG-0004]: metadata value attributes proposal (revision 2) (#440) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit > [!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. --- .../SLG-0004-metadata-value-attributes.md | 507 ++++++++++++++++++ ...0004-metadata-values-privacy-attributes.md | 467 ---------------- 2 files changed, 507 insertions(+), 467 deletions(-) create mode 100644 Sources/Logging/Docs.docc/Proposals/SLG-0004-metadata-value-attributes.md delete mode 100644 Sources/Logging/Docs.docc/Proposals/SLG-0004-metadata-values-privacy-attributes.md diff --git a/Sources/Logging/Docs.docc/Proposals/SLG-0004-metadata-value-attributes.md b/Sources/Logging/Docs.docc/Proposals/SLG-0004-metadata-value-attributes.md new file mode 100644 index 0000000..87abd72 --- /dev/null +++ b/Sources/Logging/Docs.docc/Proposals/SLG-0004-metadata-value-attributes.md @@ -0,0 +1,507 @@ +# SLG-0004: Metadata value attributes + +Add an extensible per-value attribute mechanism for metadata. + +## Overview + +- Proposal: SLG-0004 +- Author(s): [Vladimir Kukushkin](https://github.com/kukushechkin) +- Status: **Ready for Implementation** +- Issue: [apple/swift-log#204](https://github.com/apple/swift-log/issues/204) +- Implementation: + - [apple/swift-log#453](https://github.com/apple/swift-log/pull/453) +- Related links: + - [Lightweight proposals process description](https://github.com/apple/swift-log/blob/main/Sources/Logging/Docs.docc/Proposals/Proposals.md) + - [First iteration of the proposal](https://forums.swift.org/t/proposal-slg-0004-metadata-values-privacy-attribute/85249) + +### Introduction + +Introduce an extensible mechanism for attaching per-value attributes to metadata. The core `Logging` module provides +the protocol and storage. Attribute packages define concrete attributes using the +`Logger.MetadataValueAttributes.Attribute` protocol. + +### 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. + +Today, there is no way to express this. A single log statement can contain values that need different treatment, and +log levels cannot help because they are per-statement, not per-value: + +```swift +logger.info("Login", metadata: [ + "action": "\(action)", // safe to log + "user_email": "\(email)", // should be redacted in production, but nothing tells the handler +]) +``` + +The workaround is handler-side key-based rules (`redact: ["email", "card-*", ...]`), but this is fragile: + +- Rules break when libraries rename keys. +- Rules require coordination across all dependencies. +- The rule mapping is invisible at the call site. + +### Proposed solution + +Attributes are embedded directly in `MetadataValue` via the existing `.stringConvertible` case. A custom +`MetadataValue.StringInterpolation` type produces attributed values when any interpolation segment specifies +attributes. Libraries define attribute types conforming to `Logger.MetadataValueAttributes.Attribute` and provide +ergonomic string interpolation overloads. Handlers read the attributes via `value.attributes` and act on them: + +```swift +import Logging + +public enum Sensitivity: Int64, Logger.MetadataValueAttributes.Attribute, Sendable { + case sensitive = 1 + case `public` = 2 +} + +extension Logger.MetadataValue.StringInterpolation { + public mutating func appendInterpolation( + _ value: T, sensitivity: Sensitivity + ) { + self.appendInterpolation(value, attributes: { $0[Sensitivity.self] = sensitivity }) + } +} + +logger.info("Request", metadata: [ + "method": "\(req.method)", + "user_id": "\(req.userId, sensitivity: .sensitive)", +]) +``` + +Handlers that support specific attributes read them from `value.attributes` and act accordingly. Handlers that do not +understand attributes see plain `MetadataValue` instances — attributes are invisible unless explicitly inspected. The +existing `metadata:` parameter is the only parameter needed; no new log method overloads are added. + +Attributed values can also be created programmatically with the `.attributed` factory, which behaves like an additional +enum case without breaking existing exhaustive switches: + +```swift +let value: Logger.MetadataValue = .attributed(userId, attributes: [Sensitivity.sensitive]) +``` + +Intermediate handlers can read **and modify** attributes as metadata flows through a handler chain. The `attributes` +property supports both getting and setting, enabling composable pipelines where each handler in the chain can enrich, +transform, or strip attributes before forwarding: + +```swift +// An enriching handler that tags all metadata with a processing timestamp attribute +func log(event: LogEvent) { + var mutatedEvent = event + if var eventMetadata = event.metadata { + for (key, _) in eventMetadata { + var attrs = eventMetadata[key]!.attributes + attrs[ProcessingStage.self] = .enriched + eventMetadata[key]?.attributes = attrs + } + mutatedEvent.metadata = eventMetadata + } + self.inner.log(event: mutatedEvent) +} +``` + +Attributes are **classifications, not enforcement**. An attribute does not guarantee any particular handler behavior — +the handler may not support it. Applications needing guaranteed behavior must enforce it at a different abstraction. + +The attribute mechanism is extensible: packages define their own attribute types using +`Logger.MetadataValueAttributes.Attribute`. A +chained `LogHandler` can read the attributes it cares about, act on them, and forward the rest to the next handler in +the chain — enabling composable handler pipelines (e.g., redaction handler -> metrics-extraction handler -> output +handler). Common attributes should be defined in separate packages so that the core `Logging` module remains free of +domain-specific attributes while providing shared vocabulary across libraries. To improve discoverability, `swift-log` +can reference attribute packages that are common across the whole ecosystem. + +### Detailed design + +#### `Attribute` protocol + +```swift +extension Logger.MetadataValueAttributes { + /// A protocol for defining custom metadata attributes. + /// + /// Conform to this protocol to define a custom attribute that can be stored in + /// ``MetadataValueAttributes``. Each conforming type acts as both the key (identified + /// by its metatype) and the value. + /// + /// This protocol is designed for **small, fixed-vocabulary attributes** represented as + /// enums. Each attribute value is stored as an `Int64` raw value, so attributes occupy minimal + /// space (one inline slot without heap allocation for the common single-attribute case). + /// Attributes that need to carry associated data, strings, or richer payloads are outside + /// the scope of this protocol. + /// + /// ## Example + /// + /// ```swift + /// public enum Priority: Int64, Sendable, Logger.MetadataValueAttributes.Attribute { + /// case low = 1 + /// case high = 2 + /// } + /// ``` + public protocol Attribute: Sendable, + RawRepresentable where RawValue == Int64 {} +} +``` + +Each conforming type serves as both the key and the value for an attribute. The metatype (`Key.Type`) identifies +the attribute at runtime — no coordination between packages is needed. + +#### `MetadataValueAttributes` + +```swift +extension Logger { + /// Attributes that can be associated with metadata values. + /// + /// `MetadataValueAttributes` stores one attribute inline without heap allocation. When more than one attribute + /// is needed, additional attributes spill over to a heap-allocated array. + /// Use the generic subscript to get/set attributes by their ``Attribute`` type. + public struct MetadataValueAttributes: Sendable, Equatable, ExpressibleByArrayLiteral { + /// Nested ``Attribute`` protocol (see above). + public protocol Attribute: Sendable, RawRepresentable where RawValue == Int64 {} + + /// Create empty metadata value attributes. + public init() + + /// Create metadata value attributes from an array literal of attribute values. + /// + /// ```swift + /// let attrs: MetadataValueAttributes = [Sensitivity.sensitive, ValueType.int64] + /// ``` + public init(arrayLiteral elements: any Attribute...) + + /// Get or set a custom attribute by its type. + /// + /// - Parameter attribute: The metatype of the attribute to access. + /// - Returns: The attribute value, or `nil` if not set. + public subscript(attribute: Attr.Type) -> Attr? { get set } + } +} +``` + +The common case (0–1 attributes) avoids heap allocation. `Equatable` compares entries as an unordered set (O(n²), +n typically 0–2). + +#### `MetadataValue.attributes` computed property + +```swift +extension Logger.MetadataValue { + /// The attributes associated with this metadata value, if any. + /// + /// **Getting:** When the value is a ``stringConvertible(_:)`` wrapping an attributed carrier, + /// returns that carrier's attributes. For all other cases returns empty attributes. + /// + /// **Setting:** Replaces the value with `.stringConvertible(AttributedStringCarrier(...))` + /// carrying the given attributes. For `.string` and `.stringConvertible` cases the string + /// representation is preserved. For `.dictionary` and `.array` cases the setter is a no-op. + public var attributes: Logger.MetadataValueAttributes { get set } +} +``` + +This is the handler-side read/write API. Internally, the `Logging` module stores attributes in an internal +`AttributedStringCarrier` class wrapped by `.stringConvertible`. The getter check is a concrete type comparison — no +protocol conformance lookup. Users attach attributes via string interpolation and read them via this property. The +setter allows handlers to modify or add attributes as they process metadata values through the handler chain. + +#### `MetadataValue.attributed` factory method + +```swift +extension Logger.MetadataValue { + /// Creates an attributed metadata value from a string-convertible value and attributes. + public static func attributed( + _ value: some CustomStringConvertible & Sendable, + attributes: Logger.MetadataValueAttributes + ) -> Self +} +``` + +This convenience factory behaves like an additional enum case, producing a +`.stringConvertible(AttributedStringCarrier(...))` value without requiring string interpolation: + +```swift +let value: Logger.MetadataValue = .attributed(userId, attributes: [Sensitivity.sensitive]) +``` + +#### String interpolation + +`MetadataValue` replaces its empty `ExpressibleByStringInterpolation` conformance with a custom `StringInterpolation` +type. When no attributes are specified, the result is `.string(...)` — identical to the previous behavior. When any +interpolation segment specifies attributes, the result is `.stringConvertible(...)` wrapping the internal carrier: +```swift +extension Logger.MetadataValue: ExpressibleByStringInterpolation { + /// Custom string interpolation that optionally captures metadata attributes. + /// + /// When no attributes are specified, produces `.string(...)` — identical to the + /// default `DefaultStringInterpolation` behavior. When any interpolation segment + /// specifies attributes (via the `attributes:` parameter), the result is + /// `.stringConvertible(AttributedStringCarrier(...))` carrying both the string + /// and the accumulated attributes. + /// + /// Attribute packages (like `LoggingAttributes`) can add overloads with + /// domain-specific parameters (e.g. `sensitivity:`) that call through to + /// `appendInterpolation(_:attributes:)`. + public struct StringInterpolation: StringInterpolationProtocol, Sendable { + public init(literalCapacity: Int, interpolationCount: Int) + public mutating func appendLiteral(_ literal: String) + + /// Interpolation with a custom attributes closure. + /// + /// When called, the result will be `.stringConvertible(AttributedStringCarrier(...))` + /// instead of `.string(...)`. + /// + /// ```swift + /// "\(userId, attributes: { $0[MyAttribute.self] = .flagged })" + /// ``` + public mutating func appendInterpolation( + _ value: T, + attributes: @Sendable (inout Logger.MetadataValueAttributes) -> Void + ) where T: CustomStringConvertible & Sendable + + /// Plain interpolation without attributes. + public mutating func appendInterpolation( + _ value: T + ) where T: CustomStringConvertible & Sendable + + /// Fallback interpolation for types that are not `CustomStringConvertible`. + public mutating func appendInterpolation( + _ value: T + ) where T: Sendable + + /// Unconstrained fallback for non-`Sendable` types. + /// + /// The value is immediately converted to `String` via `String(describing:)` and never + /// stored, so no `Sendable` safety issue arises. This overload exists so that interpolating + /// a non-`Sendable` type into a `MetadataValue` continues to compile, matching the behavior + /// of `DefaultStringInterpolation`. + public mutating func appendInterpolation( + _ value: T + ) + } + + /// Creates a metadata value from string interpolation. + /// + /// If any interpolation segment specified attributes, the result is + /// `.stringConvertible(AttributedStringCarrier(...))`. Otherwise, `.string(...)`. + public init(stringInterpolation: StringInterpolation) +} +``` + +Attribute packages add ergonomic overloads that wrap the closure-based method — for example: + +```swift +extension Logger.MetadataValue.StringInterpolation { + public mutating func appendInterpolation( + _ value: T, sensitivity: Sensitivity + ) { + self.appendInterpolation(value, attributes: { $0[Sensitivity.self] = sensitivity }) + } +} +``` + +This enables the clean call-site syntax: `"\(userId, sensitivity: .sensitive)"`. + +When a single `MetadataValue` contains multiple interpolated segments with different attributes, the merging behavior +is defined by each attribute's `appendInterpolation` implementation. + +#### No changes to `Logger`, `LogHandler`, `LogEvent`, or `MetadataProvider` + +Unlike earlier iterations of this proposal, the piggyback approach requires **no new API** on `Logger`, `LogHandler`, +`LogEvent`, or `MetadataProvider`: + +- **`Logger`**: No new `attributedMetadata:` log method overloads. Attributes flow through the existing `metadata:` + parameter. +- **`LogHandler`**: No new protocol requirements. No `attributedMetadata` property, no `attributedMetadataKey` + subscript. Existing handlers work unchanged. +- **`LogEvent`**: No dual storage. `metadata` remains a simple `Logger.Metadata?` stored property. Values inside the + dictionary may carry attributes, but `LogEvent` is unaware of this. +- **`MetadataProvider`**: No `.attributed()` factory or `getAttributedMetadata()` method. Providers return + `Logger.Metadata` where values may carry attributes via string interpolation. + +### API stability + +- **Existing `Logger` users.** No changes to existing API. The same `metadata:` parameter carries attributed values. +- **Existing `LogHandler` implementations.** No protocol changes. Handlers that only call `.description` on metadata + values see the string as before — attributes are invisible. Handlers that want to inspect attributes read + `value.attributes`. + +### Future directions + +- **Attribute-aware equality.** The current `MetadataValue` equality for `.stringConvertible` values compares only + `.description`, ignoring attributes. Two values with the same text but different attributes compare as equal. A + future proposal could refine equality to include attributes when both sides carry them, but this + requires careful consideration of backward compatibility since existing code may rely on description-only equality. +- **Metadata values sensitivity attribute.** A separate ecosystem package could add the sensitivity attribute, + allowing compatible `LogHandler` to redact values in certain situations. +- **Typed metadata values.** A separate ecosystem package could add typed variants to `MetadataValue` (`.int64`, + `.double`, `.bool`), reducing the need for attributes that compensate for stringly-typed metadata. + +### Alternatives considered + +#### Wrapper type with parallel API ("attributed metadata value" approach) + +Introduce an `AttributedMetadataValue` struct wrapping `MetadataValue` + `MetadataValueAttributes`, a separate +`AttributedMetadata` typealias, new `attributedMetadata:` overloads on all Logger methods, dual storage in +`LogEvent`, and new `LogHandler` protocol requirements. This was the design in the first iteration of this proposal. + +It provides strong type separation but creates a parallel API surface: 7 new convenience methods, new protocol +requirements with default implementations, dual `MetadataStorage` enum in `LogEvent`, and `mapValues` bridging +between plain and attributed representations. The piggyback approach achieves the same functionality by embedding +attributes inside `MetadataValue` via the existing `.stringConvertible` case, avoiding the parallel universe +entirely. + +#### Sidecar dictionary on `LogEvent` + +Store attributes in a separate `[String: MetadataValueAttributes]` dictionary on `LogEvent`, keyed by the same +metadata keys. This keeps `MetadataValue` unchanged but introduces sync issues — attributes can drift out of sync +with metadata keys when handlers merge or transform metadata. The piggyback approach avoids this by co-locating +attributes with the value they describe. + +#### New enum case on `MetadataValue` + +Add a dedicated `.attributed(String, MetadataValueAttributes)` case to the `MetadataValue` enum. This would make +attributes statically visible in the type — no runtime downcast needed, and `switch` statements would handle +attributed values explicitly. However, `MetadataValue` is a public enum that is exhaustively matched by every +`LogHandler` in the ecosystem. Adding a case is source-breaking: every existing handler's `switch` over +`MetadataValue` would fail to compile until updated. The piggyback approach avoids this by reusing the existing +`.stringConvertible` case, which handlers already handle. + +#### Concrete stored property instead of extensible mechanism + +Add concrete stored properties (e.g., `var sensitivity: Sensitivity?`) on `MetadataValueAttributes`. Simpler, but +closed — chained handlers cannot define their own attributes. The extensible mechanism keeps the core `Logging` module +free of domain-specific attributes. + +#### Bitmask storage + +Pack attribute values into an inline `UInt64` using declared bit offsets. O(1) access, but requires authors to +coordinate bit layout and risks collisions between independent packages. + +#### Pure dynamic array storage + +Use a dynamic array for all attributes with no inline slot. Simpler, but requires heap allocation even for the first +attribute. + +#### No per-value attributes + +Rely on handler-side configuration (key-name-based rules). Simpler, but fragile — rules break when keys are renamed, +require coordination across all dependencies, and are invisible at the call site. + +### Example attributes + +The following examples illustrate how ecosystem packages could define attributes using the +`Logger.MetadataValueAttributes.Attribute` protocol. These are not part of this proposal. + +#### Sensitivity + +A sensitivity attribute for marking metadata values that contain private or personally identifiable information: + +```swift +public enum Sensitivity: Int64, Logger.MetadataValueAttributes.Attribute, Sendable { + case sensitive = 1 + case `public` = 2 +} + +extension Logger.MetadataValue.StringInterpolation { + public mutating func appendInterpolation( + _ value: T, sensitivity: Sensitivity + ) { + self.appendInterpolation(value, attributes: { $0[Sensitivity.self] = sensitivity }) + } +} + +logger.info("Request", metadata: [ + "method": "\(req.method)", + "user_id": "\(req.userId, sensitivity: .sensitive)", +]) +``` + +A handler reads the attribute: + +```swift +for (key, value) in mergedMetadata { + if value.attributes[Sensitivity.self] == .sensitive { + // redact this value + } +} +``` + +#### Value type hint + +A type hint for structured logging backends that benefit from native types: + +```swift +public enum ValueType: Int64, Logger.MetadataValueAttributes.Attribute, Sendable { + case string = 1 + case int64 = 2 + case double = 3 + case bool = 4 +} + +extension Logger.MetadataValue.StringInterpolation { + public mutating func appendInterpolation( + _ value: T, valueType: ValueType + ) { + self.appendInterpolation(value, attributes: { $0[ValueType.self] = valueType }) + } +} + +logger.info("Metrics", metadata: [ + "latency_ms": "\(latency, valueType: .double)", + "retry_count": "\(retries, valueType: .int64)", +]) +``` + +#### Metric extraction + +A metric attribute for a chained `LogHandler` that dual-writes to swift-metrics: + +```swift +public enum MetricKind: Int64, Logger.MetadataValueAttributes.Attribute, Sendable { + case counter = 1 + case gauge = 2 + case histogram = 3 +} + +extension Logger.MetadataValue.StringInterpolation { + public mutating func appendInterpolation( + _ value: T, metricKind: MetricKind + ) { + self.appendInterpolation(value, attributes: { $0[MetricKind.self] = metricKind }) + } +} + +logger.info("Request completed", metadata: [ + "duration_ms": "\(duration, metricKind: .histogram)", + "error_count": "\(errors, metricKind: .counter)", +]) +``` + +#### Attribute-enriching intermediate handler + +An intermediate `LogHandler` that reads and modifies attributes before forwarding to the next handler in the chain. +This pattern enables composable pipelines — for example, a handler that adds a default sensitivity to all metadata +values that do not already carry one: + +```swift +struct DefaultSensitivityHandler: LogHandler { + private var inner: any LogHandler + + // ... logLevel, metadata, metadataProvider forwarded to inner ... + + func log(event: LogEvent) { + var mutatedEvent = event + if var eventMetadata = event.metadata { + for (key, _) in eventMetadata { + if eventMetadata[key]?.attributes[Sensitivity.self] == nil { + eventMetadata[key]?.attributes = [Sensitivity.sensitive] + } + } + mutatedEvent.metadata = eventMetadata + } + self.inner.log(event: mutatedEvent) + } +} +``` + +With this handler in the chain, any metadata value without an explicit sensitivity annotation is treated as sensitive +by default — a "deny by default" policy that individual call sites can override with `.public`. diff --git a/Sources/Logging/Docs.docc/Proposals/SLG-0004-metadata-values-privacy-attributes.md b/Sources/Logging/Docs.docc/Proposals/SLG-0004-metadata-values-privacy-attributes.md deleted file mode 100644 index 9143e09..0000000 --- a/Sources/Logging/Docs.docc/Proposals/SLG-0004-metadata-values-privacy-attributes.md +++ /dev/null @@ -1,467 +0,0 @@ -# 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 = "" - - 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(_ 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 `""`. - /// - /// ### 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.