Skip to content

Commit

Permalink
Add withMetadata() convenience function for adding multiple metadata …
Browse files Browse the repository at this point in the history
…k/v pairs to a Logger
  • Loading branch information
gabbifish committed Sep 13, 2024
1 parent db86ac7 commit e98a4aa
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
11 changes: 11 additions & 0 deletions Sources/Logging/Logging.swift
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,17 @@ extension Logger {
}
}

/// Convenience function for adding multiple metadata items to a logger.
///
/// - note: Logging metadata behaves as a value that means a change to the logging metadata will only affect the
/// very `Logger` it was changed on.
@inlinable
public mutating func withMetadata(metadata: Logger.Metadata) {
metadata.forEach { (key, value) in
self.handler[metadataKey: key] = value
}
}

/// Get or set the log level configured for this `Logger`.
///
/// - note: `Logger`s treat `logLevel` as a value. This means that a change in `logLevel` will only affect this
Expand Down
19 changes: 19 additions & 0 deletions Tests/LoggingTests/LoggingTest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -357,6 +357,25 @@ class LoggingTest: XCTestCase {
"nested-list": ["l1str", ["l2str1", "l2str2"]]])
}

func testWithMetadata() {
let testLogging = TestLogging()
LoggingSystem.bootstrapInternal { testLogging.make(label: $0) }

var logger = Logger(label: "\(#function)")
let metadata: Logger.Metadata = [
"foo": ["bar", "buz"],
"empty-list": [],
"nested-list": ["l1str", ["l2str1", "l2str2"]],
]
logger.withMetadata(metadata: metadata)
logger.info("hello world!")
testLogging.history.assertExist(level: .info,
message: "hello world!",
metadata: ["foo": ["bar", "buz"],
"empty-list": [],
"nested-list": ["l1str", ["l2str1", "l2str2"]]])
}

// Example of custom "box" which may be used to implement "render at most once" semantics
// Not thread-safe, thus should not be shared across threads.
internal final class LazyMetadataBox: CustomStringConvertible {
Expand Down

0 comments on commit e98a4aa

Please sign in to comment.