mirror of
https://github.com/apple/swift-log
synced 2026-11-24 03:47:49 +00:00
Compare commits
25
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fc3aaf1b75 | ||
|
|
7bdda417df | ||
|
|
4c9b50fa60 | ||
|
|
28ccbd72d9 | ||
|
|
552f91cab2 | ||
|
|
d9717f5de3 | ||
|
|
6f9aaba8e8 | ||
|
|
23ea0c2f24 | ||
|
|
ebea1c0baa | ||
|
|
e3fd0e4df6 | ||
|
|
96fdafb0b8 | ||
|
|
921cb5344c | ||
|
|
9a1f7eb0f5 | ||
|
|
2c3ee82e27 | ||
|
|
7cbc402e0d | ||
|
|
3e437856cc | ||
|
|
5e980ddce2 | ||
|
|
4c8caad4d8 | ||
|
|
5abb878a84 | ||
|
|
e3db5dc433 | ||
|
|
784405d8c9 | ||
|
|
fa5af66dd8 | ||
|
|
a4a2505e1f | ||
|
|
0c569842df | ||
|
|
ddb59ca90a |
No files matched your search
+4
-1
@@ -22,11 +22,14 @@ let package = Package(
|
||||
],
|
||||
dependencies: [
|
||||
.package(url: "https://github.com/apple/swift-docc-plugin", from: "1.0.0"),
|
||||
.package(url: "https://github.com/slashmo/swift-distributed-tracing-baggage", branch: "support/swift-5.0"),
|
||||
],
|
||||
targets: [
|
||||
.target(
|
||||
name: "Logging",
|
||||
dependencies: []
|
||||
dependencies: [
|
||||
.product(name: "InstrumentationBaggage", package: "swift-distributed-tracing-baggage"),
|
||||
]
|
||||
),
|
||||
.testTarget(
|
||||
name: "LoggingTests",
|
||||
|
||||
@@ -20,10 +20,15 @@ let package = Package(
|
||||
products: [
|
||||
.library(name: "Logging", targets: ["Logging"]),
|
||||
],
|
||||
dependencies: [
|
||||
.package(url: "https://github.com/slashmo/swift-distributed-tracing-baggage", .branch("support/swift-5.0")),
|
||||
],
|
||||
targets: [
|
||||
.target(
|
||||
name: "Logging",
|
||||
dependencies: []
|
||||
dependencies: [
|
||||
.product(name: "InstrumentationBaggage", package: "swift-distributed-tracing-baggage"),
|
||||
]
|
||||
),
|
||||
.testTarget(
|
||||
name: "LoggingTests",
|
||||
|
||||
@@ -20,10 +20,15 @@ let package = Package(
|
||||
products: [
|
||||
.library(name: "Logging", targets: ["Logging"]),
|
||||
],
|
||||
dependencies: [
|
||||
.package(url: "https://github.com/slashmo/swift-distributed-tracing-baggage", .branch("support/swift-5.0")),
|
||||
],
|
||||
targets: [
|
||||
.target(
|
||||
name: "Logging",
|
||||
dependencies: []
|
||||
dependencies: [
|
||||
.product(name: "InstrumentationBaggage", package: "swift-distributed-tracing-baggage"),
|
||||
]
|
||||
),
|
||||
.testTarget(
|
||||
name: "LoggingTests",
|
||||
|
||||
@@ -20,10 +20,15 @@ let package = Package(
|
||||
products: [
|
||||
.library(name: "Logging", targets: ["Logging"]),
|
||||
],
|
||||
dependencies: [
|
||||
.package(url: "https://github.com/slashmo/swift-distributed-tracing-baggage", .branch("support/swift-5.0")),
|
||||
],
|
||||
targets: [
|
||||
.target(
|
||||
name: "Logging",
|
||||
dependencies: []
|
||||
dependencies: [
|
||||
.product(name: "InstrumentationBaggage", package: "swift-distributed-tracing-baggage"),
|
||||
]
|
||||
),
|
||||
.testTarget(
|
||||
name: "LoggingTests",
|
||||
|
||||
@@ -20,10 +20,15 @@ let package = Package(
|
||||
products: [
|
||||
.library(name: "Logging", targets: ["Logging"]),
|
||||
],
|
||||
dependencies: [
|
||||
.package(url: "https://github.com/slashmo/swift-distributed-tracing-baggage", .branch("support/swift-5.0")),
|
||||
],
|
||||
targets: [
|
||||
.target(
|
||||
name: "Logging",
|
||||
dependencies: []
|
||||
dependencies: [
|
||||
.product(name: "InstrumentationBaggage", package: "swift-distributed-tracing-baggage"),
|
||||
]
|
||||
),
|
||||
.testTarget(
|
||||
name: "LoggingTests",
|
||||
|
||||
@@ -20,10 +20,15 @@ let package = Package(
|
||||
products: [
|
||||
.library(name: "Logging", targets: ["Logging"]),
|
||||
],
|
||||
dependencies: [
|
||||
.package(url: "https://github.com/slashmo/swift-distributed-tracing-baggage", .branch("support/swift-5.0")),
|
||||
],
|
||||
targets: [
|
||||
.target(
|
||||
name: "Logging",
|
||||
dependencies: []
|
||||
dependencies: [
|
||||
.product(name: "InstrumentationBaggage", package: "swift-distributed-tracing-baggage"),
|
||||
]
|
||||
),
|
||||
.testTarget(
|
||||
name: "LoggingTests",
|
||||
|
||||
@@ -20,10 +20,15 @@ let package = Package(
|
||||
products: [
|
||||
.library(name: "Logging", targets: ["Logging"]),
|
||||
],
|
||||
dependencies: [
|
||||
.package(url: "https://github.com/slashmo/swift-distributed-tracing-baggage", branch: "support/swift-5.0"),
|
||||
],
|
||||
targets: [
|
||||
.target(
|
||||
name: "Logging",
|
||||
dependencies: []
|
||||
dependencies: [
|
||||
.product(name: "InstrumentationBaggage", package: "swift-distributed-tracing-baggage"),
|
||||
]
|
||||
),
|
||||
.testTarget(
|
||||
name: "LoggingTests",
|
||||
|
||||
@@ -126,6 +126,18 @@ public protocol LogHandler: _SwiftLogSendableLogHandler {
|
||||
/// - file: The file the log message was emitted from.
|
||||
/// - function: The function the log line was emitted from.
|
||||
/// - line: The line the log message was emitted from.
|
||||
func log(level: Logger.Level,
|
||||
message: Logger.Message,
|
||||
metadata: Logger.Metadata?,
|
||||
baggage: Logger.BaggageStrategy,
|
||||
source: String,
|
||||
file: String,
|
||||
function: String,
|
||||
line: UInt)
|
||||
|
||||
/// SwiftLog 1.4 compatibility method. Please do _not_ implement, implement
|
||||
/// `log(level:message:metadata:baggage:source:file:function:line:)` instead.
|
||||
@available(*, deprecated, renamed: "log(level:message:metadata:baggage:source:file:function:line:)")
|
||||
func log(level: Logger.Level,
|
||||
message: Logger.Message,
|
||||
metadata: Logger.Metadata?,
|
||||
@@ -168,15 +180,30 @@ extension LogHandler {
|
||||
public func log(level: Logger.Level,
|
||||
message: Logger.Message,
|
||||
metadata: Logger.Metadata?,
|
||||
baggage: Logger.BaggageStrategy,
|
||||
source: String,
|
||||
file: String,
|
||||
function: String,
|
||||
line: UInt) {
|
||||
/// This implementation drops the `baggage` parameter
|
||||
self.log(level: level, message: message, metadata: metadata, source: source, file: file, function: function, line: line)
|
||||
}
|
||||
|
||||
@available(*, deprecated, renamed: "log(level:message:metadata:baggage:source:file:function:line:)")
|
||||
public func log(level: Logger.Level,
|
||||
message: Logger.Message,
|
||||
metadata: Logger.Metadata?,
|
||||
source: String,
|
||||
file: String,
|
||||
function: String,
|
||||
line: UInt) {
|
||||
/// This implementation drops the `source` parameter
|
||||
self.log(level: level, message: message, metadata: metadata, file: file, function: function, line: line)
|
||||
}
|
||||
|
||||
@available(*, deprecated, renamed: "log(level:message:metadata:source:file:function:line:)")
|
||||
public func log(level: Logging.Logger.Level, message: Logging.Logger.Message, metadata: Logging.Logger.Metadata?, file: String, function: String, line: UInt) {
|
||||
/// This implementation obtains the source from the `file` parameter
|
||||
self.log(level: level,
|
||||
message: message,
|
||||
metadata: metadata,
|
||||
|
||||
+955
-39
File diff suppressed because it is too large.
Load diff
@@ -63,7 +63,7 @@ private struct OldSchoolLogHandler: LogHandler {
|
||||
let recorder: Recorder
|
||||
|
||||
func make(label: String) -> LogHandler {
|
||||
return TestLogHandler(label: label, config: self.config, recorder: self.recorder)
|
||||
return TestLogHandler(label: label, config: self.config, recorder: self.recorder, metadataProvider: LoggingSystem.metadataProvider)
|
||||
}
|
||||
|
||||
func log(level: Logger.Level, message: Logger.Message, metadata: Logger.Metadata?, file: String, function: String, line: UInt) {
|
||||
|
||||
@@ -18,7 +18,7 @@ class GlobalLoggerTest: XCTestCase {
|
||||
func test1() throws {
|
||||
// bootstrap with our test logging impl
|
||||
let logging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal(logging.make)
|
||||
LoggingSystem.bootstrapInternal(logging.make(label:metadataProvider:))
|
||||
|
||||
// change test logging config to log traces and above
|
||||
logging.config.set(value: Logger.Level.debug)
|
||||
@@ -45,7 +45,7 @@ class GlobalLoggerTest: XCTestCase {
|
||||
func test2() throws {
|
||||
// bootstrap with our test logging impl
|
||||
let logging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal(logging.make)
|
||||
LoggingSystem.bootstrapInternal(logging.make(label:metadataProvider:))
|
||||
|
||||
// change test logging config to log errors and above
|
||||
logging.config.set(value: Logger.Level.error)
|
||||
@@ -72,7 +72,7 @@ class GlobalLoggerTest: XCTestCase {
|
||||
func test3() throws {
|
||||
// bootstrap with our test logging impl
|
||||
let logging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal(logging.make)
|
||||
LoggingSystem.bootstrapInternal(logging.make(label:metadataProvider:))
|
||||
|
||||
// change test logging config
|
||||
logging.config.set(value: .warning)
|
||||
|
||||
@@ -18,7 +18,7 @@ class LocalLoggerTest: XCTestCase {
|
||||
func test1() throws {
|
||||
// bootstrap with our test logging impl
|
||||
let logging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal(logging.make)
|
||||
LoggingSystem.bootstrapInternal(logging.make(label:metadataProvider:))
|
||||
|
||||
// change test logging config to log traces and above
|
||||
logging.config.set(value: Logger.Level.debug)
|
||||
@@ -46,7 +46,7 @@ class LocalLoggerTest: XCTestCase {
|
||||
func test2() throws {
|
||||
// bootstrap with our test logging impl
|
||||
let logging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal(logging.make)
|
||||
LoggingSystem.bootstrapInternal(logging.make(label:metadataProvider:))
|
||||
|
||||
// change test logging config to log errors and above
|
||||
logging.config.set(value: Logger.Level.error)
|
||||
|
||||
@@ -44,6 +44,15 @@ extension LoggingTest {
|
||||
("testLogsEmittedFromSubdirectoryGetCorrectModuleInNewerSwifts", testLogsEmittedFromSubdirectoryGetCorrectModuleInNewerSwifts),
|
||||
("testLogMessageWithStringInterpolation", testLogMessageWithStringInterpolation),
|
||||
("testLoggingAString", testLoggingAString),
|
||||
("testLoggingCallsMetadataProviderWithTaskLocalBaggage", testLoggingCallsMetadataProviderWithTaskLocalBaggage),
|
||||
("testLoggingCallsMetadataProviderWithExplicitlyPassedBaggage", testLoggingCallsMetadataProviderWithExplicitlyPassedBaggage),
|
||||
("testLoggingMergesOneOffMetadataWithProvidedMetadataFromTaskLocalBaggage", testLoggingMergesOneOffMetadataWithProvidedMetadataFromTaskLocalBaggage),
|
||||
("testLoggingMergesOneOffMetadataWithProvidedMetadataFromExplicitlyPassedBaggage", testLoggingMergesOneOffMetadataWithProvidedMetadataFromExplicitlyPassedBaggage),
|
||||
("testLoggingPrefersExplicitBaggageOverTaskLocal", testLoggingPrefersExplicitBaggageOverTaskLocal),
|
||||
("testLoggingWithExplicitlyPassedNilBaggageDoesNotPickUpTaskLocalBaggage", testLoggingWithExplicitlyPassedNilBaggageDoesNotPickUpTaskLocalBaggage),
|
||||
("testMultiplexMetadataProviderMergesInSpecifiedOrder", testMultiplexMetadataProviderMergesInSpecifiedOrder),
|
||||
("testLoggerWithoutFactoryOverrideDefaultsToUsingLoggingSystemMetadataProvider", testLoggerWithoutFactoryOverrideDefaultsToUsingLoggingSystemMetadataProvider),
|
||||
("testLoggerWithFactoryOverrideDefaultsToUsingLoggingSystemMetadataProvider", testLoggerWithFactoryOverrideDefaultsToUsingLoggingSystemMetadataProvider),
|
||||
("testMultiplexerIsValue", testMultiplexerIsValue),
|
||||
("testLoggerWithGlobalOverride", testLoggerWithGlobalOverride),
|
||||
("testLogLevelCases", testLogLevelCases),
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import InstrumentationBaggage
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Logging API open source project
|
||||
@@ -26,7 +27,7 @@ class LoggingTest: XCTestCase {
|
||||
func testAutoclosure() throws {
|
||||
// bootstrap with our test logging impl
|
||||
let logging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal(logging.make)
|
||||
LoggingSystem.bootstrapInternal(logging.make(label:metadataProvider:))
|
||||
|
||||
var logger = Logger(label: "test")
|
||||
logger.logLevel = .info
|
||||
@@ -230,7 +231,7 @@ class LoggingTest: XCTestCase {
|
||||
|
||||
func testDictionaryMetadata() {
|
||||
let testLogging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal(testLogging.make)
|
||||
LoggingSystem.bootstrapInternal(testLogging.make(label:metadataProvider:))
|
||||
|
||||
var logger = Logger(label: "\(#function)")
|
||||
logger[metadataKey: "foo"] = ["bar": "buz"]
|
||||
@@ -246,7 +247,7 @@ class LoggingTest: XCTestCase {
|
||||
|
||||
func testListMetadata() {
|
||||
let testLogging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal(testLogging.make)
|
||||
LoggingSystem.bootstrapInternal(testLogging.make(label:metadataProvider:))
|
||||
|
||||
var logger = Logger(label: "\(#function)")
|
||||
logger[metadataKey: "foo"] = ["bar", "buz"]
|
||||
@@ -289,7 +290,7 @@ class LoggingTest: XCTestCase {
|
||||
|
||||
func testStringConvertibleMetadata() {
|
||||
let testLogging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal(testLogging.make)
|
||||
LoggingSystem.bootstrapInternal(testLogging.make(label:metadataProvider:))
|
||||
var logger = Logger(label: "\(#function)")
|
||||
|
||||
logger[metadataKey: "foo"] = .stringConvertible("raw-string")
|
||||
@@ -309,7 +310,7 @@ class LoggingTest: XCTestCase {
|
||||
|
||||
func testAutoClosuresAreNotForcedUnlessNeeded() {
|
||||
let testLogging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal(testLogging.make)
|
||||
LoggingSystem.bootstrapInternal(testLogging.make(label:metadataProvider:))
|
||||
|
||||
var logger = Logger(label: "\(#function)")
|
||||
logger.logLevel = .error
|
||||
@@ -323,7 +324,7 @@ class LoggingTest: XCTestCase {
|
||||
|
||||
func testLocalMetadata() {
|
||||
let testLogging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal(testLogging.make)
|
||||
LoggingSystem.bootstrapInternal(testLogging.make(label:metadataProvider:))
|
||||
|
||||
var logger = Logger(label: "\(#function)")
|
||||
logger.info("hello world!", metadata: ["foo": "bar"])
|
||||
@@ -364,7 +365,7 @@ class LoggingTest: XCTestCase {
|
||||
|
||||
func testAllLogLevelsExceptCriticalCanBeBlocked() {
|
||||
let testLogging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal(testLogging.make)
|
||||
LoggingSystem.bootstrapInternal(testLogging.make(label:metadataProvider:))
|
||||
|
||||
var logger = Logger(label: "\(#function)")
|
||||
logger.logLevel = .critical
|
||||
@@ -388,7 +389,7 @@ class LoggingTest: XCTestCase {
|
||||
|
||||
func testAllLogLevelsWork() {
|
||||
let testLogging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal(testLogging.make)
|
||||
LoggingSystem.bootstrapInternal(testLogging.make(label:metadataProvider:))
|
||||
|
||||
var logger = Logger(label: "\(#function)")
|
||||
logger.logLevel = .trace
|
||||
@@ -412,7 +413,7 @@ class LoggingTest: XCTestCase {
|
||||
|
||||
func testAllLogLevelByFunctionRefWithSource() {
|
||||
let testLogging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal(testLogging.make)
|
||||
LoggingSystem.bootstrapInternal(testLogging.make(label:metadataProvider:))
|
||||
|
||||
var logger = Logger(label: "\(#function)")
|
||||
logger.logLevel = .trace
|
||||
@@ -444,7 +445,7 @@ class LoggingTest: XCTestCase {
|
||||
|
||||
func testAllLogLevelByFunctionRefWithoutSource() {
|
||||
let testLogging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal(testLogging.make)
|
||||
LoggingSystem.bootstrapInternal(testLogging.make(label:metadataProvider:))
|
||||
|
||||
var logger = Logger(label: "\(#function)")
|
||||
logger.logLevel = .trace
|
||||
@@ -461,18 +462,18 @@ class LoggingTest: XCTestCase {
|
||||
trace("yes: trace", [:], #fileID, #function, #line)
|
||||
debug("yes: debug", [:], #fileID, #function, #line)
|
||||
info("yes: info", [:], #fileID, #function, #line)
|
||||
notice("yes: notice", [:], #fileID, #function, #line)
|
||||
notice("yes: notice", [:], #fileID, #function, #line)
|
||||
warning("yes: warning", [:], #fileID, #function, #line)
|
||||
error("yes: error", [:], #fileID, #function, #line)
|
||||
critical("yes: critical", [:], #fileID, #function, #line)
|
||||
#else
|
||||
trace("yes: trace", [:], #file, #function, #line)
|
||||
debug("yes: debug", [:], #file, #function, #line)
|
||||
info("yes: info", [:], #file, #function, #line)
|
||||
notice("yes: notice", [:], #file, #function, #line)
|
||||
warning("yes: warning", [:], #file, #function, #line)
|
||||
error("yes: error", [:], #file, #function, #line)
|
||||
critical("yes: critical", [:], #file, #function, #line)
|
||||
trace("yes: trace", [:], nil, #file, #function, #line)
|
||||
debug("yes: debug", [:], nil, #file, #function, #line)
|
||||
info("yes: info", [:], nil, #file, #function, #line)
|
||||
notice("yes: notice", [:], nil, #file, #function, #line)
|
||||
warning("yes: warning", [:], nil, #file, #function, #line)
|
||||
error("yes: error", [:], nil, #file, #function, #line)
|
||||
critical("yes: critical", [:], nil, #file, #function, #line)
|
||||
#endif
|
||||
|
||||
testLogging.history.assertExist(level: .trace, message: "yes: trace")
|
||||
@@ -486,7 +487,7 @@ class LoggingTest: XCTestCase {
|
||||
|
||||
func testLogsEmittedFromSubdirectoryGetCorrectModuleInNewerSwifts() {
|
||||
let testLogging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal(testLogging.make)
|
||||
LoggingSystem.bootstrapInternal(testLogging.make(label:metadataProvider:))
|
||||
|
||||
var logger = Logger(label: "\(#function)")
|
||||
logger.logLevel = .trace
|
||||
@@ -510,7 +511,7 @@ class LoggingTest: XCTestCase {
|
||||
|
||||
func testLogMessageWithStringInterpolation() {
|
||||
let testLogging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal(testLogging.make)
|
||||
LoggingSystem.bootstrapInternal(testLogging.make(label:metadataProvider:))
|
||||
|
||||
var logger = Logger(label: "\(#function)")
|
||||
logger.logLevel = .debug
|
||||
@@ -523,7 +524,7 @@ class LoggingTest: XCTestCase {
|
||||
|
||||
func testLoggingAString() {
|
||||
let testLogging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal(testLogging.make)
|
||||
LoggingSystem.bootstrapInternal(testLogging.make(label:metadataProvider:))
|
||||
|
||||
var logger = Logger(label: "\(#function)")
|
||||
logger.logLevel = .debug
|
||||
@@ -537,6 +538,237 @@ class LoggingTest: XCTestCase {
|
||||
testLogging.history.assertExist(level: .debug, message: "hello world!")
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
func testLoggingCallsMetadataProviderWithTaskLocalBaggage() throws {
|
||||
#if swift(>=5.5) && canImport(_Concurrency)
|
||||
let logging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal(logging.make(label:metadataProvider:))
|
||||
|
||||
var logger = Logger(label: #function, metadataProvider: .init { baggage in
|
||||
guard let baggage = baggage, let testID = baggage[TestIDKey.self] else {
|
||||
XCTFail("Expected Baggage to be passed along to the metadata provider.")
|
||||
return nil
|
||||
}
|
||||
return ["provider": .string(testID)]
|
||||
})
|
||||
logger.logLevel = .trace
|
||||
|
||||
var baggage = Baggage.topLevel
|
||||
baggage[TestIDKey.self] = "42"
|
||||
|
||||
Baggage.$current.withValue(baggage) {
|
||||
logger.trace("test")
|
||||
logger.debug("test")
|
||||
logger.info("test")
|
||||
logger.notice("test")
|
||||
logger.warning("test")
|
||||
logger.error("test")
|
||||
logger.critical("test")
|
||||
}
|
||||
|
||||
logging.history.assertExist(level: .trace, message: "test", metadata: ["provider": "42"])
|
||||
logging.history.assertExist(level: .debug, message: "test", metadata: ["provider": "42"])
|
||||
logging.history.assertExist(level: .info, message: "test", metadata: ["provider": "42"])
|
||||
logging.history.assertExist(level: .notice, message: "test", metadata: ["provider": "42"])
|
||||
logging.history.assertExist(level: .warning, message: "test", metadata: ["provider": "42"])
|
||||
logging.history.assertExist(level: .error, message: "test", metadata: ["provider": "42"])
|
||||
logging.history.assertExist(level: .critical, message: "test", metadata: ["provider": "42"])
|
||||
|
||||
enum TestIDKey: BaggageKey {
|
||||
typealias Value = String
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
func testLoggingCallsMetadataProviderWithExplicitlyPassedBaggage() throws {
|
||||
let logging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal(logging.make(label:metadataProvider:))
|
||||
|
||||
var logger = Logger(label: #function, metadataProvider: .init { baggage in
|
||||
guard let baggage = baggage, let testID = baggage[TestIDKey.self] else {
|
||||
XCTFail("Expected Baggage to be passed along to the metadata provider.")
|
||||
return nil
|
||||
}
|
||||
return ["provider": .string(testID)]
|
||||
})
|
||||
logger.logLevel = .trace
|
||||
|
||||
var baggage = Baggage.topLevel
|
||||
baggage[TestIDKey.self] = "42"
|
||||
|
||||
logger.trace("test", baggage: baggage)
|
||||
logger.debug("test", baggage: baggage)
|
||||
logger.info("test", baggage: baggage)
|
||||
logger.notice("test", baggage: baggage)
|
||||
logger.warning("test", baggage: baggage)
|
||||
logger.error("test", baggage: baggage)
|
||||
logger.critical("test", baggage: baggage)
|
||||
|
||||
logging.history.assertExist(level: .trace, message: "test", metadata: ["provider": "42"])
|
||||
logging.history.assertExist(level: .debug, message: "test", metadata: ["provider": "42"])
|
||||
logging.history.assertExist(level: .info, message: "test", metadata: ["provider": "42"])
|
||||
logging.history.assertExist(level: .notice, message: "test", metadata: ["provider": "42"])
|
||||
logging.history.assertExist(level: .warning, message: "test", metadata: ["provider": "42"])
|
||||
logging.history.assertExist(level: .error, message: "test", metadata: ["provider": "42"])
|
||||
logging.history.assertExist(level: .critical, message: "test", metadata: ["provider": "42"])
|
||||
|
||||
enum TestIDKey: BaggageKey {
|
||||
typealias Value = String
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
func testLoggingMergesOneOffMetadataWithProvidedMetadataFromTaskLocalBaggage() throws {
|
||||
#if swift(>=5.5) && canImport(_Concurrency)
|
||||
let logging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal(logging.make(label:metadataProvider:))
|
||||
|
||||
let logger = Logger(label: #function, metadataProvider: .init { _ in
|
||||
[
|
||||
"common": "provider",
|
||||
"provider": "42",
|
||||
]
|
||||
})
|
||||
|
||||
Baggage.$current.withValue(.topLevel) {
|
||||
logger.log(level: .info, "test", metadata: ["one-off": "42", "common": "one-off"])
|
||||
}
|
||||
|
||||
logging.history.assertExist(level: .info,
|
||||
message: "test",
|
||||
metadata: ["common": "one-off", "one-off": "42", "provider": "42"])
|
||||
#endif
|
||||
}
|
||||
|
||||
func testLoggingMergesOneOffMetadataWithProvidedMetadataFromExplicitlyPassedBaggage() throws {
|
||||
let logging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal(logging.make(label:metadataProvider:))
|
||||
|
||||
let logger = Logger(label: #function, metadataProvider: .init { _ in
|
||||
[
|
||||
"common": "provider",
|
||||
"provider": "42",
|
||||
]
|
||||
})
|
||||
|
||||
logger.log(level: .info, "test", metadata: ["one-off": "42", "common": "one-off"], baggage: .explicitlyPassed(.topLevel))
|
||||
|
||||
logging.history.assertExist(level: .info,
|
||||
message: "test",
|
||||
metadata: ["common": "one-off", "one-off": "42", "provider": "42"])
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
func testLoggingPrefersExplicitBaggageOverTaskLocal() {
|
||||
#if swift(>=5.5) && canImport(_Concurrency)
|
||||
let logging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal(logging.make(label:metadataProvider:))
|
||||
|
||||
var logger = Logger(label: #function, metadataProvider: .init { baggage in
|
||||
guard let baggage = baggage, let testID = baggage[TestIDKey.self] else {
|
||||
XCTFail("Expected Baggage to be passed along to the metadata provider.")
|
||||
return nil
|
||||
}
|
||||
return ["provider": .string(testID)]
|
||||
})
|
||||
logger.logLevel = .trace
|
||||
|
||||
var taskLocalBaggage = Baggage.topLevel
|
||||
taskLocalBaggage[TestIDKey.self] = "task-local"
|
||||
|
||||
var explicitBaggage = Baggage.topLevel
|
||||
explicitBaggage[TestIDKey.self] = "explicit"
|
||||
|
||||
Baggage.$current.withValue(taskLocalBaggage) {
|
||||
logger.trace("test", metadata: ["one-off": "42"], baggage: explicitBaggage)
|
||||
logger.debug("test", metadata: ["one-off": "42"], baggage: explicitBaggage)
|
||||
logger.info("test", metadata: ["one-off": "42"], baggage: explicitBaggage)
|
||||
logger.notice("test", metadata: ["one-off": "42"], baggage: explicitBaggage)
|
||||
logger.warning("test", metadata: ["one-off": "42"], baggage: explicitBaggage)
|
||||
logger.error("test", metadata: ["one-off": "42"], baggage: explicitBaggage)
|
||||
logger.critical("test", metadata: ["one-off": "42"], baggage: explicitBaggage)
|
||||
}
|
||||
|
||||
logging.history.assertExist(level: .trace, message: "test", metadata: ["one-off": "42", "provider": "explicit"])
|
||||
logging.history.assertExist(level: .debug, message: "test", metadata: ["one-off": "42", "provider": "explicit"])
|
||||
logging.history.assertExist(level: .info, message: "test", metadata: ["one-off": "42", "provider": "explicit"])
|
||||
logging.history.assertExist(level: .notice, message: "test", metadata: ["one-off": "42", "provider": "explicit"])
|
||||
logging.history.assertExist(level: .warning, message: "test", metadata: ["one-off": "42", "provider": "explicit"])
|
||||
logging.history.assertExist(level: .error, message: "test", metadata: ["one-off": "42", "provider": "explicit"])
|
||||
logging.history.assertExist(level: .critical, message: "test", metadata: ["one-off": "42", "provider": "explicit"])
|
||||
|
||||
enum TestIDKey: BaggageKey {
|
||||
typealias Value = String
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
func testLoggingWithExplicitlyPassedNilBaggageDoesNotPickUpTaskLocalBaggage() {
|
||||
#if swift(>=5.5) && canImport(_Concurrency)
|
||||
let logging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal(logging.make(label:metadataProvider:))
|
||||
|
||||
let logger = Logger(label: #function, metadataProvider: .init { baggage in
|
||||
XCTAssertNil(baggage)
|
||||
return ["provider": .string("42")]
|
||||
})
|
||||
|
||||
Baggage.$current.withValue(.topLevel) {
|
||||
logger.log(level: .info, "test", baggage: .ignore)
|
||||
}
|
||||
|
||||
logging.history.assertExist(level: .info, message: "test", metadata: ["provider": "42"])
|
||||
#endif
|
||||
}
|
||||
|
||||
func testMultiplexMetadataProviderMergesInSpecifiedOrder() {
|
||||
let logging = TestLogging()
|
||||
|
||||
let providerA = Logger.MetadataProvider { _ in ["provider": "a", "a": "foo"] }
|
||||
let providerB = Logger.MetadataProvider { _ in ["provider": "b", "b": "bar"] }
|
||||
let logger = Logger(label: #function,
|
||||
factory: { label in
|
||||
logging.make(label: label, metadataProvider: .multiplex([providerA, providerB]))
|
||||
})
|
||||
|
||||
logger.log(level: .info, "test", metadata: ["one-off": "42"])
|
||||
|
||||
logging.history.assertExist(level: .info,
|
||||
message: "test",
|
||||
metadata: ["provider": "b", "a": "foo", "b": "bar", "one-off": "42"])
|
||||
}
|
||||
|
||||
func testLoggerWithoutFactoryOverrideDefaultsToUsingLoggingSystemMetadataProvider() {
|
||||
let logging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal { label in
|
||||
logging.make(label: label, metadataProvider: .init({ _ in ["provider": "42"] }))
|
||||
}
|
||||
|
||||
let logger = Logger(label: #function)
|
||||
|
||||
logger.log(level: .info, "test", metadata: ["one-off": "42"])
|
||||
|
||||
logging.history.assertExist(level: .info,
|
||||
message: "test",
|
||||
metadata: ["provider": "42", "one-off": "42"])
|
||||
}
|
||||
|
||||
func testLoggerWithFactoryOverrideDefaultsToUsingLoggingSystemMetadataProvider() {
|
||||
let logging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal(
|
||||
metadataProvider: .init({ _ in ["provider": "42"] }),
|
||||
logging.make(label:metadataProvider:))
|
||||
|
||||
let logger = Logger(label: #function, factory: logging.make(label:metadataProvider:))
|
||||
|
||||
logger.log(level: .info, "test", metadata: ["one-off": "42"])
|
||||
|
||||
logging.history.assertExist(level: .info,
|
||||
message: "test",
|
||||
metadata: ["provider": "42", "one-off": "42"])
|
||||
}
|
||||
|
||||
func testMultiplexerIsValue() {
|
||||
let multi = MultiplexLogHandler([StreamLogHandler.standardOutput(label: "x"), StreamLogHandler.standardOutput(label: "y")])
|
||||
LoggingSystem.bootstrapInternal { _ in
|
||||
@@ -863,7 +1095,7 @@ class LoggingTest: XCTestCase {
|
||||
}
|
||||
// bootstrap with our test logging impl
|
||||
let logging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal(logging.make)
|
||||
LoggingSystem.bootstrapInternal(logging.make(label:metadataProvider:))
|
||||
|
||||
var logger = Logger(label: "test")
|
||||
logger.logLevel = .error
|
||||
|
||||
@@ -19,7 +19,7 @@ class MDCTest: XCTestCase {
|
||||
func test1() throws {
|
||||
// bootstrap with our test logger
|
||||
let logging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal(logging.make)
|
||||
LoggingSystem.bootstrapInternal(logging.make(label:metadataProvider:))
|
||||
|
||||
// run the program
|
||||
MDC.global["foo"] = "bar"
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
import Foundation
|
||||
@testable import Logging
|
||||
import InstrumentationBaggage
|
||||
import XCTest
|
||||
#if os(Windows)
|
||||
import WinSDK
|
||||
@@ -23,7 +24,19 @@ internal struct TestLogging {
|
||||
private let recorder = Recorder() // shared among loggers
|
||||
|
||||
func make(label: String) -> LogHandler {
|
||||
return TestLogHandler(label: label, config: self.config, recorder: self.recorder)
|
||||
return TestLogHandler(
|
||||
label: label,
|
||||
config: self.config,
|
||||
recorder: self.recorder,
|
||||
metadataProvider: LoggingSystem.metadataProvider)
|
||||
}
|
||||
|
||||
func make(label: String, metadataProvider: Logger.MetadataProvider?) -> LogHandler {
|
||||
return TestLogHandler(
|
||||
label: label,
|
||||
config: self.config,
|
||||
recorder: self.recorder,
|
||||
metadataProvider: metadataProvider)
|
||||
}
|
||||
|
||||
var config: Config { return self._config }
|
||||
@@ -36,16 +49,48 @@ internal struct TestLogHandler: LogHandler {
|
||||
private var logger: Logger // the actual logger
|
||||
|
||||
let label: String
|
||||
init(label: String, config: Config, recorder: Recorder) {
|
||||
private let metadataProvider: Logger.MetadataProvider?
|
||||
|
||||
init(label: String, config: Config, recorder: Recorder, metadataProvider: Logger.MetadataProvider?) {
|
||||
self.label = label
|
||||
self.config = config
|
||||
self.recorder = recorder
|
||||
self.logger = Logger(label: "test", StreamLogHandler.standardOutput(label: label))
|
||||
self.logger = Logger(label: "test", StreamLogHandler.standardOutput(label: label, metadataProvider: nil))
|
||||
self.logger.logLevel = .debug
|
||||
self.metadataProvider = metadataProvider
|
||||
}
|
||||
|
||||
func log(level: Logger.Level, message: Logger.Message, metadata: Logger.Metadata?, source: String, file: String, function: String, line: UInt) {
|
||||
let metadata = (self._metadataSet ? self.metadata : MDC.global.metadata).merging(metadata ?? [:], uniquingKeysWith: { _, new in new })
|
||||
func log(level: Logger.Level,
|
||||
message: Logger.Message,
|
||||
metadata explicitMetadata: Logger.Metadata?,
|
||||
baggage whereIsTheBaggage: Logger.BaggageStrategy,
|
||||
source: String,
|
||||
file: String, function: String, line: UInt) {
|
||||
var baggage: Baggage?
|
||||
switch whereIsTheBaggage {
|
||||
case .explicitlyPassed(let b):
|
||||
baggage = b
|
||||
case .taskLocal:
|
||||
#if swift(>=5.5) && canImport(_Concurrency)
|
||||
if #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) {
|
||||
baggage = .current
|
||||
} else {
|
||||
baggage = nil
|
||||
}
|
||||
#else
|
||||
baggage = nil
|
||||
#endif
|
||||
case .ignore:
|
||||
baggage = nil
|
||||
}
|
||||
|
||||
var metadata = metadataProvider?.provideMetadata(from: baggage) ?? [:]
|
||||
metadata = metadata.merging(
|
||||
(self._metadataSet ? self.metadata : MDC.global.metadata).merging(metadata ?? [:], uniquingKeysWith: { _, new in new }),
|
||||
uniquingKeysWith: { _, new in new })
|
||||
metadata = metadata.merging(
|
||||
explicitMetadata ?? [:], uniquingKeysWith: { _, new in new })
|
||||
|
||||
self.logger.log(level: level, message, metadata: metadata, source: source, file: file, function: function, line: line)
|
||||
self.recorder.record(level: level, metadata: metadata, message: message, source: source)
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ class SendableTest: XCTestCase {
|
||||
#if compiler(>=5.6)
|
||||
func testSendableLogger() async {
|
||||
let testLogging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal(testLogging.make)
|
||||
LoggingSystem.bootstrapInternal(testLogging.make(label:metadataProvider:))
|
||||
|
||||
let logger = Logger(label: "test")
|
||||
let message1 = Logger.Message(stringLiteral: "critical 1")
|
||||
|
||||
@@ -0,0 +1,489 @@
|
||||
# Metadata Providers
|
||||
|
||||
Authors: [Moritz Lang](https://github.com/slashmo), [Konrad 'ktoso' Malawski](https://github.com/ktoso)
|
||||
|
||||
## Introduction
|
||||
|
||||
While global metadata attributes may be manually set on a `LogHandler` level, there's currently no way of reliably providing contextual, automatically propagated, metadata when logging with swift-log.
|
||||
|
||||
## Motivation
|
||||
|
||||
To benefit from tools such as [Distributed Tracing](https://github.com/apple/swift-distributed-tracing) it is necessary for libraries to make use of the trace information.
|
||||
|
||||
Most notably, loggers should participate in tracing by including some trace metadata (such as e.g. a `trace-id`) when logging, as it transparently enables developers to benefit from log correlation using those IDs.
|
||||
|
||||
Today, the only supported way of providing such metadata is to pass them along to each log call explicitly:
|
||||
|
||||
```swift
|
||||
logger.info("first this ...", metadata: ["trace-id": MyTracingLibrary.currentTraceID])
|
||||
logger.info("... now this", metadata: ["trace-id": MyTracingLibrary.currentTraceID])
|
||||
```
|
||||
|
||||
This comes with a couple of downsides:
|
||||
|
||||
### Error-prone and repetitive
|
||||
|
||||
It's easy to forget passing this metadata to _all_ log statements, resulting in an inconsistent debugging experience as these log statements cannot be found using correlation IDs.
|
||||
|
||||
The repetitiveness and verboseness of logging multiple metadata in-line quickly becomes annoying and vastly decreases the signal-to-noise ratio of Swift code trying to be a good citizen and making use of log correlation techniques such as distributed tracing.
|
||||
|
||||
### Impossible to implement for libraries
|
||||
|
||||
A large portion of logs are not generated by the end-user but by libraries such as AsyncHTTPClient, Vapor etc.
|
||||
These libraries, by design, don't know about the specific metadata keys that should be included in the logs.
|
||||
Those keys are after all runtime dependent, and may change depending on what tracing system is configured by the end user.
|
||||
|
||||
For example, a specific `Tracer` implementation would use a type representing a trace ID, and has a way of extracting
|
||||
that trace ID from a `Baggage`. But other libraries can't know about this _specific_ trace ID and therefore would not be
|
||||
able to pass such values along to their log statements.
|
||||
|
||||
## Proposed solution
|
||||
|
||||
To support this kind of runtime-generated metadata in `swift-log`, we need to extend the logging APIs in an open-ended way, to allow any kinds of metadata to be provided from the asynchronous context.
|
||||
|
||||
To solve this, we propose the extension of swift-log APIs with a new concept: _metadata providers_.
|
||||
|
||||
`MetadataProvider` is struct nested in the `Logger` type, sitting alongside `MetadataValue`
|
||||
and the `Metadata` typealias. It has a single property `metadata` which is a closure from `Baggage?` to `Metadata?`:
|
||||
|
||||
```swift
|
||||
extension Logger {
|
||||
public struct MetadataProvider: Sendable {
|
||||
public var metadata: @Sendable (_ baggage: Baggage?) -> Metadata?
|
||||
|
||||
public init(metadata: @escaping @Sendable (Baggage?) -> Metadata?) {
|
||||
self.metadata = metadata
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Defining a `MetadataProvider`
|
||||
|
||||
While `MetadataProvider`s can be created in an ad-hoc fashion, the struct may be used as a namespace
|
||||
to define providers in. A Tracing library e.g. could expose its metadata provider via a static property
|
||||
on `Logger.MetadataProvider`:
|
||||
|
||||
```swift
|
||||
extension Logger.MetadataProvider {
|
||||
static let tracer = Logger.MetadataProvider { baggage in
|
||||
guard let spanContext = baggage?.spanContext else { return nil }
|
||||
return [
|
||||
"traceID": "\(spanContext.traceID)",
|
||||
"spanID": "\(spanContext.spanID)",
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Using a `MetadataProvider`
|
||||
|
||||
A `MetadataProvider` can be set up either globally, on a boot-strapped logging system:
|
||||
|
||||
```swift
|
||||
LoggingSystem.bootstrap(
|
||||
metadataProvider: .tracer,
|
||||
StreamLogHandler.standardOutput
|
||||
)
|
||||
```
|
||||
|
||||
or, on a specific logger, in case some contexts should extract additional information:
|
||||
|
||||
```swift
|
||||
let logger = Logger(label: "example", metadataProvider: .init { baggage in
|
||||
guard let operationID = baggage?.operationID else { return nil }
|
||||
return ["extra/opID": "\(opID)"]
|
||||
})
|
||||
```
|
||||
|
||||
> NOTE: Setting the metadata provider on the logger directly means the `LoggingSystem` metadata provider
|
||||
> is skipped (if defined), following how an explicitly passed handler `factory`
|
||||
> overrides the `LoggingSystem`s `factory`.
|
||||
|
||||
Once a metadata provider was set up, when a log statement is about to be emitted, the logger will obtain the task-local `Baggage.current`,
|
||||
and pass it to the metadata providers. The providers can then convert specific baggage items into logger metadata as they see fit.
|
||||
|
||||
Those metadata will then be included in the log statement, e.g. like this:
|
||||
|
||||
```swift
|
||||
var baggage = Baggage.topLevel
|
||||
baggage.spanContext = SpanContext()
|
||||
Baggage.$current.withValue(baggage) {
|
||||
test()
|
||||
}
|
||||
|
||||
func test() {
|
||||
log.info("Test", metadata: ["oneOff": "42"])
|
||||
// info [traceID: abc, spanID: 123, onOff: 42] Test
|
||||
}
|
||||
```
|
||||
|
||||
### Multiple `MetadataProvider`s using `MetadataProvider.multiplex(_:)`
|
||||
|
||||
Borrowing the concept from log handlers, metadata providers also have a multiplexing implementation.
|
||||
It is defined as an extension on `MetadataProvider` and is useful in cases where users want to utilize
|
||||
more than one metadata provider at the same time:
|
||||
|
||||
```swift
|
||||
extension Logger.MetadataProvider {
|
||||
public static func multiplex(_ providers: [Logger.MetadataProvider]) -> Logger.MetadataProvider {
|
||||
assert(!providers.isEmpty, "providers MUST NOT be empty")
|
||||
return Logger.MetadataProvider { baggage in
|
||||
providers.reduce(into: nil) { metadata, provider in
|
||||
if let providedMetadata = provider.metadata(baggage) {
|
||||
if metadata != nil {
|
||||
metadata!.merge(providedMetadata, uniquingKeysWith: { _, rhs in rhs })
|
||||
} else {
|
||||
metadata = providedMetadata
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Metadata keys are unique, so in case multiple metadata providers return the same key,
|
||||
the last provider in the array "wins" and provides the value.
|
||||
|
||||
### Proposal: Using `Baggage` as the execution context dependent metadata container
|
||||
|
||||
We propose that swift-log should use [Swift Distributed Tracing Baggage](https://github.com/apple/swift-distributed-tracing-baggage) for its contextual metadata propagation type, meaning that swift-log would depend on this package.
|
||||
|
||||
The `Baggage` type is modeled after the [Propagation format for distributed context: Baggage](https://www.w3.org/TR/baggage/), a W3C working draft, and is intended for all kinds of instrumentation of Swift applications both within and across processes. It is also used by [Swift Distributed Tracing](https://github.com/apple/swift-distributed-tracing), however it is usable even without tracing infrastructure. The baggage package contains the single `Baggage` type, and is expected to have a stable, unchanging API, fit for swift-log to depend upon.
|
||||
|
||||
> NOTE: We could potentially even rename the baggage package, if the tracing wording in it is causing confusion here. But realistically, this is its primary purpose: to enable tracing in logging systems, so we think swift-log depending on `swift-distributed-tracing-baggage` is fine.
|
||||
|
||||
To start using contextual metadata, end-users configure a metadata provider on the entire logging system or on a specific `Logger` via a new initializer parameter:
|
||||
|
||||
```swift
|
||||
let logger = Logger(label: "example", metadataProvider: { baggage in
|
||||
// extract values from baggage
|
||||
guard let traceID = baggage?[TraceIDKey.self] else { return nil }
|
||||
// convert values into logging metadata
|
||||
return ["trace-id": traceID]
|
||||
})
|
||||
```
|
||||
|
||||
### Task-local Baggage
|
||||
|
||||
> NOTE: See [SE-0311](https://github.com/apple/swift-evolution/blob/main/proposals/0311-task-locals.md) for an explanation of task-local values in Swift.
|
||||
|
||||
Once configured, the `log` function and its log-level-based counterparts will utilize this provider by merging the provided metadata with the one-off metadata within the log statement.
|
||||
|
||||
Since `Baggage` is propagaged as a task-local, we do not change any of the existing method signatures, and the baggage is picked up inside the log method:
|
||||
|
||||
```swift
|
||||
extension Logger {
|
||||
@inlinable
|
||||
func log(level: Logger.Level,
|
||||
_ message: @autoclosure () -> Logger.Message,
|
||||
metadata: @autoclosure () -> Logger.Metadata? = nil,
|
||||
source: @autoclosure () -> String? = nil,
|
||||
file: String = #fileID, function: String = #function, line: UInt = #line) {
|
||||
let effectiveBaggage: Baggage? = {
|
||||
guard baggage == nil else { return baggage }
|
||||
|
||||
let taskLocalBaggage: Baggage?
|
||||
#if compiler(>=5.5) && canImport(_Concurrency)
|
||||
if #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *), self.metadataProvider != nil {
|
||||
taskLocalBaggage = Baggage.current
|
||||
} else {
|
||||
taskLocalBaggage = nil
|
||||
}
|
||||
#else
|
||||
taskLocalBaggage = nil
|
||||
#endif
|
||||
|
||||
return taskLocalBaggage
|
||||
}()
|
||||
let providerMetadata = metadataProvider?.metadata(effectiveBaggage)
|
||||
let metadata: Metadata? = {
|
||||
guard let metadata = metadata(), !metadata.isEmpty else { return providerMetadata }
|
||||
guard let providerMetadata = providerMetadata else { return metadata }
|
||||
return providerMetadata.merging(metadata, uniquingKeysWith: { _, oneOffMetadata in oneOffMetadata })
|
||||
}()
|
||||
|
||||
self.handler.log(level: level,
|
||||
message: message(),
|
||||
metadata: metadata,
|
||||
source: source() ?? Logger.currentModule(fileID: (file)),
|
||||
file: file, function: function, line: line)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Note, that the task-local lookup is only performed when the log message is about to be emitted. No task-local or thread-local lookups are performed when the log level is lower than the level of the current statement or in case no metadata provider was set up.
|
||||
|
||||
We also introduce another overload of the log (and trace/debug/info/notice/warning/error/critical) method, which allows libraries to pass a baggage explicitly if they need to (or, disable baggage value extraction by passing `nil` as the value):
|
||||
|
||||
```swift
|
||||
extension Logger {
|
||||
@inlinable
|
||||
public func log(level: Logger.Level,
|
||||
_ message: @autoclosure () -> Logger.Message,
|
||||
metadata: @autoclosure () -> Logger.Metadata? = nil,
|
||||
baggage: Baggage?,
|
||||
source: @autoclosure () -> String? = nil,
|
||||
file: String = #fileID, function: String = #function, line: UInt = #line) {
|
||||
if self.logLevel <= level {
|
||||
let providerMetadata = metadataProvider?.metadata(baggage)
|
||||
let metadata: Metadata? = {
|
||||
guard let metadata = metadata(), !metadata.isEmpty else { return providerMetadata }
|
||||
guard let providerMetadata = providerMetadata else { return metadata }
|
||||
return providerMetadata.merging(metadata, uniquingKeysWith: { _, oneOffMetadata in oneOffMetadata })
|
||||
}()
|
||||
|
||||
self.handler.log(level: level,
|
||||
message: message(),
|
||||
metadata: metadata,
|
||||
source: source() ?? Logger.currentModule(fileID: (file)),
|
||||
file: file, function: function, line: line)
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Practical usage of baggage values is as follows:
|
||||
|
||||
```swift
|
||||
var baggage = Baggage.topLevel
|
||||
baggage[TestIDKey.self] = "my-awesome-trace-id"
|
||||
|
||||
Baggage.$current.withValue(baggage) {
|
||||
logger.info("Such logging, wow!", metadata: ["one-off": "example"])
|
||||
// info [my-test-key: my-awesome-trace-id, one-off: example] Such logging, wow!
|
||||
}
|
||||
```
|
||||
|
||||
This has the advantage of not having to specify the global metadata explicitly anymore.
|
||||
|
||||
The task-local baggage is often going to be set by e.g. tracing libraries or frameworks, so end-users do not need to do anything to benefit from tracing,
|
||||
other than setting up the metadata providers when they bootstrap their logging and tracing systems. For example, assuming some imaginary http framework where http requests are forwarded to an actor for handling, all the end-users of this framework would benefit from contextual metadata, propagated with baggage by logging, as usual:
|
||||
|
||||
```swift
|
||||
actor MyHTTPHandler {
|
||||
|
||||
func handle(request: HTTPRequest) async {
|
||||
Logger(label: "inline").info("Handling request!")
|
||||
// info [trace-id: 1234-5678] Handling request!
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This also solves the issue of libraries not being able to include this kind of metadata since it is done automatically in the background, as long as
|
||||
the values are stored inside the task-local `Baggage`.
|
||||
|
||||
### When to use `Baggage` vs. `Logger[metadataKey:]`
|
||||
|
||||
While `Baggage` is context-dependend and changes depending on where the log methods are being called from, the metadata set on a `Logger` is static and not context-dependent. E.g, if you wanted to add things like an instance ID or a subsystem name to a `Logger`, that could be seen as static information and set via `Logger[metadataKey:]`.
|
||||
|
||||
```swift
|
||||
var logger = Logger(label: "org.swift.my-service")
|
||||
logger[metadataKey: "instanceId"] = "123"
|
||||
|
||||
logger.info("Service started.")
|
||||
// [instanceId: 123] Service started.
|
||||
```
|
||||
|
||||
On the other hand, things like a trace ID are dynamic and context-dependent, therefore would be obtained via `Baggage`:
|
||||
|
||||
```swift
|
||||
logger.info("Product fetched.")
|
||||
// [traceId: 42] Product fetched.
|
||||
```
|
||||
|
||||
Inline-metadata is suitable for one-offs such as a `productId` or a `paymentMethod` in an online store service, but are not enough to corralate the following log statements, i.e. tying them both to the same request:
|
||||
|
||||
```swift
|
||||
logger.info("Product fetched.", metadata: ["productId": "42"])
|
||||
logger.info("Product purchased.", metadata: ["paymentMethod": "apple-pay"])
|
||||
|
||||
// [productId: 42] Product fetched.
|
||||
// [paymentMethod: apple-pay] Product fetched.
|
||||
```
|
||||
|
||||
If there was a `Baggage` value with a trace ID surrounding these log statements, they would be automatically correlatable:
|
||||
|
||||
```swift
|
||||
var baggage = Baggage.topLevel
|
||||
baggage.traceID = 42
|
||||
Baggage.$current.withValue(baggage) {
|
||||
logger.info("Product fetched.", metadata: ["productId": "42"])
|
||||
logger.info("Product purchased.", metadata: ["paymentMethod": "apple-pay"])
|
||||
}
|
||||
|
||||
// [trace-id: 42, productId: 42] Product fetched.
|
||||
// [trace-id: 42, paymentMethod: apple-pay] Product fetched.
|
||||
```
|
||||
|
||||
### Using Baggage in callback APIs
|
||||
|
||||
Many libraries which provide `async` APIs, are implemented on top of Swift NIO, or other callback-heavy libraries (e.g. when wrapping existing non-async database libraries or similar).
|
||||
|
||||
The proposed API must work well with such libraries, in the sense that a metadata provider configured by an end-user, should still be useful in such libraries where setting a Task-local baggage is either impossible, or very weird (continiously wrapping every call into "restoring" the current baggage upon every re-entry from a callback):
|
||||
|
||||
```swift
|
||||
class RequestStateMachine: ChannelInboundHandler {
|
||||
let logger: Logger
|
||||
|
||||
func channelActive(context: ChannelHandlerContext) {
|
||||
logger.debug("Channel active.")
|
||||
// debug [trace-id: ???] Channel active.
|
||||
}
|
||||
|
||||
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
|
||||
logger.debug("Received request part.")
|
||||
// debug [trace-id: ???] Received request part.
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
In the above example, we want the logger to capture the trace ID of the task that created `MyChannel`, but the delegate methods are called on the NIO event-loop which doesn't set any task-local `Baggage`.
|
||||
|
||||
We propose the following strategy for such libraries:
|
||||
|
||||
Entry points into such libraries should assume the presence of task-local `Baggage`.
|
||||
This is the same as with tracing -- e.g. a `startWork()` method, does not need to accept a baggage parameter, but simply query `Baggage.current` if in need of any contextual metadata.
|
||||
|
||||
When the library is forced to exit the world of structured concurrency where task-locals work well `*`, they should _get and store_ the current baggage from the user's calling context, e.g. by storing it in a state machine driving class, handler, or actor: `self.baggage = Baggage.current`:
|
||||
|
||||
```swift
|
||||
class RequestStateMachine: ChannelInboundHandler {
|
||||
let logger: Logger
|
||||
var baggage: Baggage?
|
||||
|
||||
init(logger: Logger) {
|
||||
self.logger = logger
|
||||
// in here we can still access the task-local Baggage
|
||||
self.baggage = Baggage.current
|
||||
}
|
||||
|
||||
func channelActive(context: ChannelHandlerContext) {
|
||||
logger.debug("Channel active.", baggage: self.baggage)
|
||||
// debug [trace-id: 42] Channel active.
|
||||
}
|
||||
|
||||
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
|
||||
logger.debug("Received request part.", baggage: self.baggage)
|
||||
// debug [trace-id: 42] Received request part.
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> `*` situations where task-local baggage just works include: plain synchronous methods, asynchronous methods, as all forms of structured concurrency (async lets and task groups), as well as un-structured (but _not_ detached) tasks (created by calling `Task { ... }`).
|
||||
|
||||
The libraries are then free to continue using their callback or delegate-style APIs, and whenever needing to log or restore the baggage they can, either:
|
||||
|
||||
- explicitly pass it to a logger: `log.info("Request finished", metadata: [...], baggage: self.baggage)`
|
||||
- restore the contextual task-local baggage and wrap subsequent calls with: `Baggage.current.withValue(self.baggage) { moreThings() }`
|
||||
|
||||
### Rendering provider metadata only once in performance-critical code
|
||||
|
||||
In some performance-critical code, you may want to render the provider metadata only once. In such cases, you can call the metadata provider explicitly at the point of entry and instead of passing `Baggage` you'd use the `Logger`'s metadata:
|
||||
|
||||
```swift
|
||||
class PerformanceCriticalRequestStateMachine: ChannelInboundHandler {
|
||||
let logger: Logger
|
||||
|
||||
init(logger: Logger) {
|
||||
var logger = logger
|
||||
// in here we can still access the task-local Baggage
|
||||
if let baggage = Baggage.current, let metadataProvider = logger.metadataProvider {
|
||||
let metadata = metadataProvider(baggage)
|
||||
for (key, value) in metadata {
|
||||
logger[metadataKey: key] = value
|
||||
}
|
||||
}
|
||||
self.logger = logger
|
||||
}
|
||||
|
||||
func channelActive(context: ChannelHandlerContext) {
|
||||
logger.debug("Channel active.", baggage: nil)
|
||||
// debug [trace-id: 42] Channel active.
|
||||
}
|
||||
|
||||
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
|
||||
logger.debug("Received request part.", baggage: nil)
|
||||
// debug [trace-id: 42] Received request part.
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Passing `nil` as the `Baggage` will prevent task-local look-ups in these performance sensitive situations.
|
||||
|
||||
> NOTE: Most applications shouldn't need to worry about this and just rely on automatic Baggage propagation using task-locals
|
||||
|
||||
> WARNING: The context-dependent metadata becomes static which makes it hard to recover the dynamic information back into `Baggage`, e.g. if you wanted to create a child span in one of those callbacks.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
### Removing `LogHandler.Metadata` in favor of `Baggage`
|
||||
|
||||
Removing logger metadata is not a good option because it serves a slightly different style of metadata than the baggage.
|
||||
|
||||
Baggage is intended for contextual, task-local, metadata which is _carried across multiple libraries_. The values stored in baggage are well-typed, and must declare keys for accessing values in a baggage, this works well for multiple pieces of an application needing to reach for specific baggage items: everyone aware of the `traceID` key, is able to query the baggage for this key (`baggage.traceID`) and obtain a well-typed value. This comes with a higher cost on declaring keys though, as well as a global namespace for those - which is desirable for such kinds of metadata.
|
||||
|
||||
This is not the same usage pattern as emitting a plain structured log where we'd like to include the name of an item we just queried:
|
||||
|
||||
```swift
|
||||
log.info("Obtained item! Hooray!", metadata: ["item": "\(item)"])
|
||||
```
|
||||
|
||||
In this example, the key/value pair for `"item"` is pretty ad-hoc, and we never need to refer to it elsewhere in the program. It never is queried by other pieces of the application, nor would it be useful to set it in baggage metadata, as the only purpose of the `item` key here is to log, and forget about it.
|
||||
|
||||
### Explicitly passing `Baggage` always
|
||||
|
||||
Baggage is designed for use cases like distributed tracing, or similar instrumentation patterns where "all" participating code may need to reach for it.
|
||||
|
||||
Specifically in logging, this means that _every_ call site for _every_ log statement would have to pass it explicitly resulting in annoying noisy code:
|
||||
|
||||
```swift
|
||||
class StoresRepository {
|
||||
func store(byID id: String, eventLoop: EventLoop, logger: Logger, baggage: Baggage) async throws -> Store {
|
||||
InstrumentationSystem.tracer.withSpan("Fetch Store", baggage: baggage) { span in
|
||||
logger.info("Fetched store.", baggage: span.baggage)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try await storesRepository.store(
|
||||
byID: storeID,
|
||||
eventLoop: eventLoop,
|
||||
logger: logger,
|
||||
baggage: baggage
|
||||
)
|
||||
```
|
||||
|
||||
### Explicitly passing `Logger` always
|
||||
|
||||
Imagine we don't have metadata providers, we'd have to manually set trace IDs on loggers which doesn't really work as all libraries involved would need to know about the same specific trace ID. Event if we inverted the dependency to have `Tracing` depend on `Logging` so that we'd be able to define something like "Tracing, please populate this logger with metadata", we'd have to make sure this thing is called in all places to avoid dropping contextual metadata.
|
||||
|
||||
```swift
|
||||
import Tracing
|
||||
import Logging
|
||||
|
||||
let contextualLogger = InstrumentationSystem.tracer.populateTraceMetadata(logger, baggage: baggage)
|
||||
contextualLogger.info("Request received.")
|
||||
```
|
||||
|
||||
### Tracing providing extensions on Logger
|
||||
|
||||
Instead of having `swift-log` depend on `swift-distributed-tracing-baggage` we could also create extensions for `Logger` inside `swift-distributed-tracing` and have users call these new overloaded methods instead:
|
||||
|
||||
```swift
|
||||
extension Logger {
|
||||
func tinfo(_ message: ..., baggage: Baggage?) {
|
||||
// ...
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Such extensions could work like the currently-proposed APIs, but the risk of users calling the wrong methods is incredibly high and we cannot overload the existing methods' signatures because of ambiguity of call-sides without explicit Baggage being passed:
|
||||
|
||||
```swift
|
||||
logger.info("Hello")
|
||||
// we want this to pick up Baggage, but the signature would be ambiguous
|
||||
```
|
||||
|
||||
Also, this extension-based contextual metadata would require basically everyone in Server-side Swift to adapt their usage of `Logging` to use these extensions instead. With the proposed APIs, we'd only need to modify `Logging` and any NIO-based libraries such as `AsyncHTTPClient`, `Vapor`, etc. and not every single log statement in every application.
|
||||
Reference in new issue
Block a user