Skip to content

Commit e98a4aa

Browse files
committed
Add withMetadata() convenience function for adding multiple metadata k/v pairs to a Logger
1 parent db86ac7 commit e98a4aa

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

Sources/Logging/Logging.swift

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,17 @@ extension Logger {
166166
}
167167
}
168168

169+
/// Convenience function for adding multiple metadata items to a logger.
170+
///
171+
/// - note: Logging metadata behaves as a value that means a change to the logging metadata will only affect the
172+
/// very `Logger` it was changed on.
173+
@inlinable
174+
public mutating func withMetadata(metadata: Logger.Metadata) {
175+
metadata.forEach { (key, value) in
176+
self.handler[metadataKey: key] = value
177+
}
178+
}
179+
169180
/// Get or set the log level configured for this `Logger`.
170181
///
171182
/// - note: `Logger`s treat `logLevel` as a value. This means that a change in `logLevel` will only affect this

Tests/LoggingTests/LoggingTest.swift

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -357,6 +357,25 @@ class LoggingTest: XCTestCase {
357357
"nested-list": ["l1str", ["l2str1", "l2str2"]]])
358358
}
359359

360+
func testWithMetadata() {
361+
let testLogging = TestLogging()
362+
LoggingSystem.bootstrapInternal { testLogging.make(label: $0) }
363+
364+
var logger = Logger(label: "\(#function)")
365+
let metadata: Logger.Metadata = [
366+
"foo": ["bar", "buz"],
367+
"empty-list": [],
368+
"nested-list": ["l1str", ["l2str1", "l2str2"]],
369+
]
370+
logger.withMetadata(metadata: metadata)
371+
logger.info("hello world!")
372+
testLogging.history.assertExist(level: .info,
373+
message: "hello world!",
374+
metadata: ["foo": ["bar", "buz"],
375+
"empty-list": [],
376+
"nested-list": ["l1str", ["l2str1", "l2str2"]]])
377+
}
378+
360379
// Example of custom "box" which may be used to implement "render at most once" semantics
361380
// Not thread-safe, thus should not be shared across threads.
362381
internal final class LazyMetadataBox: CustomStringConvertible {

0 commit comments

Comments
 (0)