From 7dc6101ae4dbe95cd3bc9cebad3b7cf8e49a7a63 Mon Sep 17 00:00:00 2001 From: Vladimir Kukushkin Date: Fri, 22 May 2026 16:06:57 +0100 Subject: [PATCH] [SLG-0004]: metadata value attributes implementation (#453) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Proposal discussion thread: https://forums.swift.org/t/proposal-slg-0004-metadata-value-attributes-revision-2/86488 Add an extensible per-value attribute mechanism for metadata. ### Motivation: Metadata values in `swift-log` are opaque strings by the time the `LogHandler` receives them. The call site often knows things about a value that the handler cannot infer — for example, whether the value should be redacted in different environments. ### Modifications: - SLG-0004 proposal is updated based on the feedback. - Added `AttributedStringCarrier: CustomStringConvertible`-based mechanism to `Logging`. - Added benchmarks and benchmark thresholds for the new attributed metadata. ### Result: `swift-log` provides an optional extensible mechanism for attaching attributes to metadata values. --------- Co-authored-by: Franz Busch --- ..._with_error_log_level_1_attribute.p90.json | 4 + ...with_error_log_level_2_attributes.p90.json | 4 + ..._with_error_log_level_1_attribute.p90.json | 4 + ...with_error_log_level_2_attributes.p90.json | 4 + .../MaxLogLevelWarning.swift | 10 + ....notice_log_with_notice_log_level.p90.json | 2 +- ...tice_log_level_attributed_generic.p90.json | 4 + ...arning_log_with_warning_log_level.p90.json | 2 +- ...og_with_warning_log_level_generic.p90.json | 2 +- .../NoTraitsBenchmarks/NoTraits.swift | 36 ++ ..._with_error_log_level_1_attribute.p90.json | 4 + ...with_error_log_level_2_attributes.p90.json | 4 + ..._with_error_log_level_1_attribute.p90.json | 4 + ...with_error_log_level_2_attributes.p90.json | 4 + ..._log_with_error_log_level_generic.p90.json | 2 +- .../BenchmarksFactory/NoOpLogHandler.swift | 48 ++ .../InMemoryLogging/InMemoryLogHandler.swift | 34 +- .../DisableLogLevelsDuringCompilation.md | 8 +- .../Docs.docc/ImplementingALogHandler.md | 46 +- .../SLG-0004-metadata-value-attributes.md | 23 +- .../Logging/Docs.docc/Reference/LogEvent.md | 12 + .../Reference/Logger-MetadataProvider.md | 2 +- Sources/Logging/Docs.docc/Reference/Logger.md | 4 + .../Reference/SwiftLogNoOpLogHandler.md | 2 + Sources/Logging/Docs.docc/index.md | 2 +- Sources/Logging/LogEvent.swift | 11 +- Sources/Logging/Logger+Attributes.swift | 432 +++++++++++++++++ Sources/Logging/Logger.swift | 25 +- Sources/Logging/MetadataProvider.swift | 27 +- .../InMemoryLogHandlerTests.swift | 107 +++-- Tests/LoggingTests/LogEventTest.swift | 59 +++ Tests/LoggingTests/LoggingTest.swift | 72 +++ .../LoggingTests/MetadataAttributesTest.swift | 443 ++++++++++++++++++ 33 files changed, 1346 insertions(+), 101 deletions(-) create mode 100644 Benchmarks/MaxLogLevelNone/Thresholds/Xcode swift 6.3/NoTraits.debug_log_with_error_log_level_1_attribute.p90.json create mode 100644 Benchmarks/MaxLogLevelNone/Thresholds/Xcode swift 6.3/NoTraits.debug_log_with_error_log_level_2_attributes.p90.json create mode 100644 Benchmarks/MaxLogLevelNone/Thresholds/Xcode swift 6.3/NoTraits.error_log_with_error_log_level_1_attribute.p90.json create mode 100644 Benchmarks/MaxLogLevelNone/Thresholds/Xcode swift 6.3/NoTraits.error_log_with_error_log_level_2_attributes.p90.json create mode 100644 Benchmarks/MaxLogLevelWarning/Thresholds/Xcode swift 6.3/MaxLogLevelWarning.notice_log_with_notice_log_level_attributed_generic.p90.json create mode 100644 Benchmarks/NoTraits/Thresholds/Xcode swift 6.3/NoTraits.debug_log_with_error_log_level_1_attribute.p90.json create mode 100644 Benchmarks/NoTraits/Thresholds/Xcode swift 6.3/NoTraits.debug_log_with_error_log_level_2_attributes.p90.json create mode 100644 Benchmarks/NoTraits/Thresholds/Xcode swift 6.3/NoTraits.error_log_with_error_log_level_1_attribute.p90.json create mode 100644 Benchmarks/NoTraits/Thresholds/Xcode swift 6.3/NoTraits.error_log_with_error_log_level_2_attributes.p90.json create mode 100644 Sources/Logging/Logger+Attributes.swift create mode 100644 Tests/LoggingTests/MetadataAttributesTest.swift diff --git a/Benchmarks/MaxLogLevelNone/Thresholds/Xcode swift 6.3/NoTraits.debug_log_with_error_log_level_1_attribute.p90.json b/Benchmarks/MaxLogLevelNone/Thresholds/Xcode swift 6.3/NoTraits.debug_log_with_error_log_level_1_attribute.p90.json new file mode 100644 index 0000000..4f8896e --- /dev/null +++ b/Benchmarks/MaxLogLevelNone/Thresholds/Xcode swift 6.3/NoTraits.debug_log_with_error_log_level_1_attribute.p90.json @@ -0,0 +1,4 @@ +{ + "instructions" : 970, + "objectAllocCount" : 0 +} \ No newline at end of file diff --git a/Benchmarks/MaxLogLevelNone/Thresholds/Xcode swift 6.3/NoTraits.debug_log_with_error_log_level_2_attributes.p90.json b/Benchmarks/MaxLogLevelNone/Thresholds/Xcode swift 6.3/NoTraits.debug_log_with_error_log_level_2_attributes.p90.json new file mode 100644 index 0000000..4f8896e --- /dev/null +++ b/Benchmarks/MaxLogLevelNone/Thresholds/Xcode swift 6.3/NoTraits.debug_log_with_error_log_level_2_attributes.p90.json @@ -0,0 +1,4 @@ +{ + "instructions" : 970, + "objectAllocCount" : 0 +} \ No newline at end of file diff --git a/Benchmarks/MaxLogLevelNone/Thresholds/Xcode swift 6.3/NoTraits.error_log_with_error_log_level_1_attribute.p90.json b/Benchmarks/MaxLogLevelNone/Thresholds/Xcode swift 6.3/NoTraits.error_log_with_error_log_level_1_attribute.p90.json new file mode 100644 index 0000000..d5bce0c --- /dev/null +++ b/Benchmarks/MaxLogLevelNone/Thresholds/Xcode swift 6.3/NoTraits.error_log_with_error_log_level_1_attribute.p90.json @@ -0,0 +1,4 @@ +{ + "instructions" : 5851, + "objectAllocCount" : 2 +} \ No newline at end of file diff --git a/Benchmarks/MaxLogLevelNone/Thresholds/Xcode swift 6.3/NoTraits.error_log_with_error_log_level_2_attributes.p90.json b/Benchmarks/MaxLogLevelNone/Thresholds/Xcode swift 6.3/NoTraits.error_log_with_error_log_level_2_attributes.p90.json new file mode 100644 index 0000000..cde2d24 --- /dev/null +++ b/Benchmarks/MaxLogLevelNone/Thresholds/Xcode swift 6.3/NoTraits.error_log_with_error_log_level_2_attributes.p90.json @@ -0,0 +1,4 @@ +{ + "instructions" : 7055, + "objectAllocCount" : 3 +} \ No newline at end of file diff --git a/Benchmarks/MaxLogLevelWarning/Benchmarks/MaxLogLevelWarningBenchmarks/MaxLogLevelWarning.swift b/Benchmarks/MaxLogLevelWarning/Benchmarks/MaxLogLevelWarningBenchmarks/MaxLogLevelWarning.swift index 2719bfc..fc8cd67 100644 --- a/Benchmarks/MaxLogLevelWarning/Benchmarks/MaxLogLevelWarningBenchmarks/MaxLogLevelWarning.swift +++ b/Benchmarks/MaxLogLevelWarning/Benchmarks/MaxLogLevelWarningBenchmarks/MaxLogLevelWarning.swift @@ -30,4 +30,14 @@ public let benchmarks: @Sendable () -> Void = { makeBenchmark(loggerLevel: .warning, logLevel: .warning, "_generic") { logger in logger.log(level: .warning, "hello, benchmarking world") } + makeBenchmark(loggerLevel: .notice, logLevel: .notice, "_attributed_generic") { logger in + logger.log( + level: .notice, + "hello, benchmarking world", + metadata: [ + "public-key": "\("public-value", sensitivity: .public)", + "private-key": "\("private-value", sensitivity: .sensitive)", + ] + ) + } } diff --git a/Benchmarks/MaxLogLevelWarning/Thresholds/Xcode swift 6.3/MaxLogLevelWarning.notice_log_with_notice_log_level.p90.json b/Benchmarks/MaxLogLevelWarning/Thresholds/Xcode swift 6.3/MaxLogLevelWarning.notice_log_with_notice_log_level.p90.json index 53f3d5f..7829706 100644 --- a/Benchmarks/MaxLogLevelWarning/Thresholds/Xcode swift 6.3/MaxLogLevelWarning.notice_log_with_notice_log_level.p90.json +++ b/Benchmarks/MaxLogLevelWarning/Thresholds/Xcode swift 6.3/MaxLogLevelWarning.notice_log_with_notice_log_level.p90.json @@ -1,4 +1,4 @@ { - "instructions" : 658, + "instructions" : 662, "objectAllocCount" : 0 } \ No newline at end of file diff --git a/Benchmarks/MaxLogLevelWarning/Thresholds/Xcode swift 6.3/MaxLogLevelWarning.notice_log_with_notice_log_level_attributed_generic.p90.json b/Benchmarks/MaxLogLevelWarning/Thresholds/Xcode swift 6.3/MaxLogLevelWarning.notice_log_with_notice_log_level_attributed_generic.p90.json new file mode 100644 index 0000000..7829706 --- /dev/null +++ b/Benchmarks/MaxLogLevelWarning/Thresholds/Xcode swift 6.3/MaxLogLevelWarning.notice_log_with_notice_log_level_attributed_generic.p90.json @@ -0,0 +1,4 @@ +{ + "instructions" : 662, + "objectAllocCount" : 0 +} \ No newline at end of file diff --git a/Benchmarks/MaxLogLevelWarning/Thresholds/Xcode swift 6.3/MaxLogLevelWarning.warning_log_with_warning_log_level.p90.json b/Benchmarks/MaxLogLevelWarning/Thresholds/Xcode swift 6.3/MaxLogLevelWarning.warning_log_with_warning_log_level.p90.json index 6ca38aa..b033268 100644 --- a/Benchmarks/MaxLogLevelWarning/Thresholds/Xcode swift 6.3/MaxLogLevelWarning.warning_log_with_warning_log_level.p90.json +++ b/Benchmarks/MaxLogLevelWarning/Thresholds/Xcode swift 6.3/MaxLogLevelWarning.warning_log_with_warning_log_level.p90.json @@ -1,4 +1,4 @@ { - "instructions" : 1874, + "instructions" : 1892, "objectAllocCount" : 0 } \ No newline at end of file diff --git a/Benchmarks/MaxLogLevelWarning/Thresholds/Xcode swift 6.3/MaxLogLevelWarning.warning_log_with_warning_log_level_generic.p90.json b/Benchmarks/MaxLogLevelWarning/Thresholds/Xcode swift 6.3/MaxLogLevelWarning.warning_log_with_warning_log_level_generic.p90.json index 6ca38aa..b033268 100644 --- a/Benchmarks/MaxLogLevelWarning/Thresholds/Xcode swift 6.3/MaxLogLevelWarning.warning_log_with_warning_log_level_generic.p90.json +++ b/Benchmarks/MaxLogLevelWarning/Thresholds/Xcode swift 6.3/MaxLogLevelWarning.warning_log_with_warning_log_level_generic.p90.json @@ -1,4 +1,4 @@ { - "instructions" : 1874, + "instructions" : 1892, "objectAllocCount" : 0 } \ No newline at end of file diff --git a/Benchmarks/NoTraits/Benchmarks/NoTraitsBenchmarks/NoTraits.swift b/Benchmarks/NoTraits/Benchmarks/NoTraitsBenchmarks/NoTraits.swift index b7d94ce..621c5bb 100644 --- a/Benchmarks/NoTraits/Benchmarks/NoTraitsBenchmarks/NoTraits.swift +++ b/Benchmarks/NoTraits/Benchmarks/NoTraitsBenchmarks/NoTraits.swift @@ -24,4 +24,40 @@ public let benchmarks: @Sendable () -> Void = { makeBenchmark(loggerLevel: .error, logLevel: .debug, "_generic") { logger in logger.log(level: .debug, "hello, benchmarking world") } + makeBenchmark(loggerLevel: .error, logLevel: .error, "_1_attribute") { logger in + logger.log( + level: .error, + "hello, benchmarking world", + metadata: [ + "public-key": "\("public-value", sensitivity: .public)" + ] + ) + } + makeBenchmark(loggerLevel: .error, logLevel: .debug, "_1_attribute") { logger in + logger.log( + level: .debug, + "hello, benchmarking world", + metadata: [ + "public-key": "\("public-value", sensitivity: .public)" + ] + ) + } + makeBenchmark(loggerLevel: .error, logLevel: .error, "_2_attributes") { logger in + logger.log( + level: .error, + "hello, benchmarking world", + metadata: [ + "public-key": "\("public-value", attributes: [BenchmarkSensitivity.public, BenchmarkColor.red])" + ] + ) + } + makeBenchmark(loggerLevel: .error, logLevel: .debug, "_2_attributes") { logger in + logger.log( + level: .debug, + "hello, benchmarking world", + metadata: [ + "public-key": "\("public-value", attributes: [BenchmarkSensitivity.public, BenchmarkColor.red])" + ] + ) + } } diff --git a/Benchmarks/NoTraits/Thresholds/Xcode swift 6.3/NoTraits.debug_log_with_error_log_level_1_attribute.p90.json b/Benchmarks/NoTraits/Thresholds/Xcode swift 6.3/NoTraits.debug_log_with_error_log_level_1_attribute.p90.json new file mode 100644 index 0000000..957dc64 --- /dev/null +++ b/Benchmarks/NoTraits/Thresholds/Xcode swift 6.3/NoTraits.debug_log_with_error_log_level_1_attribute.p90.json @@ -0,0 +1,4 @@ +{ + "instructions" : 985, + "objectAllocCount" : 0 +} \ No newline at end of file diff --git a/Benchmarks/NoTraits/Thresholds/Xcode swift 6.3/NoTraits.debug_log_with_error_log_level_2_attributes.p90.json b/Benchmarks/NoTraits/Thresholds/Xcode swift 6.3/NoTraits.debug_log_with_error_log_level_2_attributes.p90.json new file mode 100644 index 0000000..957dc64 --- /dev/null +++ b/Benchmarks/NoTraits/Thresholds/Xcode swift 6.3/NoTraits.debug_log_with_error_log_level_2_attributes.p90.json @@ -0,0 +1,4 @@ +{ + "instructions" : 985, + "objectAllocCount" : 0 +} \ No newline at end of file diff --git a/Benchmarks/NoTraits/Thresholds/Xcode swift 6.3/NoTraits.error_log_with_error_log_level_1_attribute.p90.json b/Benchmarks/NoTraits/Thresholds/Xcode swift 6.3/NoTraits.error_log_with_error_log_level_1_attribute.p90.json new file mode 100644 index 0000000..ede7d2b --- /dev/null +++ b/Benchmarks/NoTraits/Thresholds/Xcode swift 6.3/NoTraits.error_log_with_error_log_level_1_attribute.p90.json @@ -0,0 +1,4 @@ +{ + "instructions" : 5855, + "objectAllocCount" : 2 +} \ No newline at end of file diff --git a/Benchmarks/NoTraits/Thresholds/Xcode swift 6.3/NoTraits.error_log_with_error_log_level_2_attributes.p90.json b/Benchmarks/NoTraits/Thresholds/Xcode swift 6.3/NoTraits.error_log_with_error_log_level_2_attributes.p90.json new file mode 100644 index 0000000..f53cae1 --- /dev/null +++ b/Benchmarks/NoTraits/Thresholds/Xcode swift 6.3/NoTraits.error_log_with_error_log_level_2_attributes.p90.json @@ -0,0 +1,4 @@ +{ + "instructions" : 7075, + "objectAllocCount" : 3 +} \ No newline at end of file diff --git a/Benchmarks/NoTraits/Thresholds/Xcode swift 6.3/NoTraits.error_log_with_error_log_level_generic.p90.json b/Benchmarks/NoTraits/Thresholds/Xcode swift 6.3/NoTraits.error_log_with_error_log_level_generic.p90.json index a8fa643..15f67a1 100644 --- a/Benchmarks/NoTraits/Thresholds/Xcode swift 6.3/NoTraits.error_log_with_error_log_level_generic.p90.json +++ b/Benchmarks/NoTraits/Thresholds/Xcode swift 6.3/NoTraits.error_log_with_error_log_level_generic.p90.json @@ -1,4 +1,4 @@ { - "instructions" : 1872, + "instructions" : 1890, "objectAllocCount" : 0 } \ No newline at end of file diff --git a/Benchmarks/Sources/BenchmarksFactory/NoOpLogHandler.swift b/Benchmarks/Sources/BenchmarksFactory/NoOpLogHandler.swift index 272634f..c870e4f 100644 --- a/Benchmarks/Sources/BenchmarksFactory/NoOpLogHandler.swift +++ b/Benchmarks/Sources/BenchmarksFactory/NoOpLogHandler.swift @@ -14,6 +14,40 @@ import Logging +// MARK: - Benchmark attributes + +public enum BenchmarkSensitivity: Int64, Logger.MetadataValueAttributes.Attribute, Sendable { + case sensitive = 1 + case `public` = 2 +} + +extension Logger.MetadataValue.StringInterpolation { + @inlinable + public mutating func appendInterpolation( + _ value: T, + sensitivity: BenchmarkSensitivity + ) { + self.appendInterpolation(value, attributes: { $0[BenchmarkSensitivity.self] = sensitivity }) + } +} + +public enum BenchmarkColor: Int64, Logger.MetadataValueAttributes.Attribute, Sendable { + case red = 1 + case blue = 2 +} + +extension Logger.MetadataValue.StringInterpolation { + @inlinable + public mutating func appendInterpolation( + _ value: T, + color: BenchmarkColor + ) { + self.appendInterpolation(value, attributes: { $0[BenchmarkColor.self] = color }) + } +} + +// MARK: - NoOpLogHandler + struct NoOpLogHandler: LogHandler { let label: String public var metadataProvider: Logger.MetadataProvider? @@ -31,6 +65,13 @@ struct NoOpLogHandler: LogHandler { func log( event: LogEvent ) { + // Access metadata attributes + if let metadata = event.metadata { + for (_, value) in metadata { + let _ = value.attributes + } + } + // Do nothing } @@ -43,6 +84,13 @@ struct NoOpLogHandler: LogHandler { function: String, line: UInt ) { + // Access metadata attributes + if let metadata = explicitMetadata { + for (_, value) in metadata { + let _ = value.attributes + } + } + // Do nothing } diff --git a/Sources/InMemoryLogging/InMemoryLogHandler.swift b/Sources/InMemoryLogging/InMemoryLogHandler.swift index f863489..af1b599 100644 --- a/Sources/InMemoryLogging/InMemoryLogHandler.swift +++ b/Sources/InMemoryLogging/InMemoryLogHandler.swift @@ -57,18 +57,23 @@ public struct InMemoryLogHandler: LogHandler { self.metadata = metadata } - public init(level: Logger.Level, message: Logger.Message, error: (any Error)?, metadata: Logger.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 { + public static func == (lhs: Entry, rhs: Entry) -> Bool { lhs.level == rhs.level && lhs.message == rhs.message - && errorsEqual(lhs.error, rhs.error) && lhs.metadata == rhs.metadata + && errorsEqual(lhs.error, rhs.error) } private static func errorsEqual(_ lhs: (any Error)?, _ rhs: (any Error)?) -> Bool { @@ -126,14 +131,23 @@ public struct InMemoryLogHandler: LogHandler { } public func log(event: LogEvent) { - // Start with the metadata provider.. - var mergedMetadata: Logger.Metadata = self.metadataProvider?.get() ?? [:] - // ..merge in self.metadata, overwriting existing keys - mergedMetadata = mergedMetadata.merging(self.metadata) { $1 } - // ..merge in metadata from this log call, overwriting existing keys - mergedMetadata = mergedMetadata.merging(event.metadata ?? [:]) { $1 } + var merged = self.metadata - self.logStore.append(level: event.level, message: event.message, error: event.error, metadata: mergedMetadata) + if let provider = self.metadataProvider { + let provided = provider.get() + merged.merge(provided, uniquingKeysWith: { _, rhs in rhs }) + } + + if let eventMetadata = event.metadata { + merged.merge(eventMetadata, uniquingKeysWith: { _, rhs in rhs }) + } + + self.logStore.append( + level: event.level, + message: event.message, + error: event.error, + metadata: merged + ) } @available(*, deprecated, renamed: "log(event:)") diff --git a/Sources/Logging/Docs.docc/DisableLogLevelsDuringCompilation.md b/Sources/Logging/Docs.docc/DisableLogLevelsDuringCompilation.md index ab2abce..4876fa2 100644 --- a/Sources/Logging/Docs.docc/DisableLogLevelsDuringCompilation.md +++ b/Sources/Logging/Docs.docc/DisableLogLevelsDuringCompilation.md @@ -3,7 +3,9 @@ SwiftLog provides compile-time traits to eliminate less severe log levels from your binary reducing the runtime overhead. -## Motivation +## Overview + +### Motivation When deploying applications to production, you often know in advance which log levels will never be needed. For example, a production service might only need @@ -11,7 +13,7 @@ warning and above, while trace and debug levels are only useful during development. By using traits, you can completely remove these unnecessary log levels at compile time, achieving zero runtime overhead. -## Available traits +### Available traits SwiftLog defines seven maximum log level traits, ordered from most permissive to most restrictive: @@ -39,7 +41,7 @@ are specified, the most restrictive one takes effect. > Note: Traits should only be set by the applications and not libraries as > any traits defined in a transitive dependency will affect the whole resolution tree. -## Example +### Example To enable a trait, specify it when declaring your package dependency: diff --git a/Sources/Logging/Docs.docc/ImplementingALogHandler.md b/Sources/Logging/Docs.docc/ImplementingALogHandler.md index 3ede87a..d9853ca 100644 --- a/Sources/Logging/Docs.docc/ImplementingALogHandler.md +++ b/Sources/Logging/Docs.docc/ImplementingALogHandler.md @@ -129,9 +129,6 @@ public struct PrintLogHandler: LogHandler { let timestamp = ISO8601DateFormatter().string(from: Date()) let levelString = event.level.rawValue.uppercased() - // Get provider metadata - let providerMetadata = metadataProvider?.get() ?? [:] - // Merge handler metadata with message metadata let combinedMetadata = Self.prepareMetadata( base: self.metadata, @@ -183,6 +180,49 @@ public struct PrintLogHandler: LogHandler { } ``` +#### Reading metadata attributes in LogHandlers + +Metadata values can carry attributes alongside their string representation. Attributes are embedded inside +`MetadataValue` via the `.stringConvertible` case and are accessible through the `value.attributes` property. This +enables features like sensitivity annotations without any changes to your handler's protocol conformance. + +To read attributes in your log handler: + +```swift +public func log(event: LogEvent) { + // Merge handler metadata, provider metadata, and event metadata as usual + var merged = self.metadata + + if let provider = self.metadataProvider { + merged.merge(provider.get(), uniquingKeysWith: { _, rhs in rhs }) + } + + if let eventMetadata = event.metadata { + merged.merge(eventMetadata, uniquingKeysWith: { _, rhs in rhs }) + } + + // Read attributes from individual values: + for (key, value) in merged { + let attributes = value.attributes // Empty if the value carries no attributes + + // Process based on your handler's needs + // For example, check for a custom attribute: + // if attributes[MyAttribute.self] == .flagged { ... } + } +} +``` + +**Key considerations:** + +- **Opt-in inspection**: Attributes are invisible unless you call `value.attributes`. Handlers that do not care about + attributes work without any changes. + +- **No new protocol requirements**: Reading attributes does not require implementing any new `LogHandler` properties + or subscripts. The `metadata` property and `metadataKey` subscript work exactly as before. + +- **Attributes flow through metadata**: Attributed values flow naturally through metadata merging, `MetadataProvider`, + and `MultiplexLogHandler` — no special handling needed. + ### Performance considerations 1. **Avoid blocking**: Don't block the calling thread for I/O operations. 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 index 87abd72..99c69cc 100644 --- a/Sources/Logging/Docs.docc/Proposals/SLG-0004-metadata-value-attributes.md +++ b/Sources/Logging/Docs.docc/Proposals/SLG-0004-metadata-value-attributes.md @@ -125,13 +125,11 @@ extension Logger.MetadataValueAttributes { /// ``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 + /// This protocol is designed for **small, fixed-vocabulary attributes**. + /// 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 + /// ## Examples /// /// ```swift /// public enum Priority: Int64, Sendable, Logger.MetadataValueAttributes.Attribute { @@ -139,6 +137,17 @@ extension Logger.MetadataValueAttributes { /// case high = 2 /// } /// ``` + /// + /// ```swift + /// public struct Priority: Sendable, Hashable, Logger.MetadataValueAttributes.Attribute { + /// public let rawValue: Int64 + /// public init(rawValue: Int64) { + /// self.rawValue = rawValue + /// } + /// public static let low = Priority(rawValue: 1) + /// public static let high = Priority(rawValue: 2) + /// } + /// ``` public protocol Attribute: Sendable, RawRepresentable where RawValue == Int64 {} } @@ -152,10 +161,6 @@ the attribute at runtime — no coordination between packages is needed. ```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 {} diff --git a/Sources/Logging/Docs.docc/Reference/LogEvent.md b/Sources/Logging/Docs.docc/Reference/LogEvent.md index d164c85..204dfaa 100644 --- a/Sources/Logging/Docs.docc/Reference/LogEvent.md +++ b/Sources/Logging/Docs.docc/Reference/LogEvent.md @@ -5,3 +5,15 @@ ### Creating a log event - ``init(level:message:metadata:source:file:function:line:)`` +- ``init(level:message:error:metadata:source:file:function:line:)`` + +### Inspecting a log event + +- ``level`` +- ``message`` +- ``error`` +- ``metadata`` +- ``source`` +- ``file`` +- ``function`` +- ``line`` diff --git a/Sources/Logging/Docs.docc/Reference/Logger-MetadataProvider.md b/Sources/Logging/Docs.docc/Reference/Logger-MetadataProvider.md index 1d2a039..f4b563e 100644 --- a/Sources/Logging/Docs.docc/Reference/Logger-MetadataProvider.md +++ b/Sources/Logging/Docs.docc/Reference/Logger-MetadataProvider.md @@ -4,7 +4,7 @@ ### Creating a metadata provider -- ``init(_:)`` +- ``init(_:)-(()->Logger.Metadata)`` ### Invoking the provider diff --git a/Sources/Logging/Docs.docc/Reference/Logger.md b/Sources/Logging/Docs.docc/Reference/Logger.md index 6f4084f..47a0e62 100644 --- a/Sources/Logging/Docs.docc/Reference/Logger.md +++ b/Sources/Logging/Docs.docc/Reference/Logger.md @@ -66,6 +66,10 @@ - ``subscript(metadataKey:)`` - ``MetadataValue`` +### Metadata attribute types + +- ``MetadataValueAttributes`` + ### Inspecting a logger - ``label`` diff --git a/Sources/Logging/Docs.docc/Reference/SwiftLogNoOpLogHandler.md b/Sources/Logging/Docs.docc/Reference/SwiftLogNoOpLogHandler.md index 8697fd4..e21ae88 100644 --- a/Sources/Logging/Docs.docc/Reference/SwiftLogNoOpLogHandler.md +++ b/Sources/Logging/Docs.docc/Reference/SwiftLogNoOpLogHandler.md @@ -1,5 +1,7 @@ # ``Logging/SwiftLogNoOpLogHandler`` +A log handler that silently discards all log messages. + ## Topics ### Creating a Swift Log no-op log handler diff --git a/Sources/Logging/Docs.docc/index.md b/Sources/Logging/Docs.docc/index.md index dd8ccf2..2fa79e4 100644 --- a/Sources/Logging/Docs.docc/index.md +++ b/Sources/Logging/Docs.docc/index.md @@ -17,7 +17,7 @@ This separation allows libraries to adopt the API while applications choose any compatible logging backend implementation without requiring changes from libraries. -## Getting Started +### Getting Started Use this package if you're writing a cross-platform application (for example, Linux and macOS) or library, and want to target this logging API. diff --git a/Sources/Logging/LogEvent.swift b/Sources/Logging/LogEvent.swift index 16a11f0..3f552b6 100644 --- a/Sources/Logging/LogEvent.swift +++ b/Sources/Logging/LogEvent.swift @@ -30,12 +30,9 @@ public struct LogEvent: Sendable { public var error: (any Error)? /// The metadata associated with this event, if any. - public var metadata: Logger.Metadata? { - get { self._metadata } - set { self._metadata = newValue } - } - - private var _metadata: Logger.Metadata? + /// + /// Metadata values may carry attributes accessible via ``Logger/MetadataValue/attributes``. + public var metadata: Logger.Metadata? /// The source where this log event originated, for example the logging module. /// @@ -116,7 +113,7 @@ public struct LogEvent: Sendable { self.level = level self.message = message self.error = error - self._metadata = metadata + self.metadata = metadata self._source = source self.file = file self.function = function diff --git a/Sources/Logging/Logger+Attributes.swift b/Sources/Logging/Logger+Attributes.swift new file mode 100644 index 0000000..45ec700 --- /dev/null +++ b/Sources/Logging/Logger+Attributes.swift @@ -0,0 +1,432 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +// MARK: - MetadataValueAttributes storage + +extension Logger { + /// Attributes that can be associated with metadata values. + public struct MetadataValueAttributes: Sendable { + /// 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**. + /// 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). + /// + /// ## Examples + /// + /// ```swift + /// public enum Priority: Int64, Sendable, Logger.MetadataValueAttributes.Attribute { + /// case low = 1 + /// case high = 2 + /// } + /// ``` + /// + /// ```swift + /// public struct Priority: Sendable, Hashable, Logger.MetadataValueAttributes.Attribute { + /// public let rawValue: Int64 + /// public init(rawValue: Int64) { + /// self.rawValue = rawValue + /// } + /// public static let low = Priority(rawValue: 1) + /// public static let high = Priority(rawValue: 2) + /// } + /// ``` + public protocol Attribute: Sendable, RawRepresentable where RawValue == Int64 {} + + /// An entry in the metadata attributes storage. + @usableFromInline + internal struct Entry: Sendable, Equatable { + @usableFromInline + internal var key: ObjectIdentifier + + @usableFromInline + internal var value: Int64 + + @inlinable + internal init(key: ObjectIdentifier, value: Int64) { + self.key = key + self.value = value + } + } + + @usableFromInline + internal var _inline: Entry? + + @usableFromInline + internal var _overflow: [Entry]? + + /// Create empty metadata value attributes. + @inlinable + public init() {} + + /// 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. + @inlinable + public subscript(attribute: Attr.Type) -> Attr? { + get { + let id = ObjectIdentifier(Attr.self) + if let inline = self._inline, inline.key == id { return Attr(rawValue: inline.value) } + if let overflow = self._overflow { + for entry in overflow { + if entry.key == id { return Attr(rawValue: entry.value) } + } + } + return nil + } + set { + let id = ObjectIdentifier(Attr.self) + if let v = newValue { + self._upsert(key: id, value: v.rawValue) + } else { + self._remove(key: id) + } + } + } + + @inlinable + internal mutating func _upsert(key id: ObjectIdentifier, value: Int64) { + let entry = Entry(key: id, value: value) + if let inline = self._inline, inline.key == id { + self._inline = entry + return + } + if let idx = self._overflow?.firstIndex(where: { $0.key == id }) { + self._overflow?[idx] = entry + return + } + if self._inline == nil { + self._inline = entry + } else { + if self._overflow == nil { + self._overflow = [entry] + } else { + self._overflow?.append(entry) + } + } + } + + @inlinable + internal mutating func _remove(key id: ObjectIdentifier) { + if let inline = self._inline, inline.key == id { + if var overflow = self._overflow, !overflow.isEmpty { + self._inline = overflow.removeLast() + self._overflow = overflow.isEmpty ? nil : overflow + } else { + self._inline = nil + } + return + } + if let idx = self._overflow?.firstIndex(where: { $0.key == id }) { + self._overflow?.remove(at: idx) + if self._overflow?.isEmpty == true { + self._overflow = nil + } + } + } + + @inlinable + internal mutating func _merge(from other: Self) { + if let inline = other._inline { + self._upsert(key: inline.key, value: inline.value) + } + if let overflow = other._overflow { + for entry in overflow { + self._upsert(key: entry.key, value: entry.value) + } + } + } + + /// Compare all entries as an unordered set. + /// + /// The inline slot and overflow array may hold the same logical entries in different + /// positions depending on insertion order. This method checks set equality by + /// verifying that every entry on one side exists on the other. O(n²) but n is + /// typically 1–2. + @inlinable + internal func _isEqual(to other: Self) -> Bool { + let lhsOverflowCount = self._overflow?.count ?? 0 + let rhsOverflowCount = other._overflow?.count ?? 0 + let lhsCount = (self._inline != nil ? 1 : 0) + lhsOverflowCount + let rhsCount = (other._inline != nil ? 1 : 0) + rhsOverflowCount + guard lhsCount == rhsCount else { return false } + guard lhsCount > 0 else { return true } + + // Check that every lhs entry exists in rhs. + // With matching counts, this is sufficient for set equality. + if let inline = self._inline { + if !other._contains(inline) { return false } + } + if let overflow = self._overflow { + for entry in overflow { + if !other._contains(entry) { return false } + } + } + return true + } + + @inlinable + internal func _contains(_ entry: Entry) -> Bool { + if self._inline == entry { return true } + if let overflow = self._overflow { + for e in overflow { + if e == entry { return true } + } + } + return false + } + } +} + +extension Logger.MetadataValueAttributes: Equatable { + @inlinable + public static func == (lhs: Self, rhs: Self) -> Bool { + lhs._isEqual(to: rhs) + } +} + +extension Logger.MetadataValueAttributes: ExpressibleByArrayLiteral { + /// Creates metadata value attributes from an array literal of attribute values. + /// + /// Each element is any ``Attribute`` conforming value. The key is + /// inferred from the concrete type of the value. + /// + /// ```swift + /// let attrs: Logger.MetadataValueAttributes = [Sensitivity.sensitive, ValueType.int64] + /// ``` + /// Each element goes through existential boxing to extract `type(of:)` and `.rawValue`. + /// This is acceptable for a literal initializer but should not be used in hot paths; + /// prefer the type-safe subscript (`attrs[SomeAttribute.self] = value`) for performance-sensitive code. + @inlinable + public init(arrayLiteral elements: any Logger.MetadataValueAttributes.Attribute...) { + self.init() + for element in elements { + self._upsert(key: ObjectIdentifier(type(of: element)), value: element.rawValue) + } + } +} + +// MARK: - AttributedStringCarrier + +extension Logger { + /// Internal carrier that wraps a string with metadata attributes. + /// + /// Produced by `MetadataValue.StringInterpolation` when any interpolation + /// segment specifies attributes, or by ``MetadataValue/attributed(_:attributes:)``. + /// This is the only type that carries attributes; the `.attributes` property on + /// `MetadataValue` checks for it with a concrete type comparison rather than a + /// protocol conformance lookup. + @usableFromInline + internal struct AttributedStringCarrier: CustomStringConvertible, Sendable { + @usableFromInline + internal let string: String + + @usableFromInline + internal let metadataAttributes: Logger.MetadataValueAttributes + + @usableFromInline + internal init(string: String, metadataAttributes: Logger.MetadataValueAttributes) { + self.string = string + self.metadataAttributes = metadataAttributes + } + + @inlinable + internal var description: String { self.string } + } +} + +// MARK: - MetadataValue attributes API + +extension Logger.MetadataValue { + /// The attributes associated with this metadata value, if any. + /// + /// **Getting:** When the value is a ``stringConvertible(_:)`` wrapping an + /// `AttributedStringCarrier`, 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. + /// + /// Only handlers that inspect attributes pay the cost of the getter check. + @inlinable + public var attributes: Logger.MetadataValueAttributes { + get { + if case .stringConvertible(let box) = self, + let carrier = box as? Logger.AttributedStringCarrier + { + return carrier.metadataAttributes + } + return .init() + } + set { + switch self { + case .string(let s): + self = .stringConvertible( + Logger.AttributedStringCarrier(string: s, metadataAttributes: newValue) + ) + case .stringConvertible(let box): + self = .stringConvertible( + Logger.AttributedStringCarrier(string: box.description, metadataAttributes: newValue) + ) + case .dictionary, .array: + assertionFailure("Cannot set attributes on .dictionary or .array metadata values") + return + } + } + } + + /// Creates an attributed metadata value from a string-convertible value and attributes. + /// + /// This is a convenience factory that behaves like an additional enum case, producing + /// a `.stringConvertible(AttributedStringCarrier(...))` value without string interpolation: + /// + /// ```swift + /// let value: Logger.MetadataValue = .attributed(userId, attributes: [Sensitivity.sensitive]) + /// ``` + @inlinable + public static func attributed( + _ value: some CustomStringConvertible & Sendable, + attributes: Logger.MetadataValueAttributes + ) -> Self { + .stringConvertible( + Logger.AttributedStringCarrier( + string: String(describing: value), + metadataAttributes: attributes + ) + ) + } +} + +// MARK: - Attributed string interpolation + +// Extension has to be done on explicit type rather than Logger.Metadata.Value as workaround for +// https://bugs.swift.org/browse/SR-9687 +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 { + @usableFromInline + internal var output: String = "" + + @usableFromInline + internal var attributes: Logger.MetadataValueAttributes = .init() + + @usableFromInline + internal var hasAttributes: Bool = false + + @inlinable + public init(literalCapacity: Int, interpolationCount: Int) { + self.output.reserveCapacity(literalCapacity + interpolationCount * 2) + } + + @inlinable + public mutating func appendLiteral(_ literal: String) { + self.output.append(literal) + } + + /// Interpolation with a custom attributes closure. + /// + /// When called, the result will be `.stringConvertible(AttributedStringCarrier(...))` + /// instead of `.string(...)`. + /// + /// ```swift + /// "\(userId, attributes: { $0[MyAttribute.self] = .flagged })" + /// ``` + @inlinable + public mutating func appendInterpolation( + _ value: T, + attributes: @Sendable (inout Logger.MetadataValueAttributes) -> Void + ) where T: CustomStringConvertible & Sendable { + self.output.append(value.description) + attributes(&self.attributes) + self.hasAttributes = true + } + + /// Interpolation with pre-built attributes. + /// + /// ```swift + /// "\(userId, attributes: [Sensitivity.sensitive])" + /// ``` + @inlinable + public mutating func appendInterpolation( + _ value: T, + attributes: Logger.MetadataValueAttributes + ) where T: CustomStringConvertible & Sendable { + self.output.append(value.description) + if self.hasAttributes { + self.attributes._merge(from: attributes) + } else { + self.attributes = attributes + } + self.hasAttributes = true + } + + /// Plain interpolation without attributes. + @inlinable + public mutating func appendInterpolation( + _ value: T + ) where T: CustomStringConvertible & Sendable { + self.output.append(value.description) + } + + /// Fallback interpolation for types that are not `CustomStringConvertible`. + @inlinable + public mutating func appendInterpolation( + _ value: T + ) where T: Sendable { + self.output.append(String(describing: value)) + } + + /// Unconstrained fallback for non-`Sendable` types. + @inlinable + public mutating func appendInterpolation( + _ value: T + ) { + self.output.append(String(describing: value)) + } + } + + /// Creates a metadata value from string interpolation. + /// + /// If any interpolation segment specified attributes, the result is + /// `.stringConvertible(AttributedStringCarrier(...))`. Otherwise, `.string(...)`. + @inlinable + public init(stringInterpolation: StringInterpolation) { + if stringInterpolation.hasAttributes { + self = .stringConvertible( + Logger.AttributedStringCarrier( + string: stringInterpolation.output, + metadataAttributes: stringInterpolation.attributes + ) + ) + } else { + self = .string(stringInterpolation.output) + } + } +} diff --git a/Sources/Logging/Logger.swift b/Sources/Logging/Logger.swift index d401878..8a9ce16 100644 --- a/Sources/Logging/Logger.swift +++ b/Sources/Logging/Logger.swift @@ -251,6 +251,7 @@ extension Logger { /// - 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. @@ -313,9 +314,23 @@ extension Logger { function: String = #function, line: UInt = #line ) { - self.log(level: level, message(), metadata: metadata(), source: nil, file: file, function: function, line: line) + self.log( + level: level, + message(), + error: nil, + metadata: metadata(), + source: nil, + file: file, + function: function, + line: line + ) } + /// Log a message using the log level and attributed metadata 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. + /// /// Add, change, or remove a logging metadata item. /// /// > Note: Changing the logging metadata only affects the instance of the `Logger` where you change it. @@ -1161,6 +1176,9 @@ extension Logger { /// `.array([.string("foo"), .string("bar \(buz)")])`, instead use the more natural `["foo", "bar \(buz)"]`. case array([Metadata.Value]) } +} + +extension Logger { /// The log level. /// @@ -1408,10 +1426,6 @@ extension Logger.MetadataValue: CustomStringConvertible { } } -// Extension has to be done on explicit type rather than Logger.Metadata.Value as workaround for -// https://bugs.swift.org/browse/SR-9687 -extension Logger.MetadataValue: ExpressibleByStringInterpolation {} - // Extension has to be done on explicit type rather than Logger.Metadata.Value as workaround for // https://bugs.swift.org/browse/SR-9686 extension Logger.MetadataValue: ExpressibleByDictionaryLiteral { @@ -1443,6 +1457,7 @@ extension Logger.MetadataValue: ExpressibleByArrayLiteral { // MARK: - Sendable support helpers extension Logger.MetadataValue: Sendable {} + extension Logger: Sendable {} extension Logger.Level: Sendable {} extension Logger.Message: Sendable {} diff --git a/Sources/Logging/MetadataProvider.swift b/Sources/Logging/MetadataProvider.swift index 0c52e88..dc353c1 100644 --- a/Sources/Logging/MetadataProvider.swift +++ b/Sources/Logging/MetadataProvider.swift @@ -53,12 +53,24 @@ extension Logger { /// } /// ``` /// + /// ### Metadata with Attributes + /// + /// Metadata providers can return values that carry attributes via string interpolation: + /// + /// ```swift + /// let provider = Logger.MetadataProvider { + /// [ + /// "trace-id": "\(Baggage.current?.traceID, sensitivity: .public)", + /// "user-id": "\(RequestContext.current.userId, sensitivity: .sensitive)" + /// ] + /// } + /// ``` + /// /// We recommend referring to [swift-distributed-tracing](https://github.com/apple/swift-distributed-tracing) /// for metadata providers which make use of its tracing and metadata propagation infrastructure. It is however /// possible to make use of metadata providers independently of tracing and instruments provided by that library, /// if necessary. public struct MetadataProvider: _SwiftLogSendable { - /// Provide ``Logger.Metadata`` from the current context. @usableFromInline internal let _provideMetadata: @Sendable () -> Metadata @@ -70,6 +82,8 @@ extension Logger { } /// Invokes the metadata provider and returns the generated contextual metadata. + /// + /// - Returns: Metadata dictionary, where values may carry attributes. public func get() -> Metadata { self._provideMetadata() } @@ -88,13 +102,12 @@ extension Logger.MetadataProvider { /// - Returns: A pseudo-`MetadataProvider` merging metadata from the given `MetadataProvider`s. public static func multiplex(_ providers: [Logger.MetadataProvider]) -> Logger.MetadataProvider? { assert(!providers.isEmpty, "providers MUST NOT be empty") + return Logger.MetadataProvider { - providers.reduce(into: [:]) { metadata, provider in - let providedMetadata = provider.get() - guard !providedMetadata.isEmpty else { - return - } - metadata.merge(providedMetadata, uniquingKeysWith: { _, rhs in rhs }) + providers.reduce(into: Logger.Metadata()) { merged, provider in + let provided = provider.get() + guard !provided.isEmpty else { return } + merged.merge(provided, uniquingKeysWith: { _, rhs in rhs }) } } } diff --git a/Tests/InMemoryLoggingTests/InMemoryLogHandlerTests.swift b/Tests/InMemoryLoggingTests/InMemoryLogHandlerTests.swift index cde34c5..a76b59c 100644 --- a/Tests/InMemoryLoggingTests/InMemoryLogHandlerTests.swift +++ b/Tests/InMemoryLoggingTests/InMemoryLogHandlerTests.swift @@ -22,15 +22,10 @@ struct InMemoryLogHandlerTests { let (logHandler, logger) = self.makeTestLogger() logger.info("hello", metadata: ["key1": "value1", "key2": ["a", "b", "c"]]) - #expect( - logHandler.entries == [ - InMemoryLogHandler.Entry( - level: .info, - message: "hello", - metadata: ["key1": "value1", "key2": ["a", "b", "c"]] - ) - ] - ) + #expect(logHandler.entries.count == 1) + #expect(logHandler.entries[0].level == .info) + #expect(logHandler.entries[0].message == "hello") + #expect(logHandler.entries[0].metadata == ["key1": "value1", "key2": ["a", "b", "c"]]) } @Test @@ -39,16 +34,10 @@ struct InMemoryLogHandlerTests { logger[metadataKey: "test"] = "value" logger.info("hello", metadata: ["key1": "value1", "key2": ["a", "b", "c"]]) - #expect( - logHandler.entries == [ - InMemoryLogHandler.Entry( - level: .info, - message: "hello", - metadata: ["key1": "value1", "key2": ["a", "b", "c"], "test": "value"] - ) - ] - ) - // Metadata also sticks onto the logger + #expect(logHandler.entries.count == 1) + #expect(logHandler.entries[0].level == .info) + #expect(logHandler.entries[0].message == "hello") + #expect(logHandler.entries[0].metadata == ["key1": "value1", "key2": ["a", "b", "c"], "test": "value"]) #expect(logger[metadataKey: "test"] == "value") } @@ -62,11 +51,54 @@ struct InMemoryLogHandlerTests { logger[metadataKey: "c"] = "2" logger.info("hello", metadata: ["c": "3"]) - #expect( - logHandler.entries == [ - InMemoryLogHandler.Entry(level: .info, message: "hello", metadata: ["a": "1", "b": "2", "c": "3"]) + #expect(logHandler.entries.count == 1) + #expect(logHandler.entries[0].level == .info) + #expect(logHandler.entries[0].message == "hello") + #expect(logHandler.entries[0].metadata == ["a": "1", "b": "1", "c": "3"]) + } + + @Test + func clear() { + let (logHandler, logger) = self.makeTestLogger() + logger.info("hello", metadata: ["key1": "value1", "key2": ["a", "b", "c"]]) + logHandler.clear() + logger.info("hello2") + + #expect(logHandler.entries.count == 1) + #expect(logHandler.entries[0].level == .info) + #expect(logHandler.entries[0].message == "hello2") + #expect(logHandler.entries[0].metadata == [:]) + } + + @Test + func metadataWithAttributesIsPreservedInEntry() { + var (logHandler, logger) = self.makeTestLogger() + logger.logLevel = .trace + logger[metadataKey: "global"] = "value" + + logger.log( + level: .info, + "test", + metadata: [ + "key": "\("value", attributes: { _ in })" ] ) + + #expect(logHandler.entries.count == 1) + #expect(logHandler.entries[0].metadata["key"]?.description == "value") + #expect(logHandler.entries[0].metadata["global"]?.description == "value") + } + + private func makeTestLogger(metadataProvider: Logger.MetadataProvider? = nil) -> (InMemoryLogHandler, Logger) { + var logHandler = InMemoryLogHandler() + logHandler.metadataProvider = metadataProvider + let logger = Logger( + label: "MyApp", + factory: { _ in + logHandler + } + ) + return (logHandler, logger) } @Test @@ -81,7 +113,7 @@ struct InMemoryLogHandlerTests { level: .info, message: "hello", error: TestError.first, - metadata: [:], + metadata: [:] ) ) @@ -91,7 +123,7 @@ struct InMemoryLogHandlerTests { level: .info, message: "hello", error: nil, - metadata: [:], + metadata: [:] ) ) @@ -116,33 +148,6 @@ struct InMemoryLogHandlerTests { ) } - @Test - func clear() { - let (logHandler, logger) = self.makeTestLogger() - logger.info("hello", metadata: ["key1": "value1", "key2": ["a", "b", "c"]]) - logHandler.clear() - logger.info("hello2") - - // Only hello2 is here - #expect( - logHandler.entries == [ - InMemoryLogHandler.Entry(level: .info, message: "hello2", metadata: [:]) - ] - ) - } - - private func makeTestLogger(metadataProvider: Logger.MetadataProvider? = nil) -> (InMemoryLogHandler, Logger) { - var logHandler = InMemoryLogHandler() - logHandler.metadataProvider = metadataProvider - let logger = Logger( - label: "MyApp", - factory: { _ in - logHandler - } - ) - return (logHandler, logger) - } - enum TestError: Error { case first case second diff --git a/Tests/LoggingTests/LogEventTest.swift b/Tests/LoggingTests/LogEventTest.swift index 9f294bc..1c0c39b 100644 --- a/Tests/LoggingTests/LogEventTest.swift +++ b/Tests/LoggingTests/LogEventTest.swift @@ -98,6 +98,65 @@ struct LogEventTest { #expect(event.metadata == nil) } + // MARK: - Attributes on metadata values + + @Test func metadataValueCarriesAttributesThroughStringInterpolation() { + enum TestAttr: Int64, Logger.MetadataValueAttributes.Attribute { + case flagged = 1 + } + + let value: Logger.MetadataValue = "\("secret", attributes: { $0[TestAttr.self] = .flagged })" + #expect(value.attributes[TestAttr.self] == .flagged) + #expect(value.description == "secret") + } + + @Test func metadataValueWithoutAttributesProducesString() { + let value: Logger.MetadataValue = "\("plain")" + #expect(value.attributes == Logger.MetadataValueAttributes()) + + if case .string(let s) = value { + #expect(s == "plain") + } else { + Issue.record("Expected .string case for non-attributed interpolation") + } + } + + @Test func metadataValueAttributesAreEmptyForPlainValues() { + let values: [Logger.MetadataValue] = [ + .string("test"), + .stringConvertible(42), + .array(["a", "b"]), + .dictionary(["k": "v"]), + ] + for value in values { + #expect(value.attributes == Logger.MetadataValueAttributes()) + } + } + + @Test func metadataValuesWithAttributesFlowThroughLogEvent() { + enum TestAttr: Int64, Logger.MetadataValueAttributes.Attribute { + case flagged = 1 + } + + let event = LogEvent( + level: .info, + message: "test", + error: nil, + metadata: [ + "secret": "\("value", attributes: { $0[TestAttr.self] = .flagged })", + "plain": "no-attrs", + ], + source: nil, + file: "M/F.swift", + function: "f()", + line: 1 + ) + + #expect(event.metadata?["secret"]?.attributes[TestAttr.self] == .flagged) + #expect(event.metadata?["secret"]?.description == "value") + #expect(event.metadata?["plain"]?.attributes[TestAttr.self] == nil) + } + @Test func loggerDerivedSourceMatchesModuleName() { let recorder = Recorder() let handler = LogEventHandler(recorder: recorder) diff --git a/Tests/LoggingTests/LoggingTest.swift b/Tests/LoggingTests/LoggingTest.swift index 2ccc2ff..c6991dc 100644 --- a/Tests/LoggingTests/LoggingTest.swift +++ b/Tests/LoggingTests/LoggingTest.swift @@ -17,6 +17,11 @@ import Testing @testable import Logging +private enum TestAttr: Int64, Logger.MetadataValueAttributes.Attribute { + case x = 1 + case y = 2 +} + extension LogHandler { fileprivate func with(logLevel: Logger.Level) -> any LogHandler { var result = self @@ -852,6 +857,73 @@ struct LoggingTest { logger1.error("hey") } + @Test func multiplexLogHandlerMetadataWithAttributes_settingAndReading() { + let logging1 = TestLogging() + let logging2 = TestLogging() + + let logger1 = logging1.make(label: "1") + let logger2 = logging2.make(label: "2") + + var multiplexLogger = Logger( + label: "test", + factory: { _ in + MultiplexLogHandler([logger1, logger2]) + } + ) + + // Set metadata with attributes via string interpolation + multiplexLogger[metadataKey: "key1"] = "\("value1", attributes: { $0[TestAttr.self] = .x })" + + // The value survives the round-trip + let retrieved = multiplexLogger[metadataKey: "key1"] + #expect(retrieved != nil) + #expect(retrieved?.description == "value1") + + // Attributes are preserved inside .stringConvertible + #expect(retrieved?.attributes[TestAttr.self] == .x) + } + + @Test func multiplexLogHandlerMetadataWithAttributes_forwardsEventWithAttributes() { + let logging1 = TestLogging() + let logging2 = TestLogging() + + var logger = Logger( + label: "test", + factory: { + MultiplexLogHandler([logging1.make(label: $0), logging2.make(label: $0)]) + } + ) + logger.logLevel = .debug + + // Log with metadata containing attributed values + logger.info("hello", metadata: ["request-id": "\("abc123")"]) + + // Both handlers should receive the message + logging1.history.assertExist(level: .info, message: "hello") + logging2.history.assertExist(level: .info, message: "hello") + } + + @Test func metadataWithAttributes_flowsThroughHandler() { + let logging = TestLogging() + + var logger = Logger( + label: "test", + factory: { logging.make(label: $0) } + ) + logger.logLevel = .debug + + // Log with metadata values that carry attributes + logger.info( + "attributed event", + metadata: [ + "user-id": "\("12345", attributes: { $0[TestAttr.self] = .x })" + ] + ) + + // The handler should receive the message via LogEvent + logging.history.assertExist(level: .info, message: "attributed event") + } + /// Protects an object such that it can only be accessed while holding a lock. private final class LockedValueBox: @unchecked Sendable { private let lock = Lock() diff --git a/Tests/LoggingTests/MetadataAttributesTest.swift b/Tests/LoggingTests/MetadataAttributesTest.swift new file mode 100644 index 0000000..0f6ac50 --- /dev/null +++ b/Tests/LoggingTests/MetadataAttributesTest.swift @@ -0,0 +1,443 @@ +//===----------------------------------------------------------------------===// +// +// 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 Logging +import Testing + +// MARK: - Test Attribute Keys + +enum AttrA: Int64, Logger.MetadataValueAttributes.Attribute { + case a1 = 1 + case a2 = 2 +} + +enum AttrB: Int64, Logger.MetadataValueAttributes.Attribute { + case b1 = 1 + case b2 = 2 +} + +enum AttrC: Int64, Logger.MetadataValueAttributes.Attribute { + case c1 = 1 + case c2 = 2 +} + +enum AttrD: Int64, Logger.MetadataValueAttributes.Attribute { + case d1 = 1 + case d2 = 2 +} + +enum AttrE: Int64, Logger.MetadataValueAttributes.Attribute { + case e1 = 1 + case e2 = 2 +} + +// MARK: - Tests + +@Suite("MetadataValueAttributes Tests") +struct MetadataAttributesTests { + + @Test("Empty attributes") + func testEmpty() { + let attrs = Logger.MetadataValueAttributes() + #expect(attrs[AttrA.self] == nil) + #expect(attrs[AttrB.self] == nil) + } + + @Test("Set and get single attribute (inline)") + func testSingleInline() { + var attrs = Logger.MetadataValueAttributes() + attrs[AttrA.self] = .a1 + #expect(attrs[AttrA.self] == .a1) + } + + @Test("Set and get multiple attributes") + func testMultipleAttributes() { + var attrs = Logger.MetadataValueAttributes() + attrs[AttrA.self] = .a1 + attrs[AttrB.self] = .b2 + attrs[AttrC.self] = .c1 + + #expect(attrs[AttrA.self] == .a1) + #expect(attrs[AttrB.self] == .b2) + #expect(attrs[AttrC.self] == .c1) + } + + @Test("Update existing attribute") + func testUpdate() { + var attrs = Logger.MetadataValueAttributes() + attrs[AttrA.self] = .a1 + #expect(attrs[AttrA.self] == .a1) + + attrs[AttrA.self] = .a2 + #expect(attrs[AttrA.self] == .a2) + } + + @Test("Remove inline attribute") + func testRemoveInline() { + var attrs = Logger.MetadataValueAttributes() + attrs[AttrA.self] = .a1 + + attrs[AttrA.self] = nil + #expect(attrs[AttrA.self] == nil) + } + + @Test("Remove overflow attribute") + func testRemoveOverflow() { + var attrs = Logger.MetadataValueAttributes() + attrs[AttrA.self] = .a1 + attrs[AttrB.self] = .b1 + attrs[AttrC.self] = .c1 + + attrs[AttrB.self] = nil + #expect(attrs[AttrA.self] == .a1) + #expect(attrs[AttrB.self] == nil) + #expect(attrs[AttrC.self] == .c1) + } + + @Test("Remove inline promotes from overflow") + func testRemoveInlinePromotesOverflow() { + var attrs = Logger.MetadataValueAttributes() + attrs[AttrA.self] = .a1 + attrs[AttrB.self] = .b1 // overflow + + // Remove inline — overflow entry should be promoted + attrs[AttrA.self] = nil + + #expect(attrs[AttrA.self] == nil) + #expect(attrs[AttrB.self] == .b1) + } + + @Test("Five attributes") + func testFiveAttributes() { + var attrs = Logger.MetadataValueAttributes() + attrs[AttrA.self] = .a1 + attrs[AttrB.self] = .b1 + attrs[AttrC.self] = .c1 + attrs[AttrD.self] = .d1 + attrs[AttrE.self] = .e1 + + #expect(attrs[AttrA.self] == .a1) + #expect(attrs[AttrB.self] == .b1) + #expect(attrs[AttrC.self] == .c1) + #expect(attrs[AttrD.self] == .d1) + #expect(attrs[AttrE.self] == .e1) + } + + @Test("Update overflow attribute") + func testUpdateOverflow() { + var attrs = Logger.MetadataValueAttributes() + attrs[AttrA.self] = .a1 + attrs[AttrB.self] = .b1 + + attrs[AttrB.self] = .b2 + #expect(attrs[AttrB.self] == .b2) + #expect(attrs[AttrA.self] == .a1) + } + + @Test("Equality with same content") + func testEquality() { + var attrs1 = Logger.MetadataValueAttributes() + attrs1[AttrA.self] = .a1 + attrs1[AttrB.self] = .b1 + + var attrs2 = Logger.MetadataValueAttributes() + attrs2[AttrA.self] = .a1 + attrs2[AttrB.self] = .b1 + + #expect(attrs1 == attrs2) + + attrs2[AttrB.self] = .b2 + #expect(attrs1 != attrs2) + } + + @Test("Equality is order-independent") + func testOrderIndependentEquality() { + var attrs1 = Logger.MetadataValueAttributes() + attrs1[AttrA.self] = .a1 + attrs1[AttrB.self] = .b1 + attrs1[AttrC.self] = .c1 + + var attrs2 = Logger.MetadataValueAttributes() + attrs2[AttrC.self] = .c1 + attrs2[AttrA.self] = .a1 + attrs2[AttrB.self] = .b1 + + #expect(attrs1 == attrs2) + } + + @Test("Setting nil on non-existent attribute is no-op") + func testSetNilNonExistent() { + var attrs = Logger.MetadataValueAttributes() + attrs[AttrA.self] = nil + #expect(attrs[AttrA.self] == nil) + + attrs[AttrB.self] = .b1 + attrs[AttrA.self] = nil + #expect(attrs[AttrA.self] == nil) + #expect(attrs[AttrB.self] == .b1) + } + + // MARK: - MetadataValue.attributed factory + + @Test("Create attributed value with .attributed factory") + func testAttributedFactory() { + let value: Logger.MetadataValue = .attributed("hello", attributes: [AttrA.a1]) + #expect(value.description == "hello") + #expect(value.attributes[AttrA.self] == .a1) + } + + @Test("Attributed factory with multiple attributes") + func testAttributedFactoryMultipleAttributes() { + let value: Logger.MetadataValue = .attributed("test", attributes: [AttrA.a1, AttrB.b2]) + #expect(value.description == "test") + #expect(value.attributes[AttrA.self] == .a1) + #expect(value.attributes[AttrB.self] == .b2) + } + + @Test("Attributed factory with empty attributes") + func testAttributedFactoryEmptyAttributes() { + let value: Logger.MetadataValue = .attributed("plain", attributes: .init()) + #expect(value.description == "plain") + #expect(value.attributes[AttrA.self] == nil) + } + + @Test("Attributed factory produces same result as string interpolation") + func testAttributedFactoryMatchesStringInterpolation() { + let factory: Logger.MetadataValue = .attributed("42", attributes: [AttrA.a1]) + let interpolated: Logger.MetadataValue = "\(42, attributes: [AttrA.a1])" + #expect(factory.description == interpolated.description) + #expect(factory.attributes == interpolated.attributes) + } + + // MARK: - Array literal construction + + @Test("Array literal with single attribute") + func testArrayLiteralSingle() { + let attrs: Logger.MetadataValueAttributes = [AttrA.a1] + #expect(attrs[AttrA.self] == .a1) + } + + @Test("Array literal with multiple attributes") + func testArrayLiteralMultiple() { + let attrs: Logger.MetadataValueAttributes = [AttrA.a1, AttrB.b2, AttrC.c1] + #expect(attrs[AttrA.self] == .a1) + #expect(attrs[AttrB.self] == .b2) + #expect(attrs[AttrC.self] == .c1) + } + + @Test("Array literal with duplicate key uses last value") + func testArrayLiteralDuplicateKey() { + let attrs: Logger.MetadataValueAttributes = [AttrA.a1, AttrA.a2] + #expect(attrs[AttrA.self] == .a2) + } + + // MARK: - MetadataValue.attributes setter + + @Test("Set attributes on .string value") + func testSetAttributesOnString() { + var value: Logger.MetadataValue = "hello" + #expect(value.attributes[AttrA.self] == nil) + + value.attributes = [AttrA.a1] + + #expect(value.description == "hello") + #expect(value.attributes[AttrA.self] == .a1) + } + + @Test("Set attributes replaces existing attributes") + func testSetAttributesReplacesExisting() { + var value: Logger.MetadataValue = .attributed("test", attributes: [AttrA.a1]) + #expect(value.attributes[AttrA.self] == .a1) + + let newAttrs: Logger.MetadataValueAttributes = [AttrB.b2] + value.attributes = newAttrs + + #expect(value.description == "test") + #expect(value.attributes[AttrA.self] == nil) + #expect(value.attributes[AttrB.self] == .b2) + } + + // MARK: - Intermediate handler modifies attributes + + @Test("Intermediate handler adds attributes before forwarding") + func testIntermediateHandlerAddsAttributes() { + let recorder = AttributeRecorder() + let inner = AttributeRecordingHandler(recorder: recorder) + let enriching = AttributeEnrichingHandler(wrapping: inner) + + var logger = Logger(label: "test") { _ in enriching } + logger.logLevel = .trace + + logger.info( + "event", + metadata: [ + "tagged": .attributed(42, attributes: [AttrA.a1]), + "plain": "no-attrs", + ] + ) + + #expect(recorder.messages.count == 1) + let metadata = recorder.messages[0] + + // The enriching handler should have added AttrB to all values + #expect(metadata["tagged"]?.attributes[AttrA.self] == .a1) + #expect(metadata["tagged"]?.attributes[AttrB.self] == .b1) + #expect(metadata["plain"]?.attributes[AttrB.self] == .b1) + } + + @Test("Intermediate handler replaces attributes before forwarding") + func testIntermediateHandlerReplacesAttributes() { + let recorder = AttributeRecorder() + let inner = AttributeRecordingHandler(recorder: recorder) + let stripping = AttributeStrippingHandler(wrapping: inner) + + var logger = Logger(label: "test") { _ in stripping } + logger.logLevel = .trace + + logger.info( + "event", + metadata: [ + "tagged": .attributed(42, attributes: [AttrA.a1]) + ] + ) + + #expect(recorder.messages.count == 1) + let metadata = recorder.messages[0] + + // The stripping handler should have removed all attributes + #expect(metadata["tagged"]?.attributes[AttrA.self] == nil) + #expect(metadata["tagged"]?.description == "42") + } +} + +// MARK: - Test Helpers for intermediate handler tests + +private final class AttributeRecorder: @unchecked Sendable { + private let lock = Lock() + private var _messages: [Logger.Metadata] = [] + + func record(metadata: Logger.Metadata) { + self.lock.withLock { self._messages.append(metadata) } + } + + var messages: [Logger.Metadata] { + self.lock.withLock { self._messages } + } +} + +private struct AttributeRecordingHandler: LogHandler { + var logLevel: Logger.Level = .trace + var metadata = Logger.Metadata() + var metadataProvider: Logger.MetadataProvider? + private let recorder: AttributeRecorder + + init(recorder: AttributeRecorder) { + self.recorder = recorder + } + + subscript(metadataKey key: String) -> Logger.Metadata.Value? { + get { self.metadata[key] } + set { self.metadata[key] = newValue } + } + + func log(event: LogEvent) { + var merged = self.metadata + if let eventMetadata = event.metadata { + merged.merge(eventMetadata, uniquingKeysWith: { _, rhs in rhs }) + } + self.recorder.record(metadata: merged) + } +} + +/// Intermediate handler that enriches all metadata values with AttrB before forwarding. +private struct AttributeEnrichingHandler: LogHandler { + var logLevel: Logger.Level { + get { self.inner.logLevel } + set { self.inner.logLevel = newValue } + } + + var metadata: Logger.Metadata { + get { self.inner.metadata } + set { self.inner.metadata = newValue } + } + + var metadataProvider: Logger.MetadataProvider? { + get { self.inner.metadataProvider } + set { self.inner.metadataProvider = newValue } + } + + private var inner: any LogHandler + + init(wrapping inner: any LogHandler) { + self.inner = inner + } + + subscript(metadataKey key: String) -> Logger.Metadata.Value? { + get { self.inner[metadataKey: key] } + set { self.inner[metadataKey: key] = newValue } + } + + func log(event: LogEvent) { + var mutatedEvent = event + if var eventMetadata = event.metadata { + for (key, value) in eventMetadata { + var attrs = value.attributes + attrs[AttrB.self] = .b1 + eventMetadata[key]?.attributes = attrs + } + mutatedEvent.metadata = eventMetadata + } + self.inner.log(event: mutatedEvent) + } +} + +/// Intermediate handler that strips all attributes before forwarding. +private struct AttributeStrippingHandler: LogHandler { + var logLevel: Logger.Level { + get { self.inner.logLevel } + set { self.inner.logLevel = newValue } + } + + var metadata: Logger.Metadata { + get { self.inner.metadata } + set { self.inner.metadata = newValue } + } + + var metadataProvider: Logger.MetadataProvider? { + get { self.inner.metadataProvider } + set { self.inner.metadataProvider = newValue } + } + + private var inner: any LogHandler + + init(wrapping inner: any LogHandler) { + self.inner = inner + } + + subscript(metadataKey key: String) -> Logger.Metadata.Value? { + get { self.inner[metadataKey: key] } + set { self.inner[metadataKey: key] = newValue } + } + + func log(event: LogEvent) { + var mutatedEvent = event + if var eventMetadata = event.metadata { + for (key, _) in eventMetadata { + eventMetadata[key]?.attributes = .init() + } + mutatedEvent.metadata = eventMetadata + } + self.inner.log(event: mutatedEvent) + } +}