From fc3aaf1b75f11d76f697566aac602cf3b4299fb8 Mon Sep 17 00:00:00 2001 From: Konrad `ktoso` Malawski Date: Mon, 14 Nov 2022 12:11:00 +0900 Subject: [PATCH] Push baggage pick-up into LogHandlers --- Sources/Logging/LogHandler.swift | 27 ++ Sources/Logging/Logging.swift | 378 +++++++++++++++------ Tests/LoggingTests/CompatibilityTest.swift | 2 +- Tests/LoggingTests/GlobalLoggingTest.swift | 6 +- Tests/LoggingTests/LocalLoggingTest.swift | 4 +- Tests/LoggingTests/LoggingTest.swift | 115 ++++--- Tests/LoggingTests/MDCTest.swift | 2 +- Tests/LoggingTests/TestLogger.swift | 55 ++- Tests/LoggingTests/TestSendable.swift | 2 +- 9 files changed, 412 insertions(+), 179 deletions(-) diff --git a/Sources/Logging/LogHandler.swift b/Sources/Logging/LogHandler.swift index 11a8a47..da17b2f 100644 --- a/Sources/Logging/LogHandler.swift +++ b/Sources/Logging/LogHandler.swift @@ -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, diff --git a/Sources/Logging/Logging.swift b/Sources/Logging/Logging.swift index dd98466..306bb8e 100644 --- a/Sources/Logging/Logging.swift +++ b/Sources/Logging/Logging.swift @@ -42,18 +42,12 @@ public struct Logger { @usableFromInline var handler: LogHandler - /// Metadata provider which will be used to convert contextual ``Baggage`` to ``Logger.Metadata`` when a log message is to be emitted. - /// The provider configured on the ``LoggingSystem`` level will be passed to a `Logger` on initialization, however it is possible to replace - /// the provider on specific instances, in case they should treat contextual baggage information in some other way (e.g. ignore it). - public var metadataProvider: MetadataProvider? - /// An identifier of the creator of this `Logger`. public let label: String - internal init(label: String, _ handler: LogHandler, metadataProvider: MetadataProvider?) { + internal init(label: String, _ handler: LogHandler) { self.label = label self.handler = handler - self.metadataProvider = metadataProvider } } @@ -85,26 +79,10 @@ extension Logger { source: @autoclosure () -> String? = nil, file: String = #fileID, function: String = #function, line: UInt = #line) { if self.logLevel <= level { - 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 - let providerMetadata = self.metadataProvider?.metadata(taskLocalBaggage) - 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, + metadata: metadata(), + baggage: .taskLocal, source: source() ?? Logger.currentModule(fileID: (file)), file: file, function: function, line: line) } @@ -121,6 +99,7 @@ extension Logger { self.handler.log(level: level, message: message(), metadata: metadata(), + baggage: .taskLocal, source: source() ?? Logger.currentModule(filePath: (file)), file: file, function: function, line: line) } @@ -152,20 +131,14 @@ extension Logger { public func log(level: Logger.Level, _ message: @autoclosure () -> Logger.Message, metadata: @autoclosure () -> Logger.Metadata? = nil, - baggage: Baggage?, + baggage: BaggageStrategy = .taskLocal, source: @autoclosure () -> String? = nil, file: String = #fileID, function: String = #function, line: UInt = #line) { if self.logLevel <= level { - let providerMetadata = self.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, + metadata: metadata(), + baggage: baggage, source: source() ?? Logger.currentModule(fileID: (file)), file: file, function: function, line: line) } @@ -176,20 +149,14 @@ extension Logger { public func log(level: Logger.Level, _ message: @autoclosure () -> Logger.Message, metadata: @autoclosure () -> Logger.Metadata? = nil, - baggage: Baggage?, + baggage: ContextualBaggage = .taskLocal, source: @autoclosure () -> String? = nil, file: String = #file, function: String = #function, line: UInt = #line) { if self.logLevel <= level { - let providerMetadata = self.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, + metadata: metadata(), + baggage: baggage, source: source() ?? Logger.currentModule(filePath: (file)), file: file, function: function, line: line) } @@ -226,7 +193,7 @@ extension Logger { _ message: @autoclosure () -> Logger.Message, metadata: @autoclosure () -> Logger.Metadata? = nil, file: String = #file, 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(), metadata: metadata(), baggage: .taskLocal, source: nil, file: file, function: function, line: line) } #endif @@ -285,23 +252,34 @@ extension Logger { @inlinable public func trace(_ message: @autoclosure () -> Logger.Message, metadata: @autoclosure () -> Logger.Metadata? = nil, - baggage: Baggage?, + baggage: Baggage, source: @autoclosure () -> String? = nil, file: String = #fileID, function: String = #function, line: UInt = #line) { - self.log(level: .trace, message(), metadata: metadata(), baggage: baggage, source: source(), file: file, function: function, line: line) + self.log(level: .trace, message(), metadata: metadata(), baggage: .explicitlyPassed(baggage), source: source(), file: file, function: function, line: line) } #else @inlinable public func trace(_ message: @autoclosure () -> Logger.Message, metadata: @autoclosure () -> Logger.Metadata? = nil, - baggage: Baggage?, + baggage: ContextualBaggage, source: @autoclosure () -> String? = nil, file: String = #file, function: String = #function, line: UInt = #line) { self.log(level: .trace, message(), metadata: metadata(), baggage: baggage, source: source(), file: file, function: function, line: line) } #endif + #if swift(>=5.5.0) + @inlinable + public func trace(_ message: @autoclosure () -> Logger.Message, + metadata: @autoclosure () -> Logger.Metadata? = nil, + baggage: ContextualBaggage, + source: @autoclosure () -> String? = nil, + file: String = #fileID, function: String = #function, line: UInt = #line) { + self.log(level: .trace, message(), metadata: metadata(), baggage: baggage, source: source(), file: file, function: function, line: line) + } + #endif + /// Log a message passing with the ``Logger/Level/trace`` log level. /// /// If `.trace` is at least as severe as the `Logger`'s ``logLevel``, it will be logged, @@ -358,7 +336,7 @@ extension Logger { @inlinable public func trace(_ message: @autoclosure () -> Logger.Message, metadata: @autoclosure () -> Logger.Metadata? = nil, - baggage: Baggage?, + baggage: BaggageStrategy, file: String = #fileID, function: String = #function, line: UInt = #line) { self.trace(message(), metadata: metadata(), baggage: baggage, source: nil, file: file, function: function, line: line) } @@ -367,7 +345,7 @@ extension Logger { @inlinable public func trace(_ message: @autoclosure () -> Logger.Message, metadata: @autoclosure () -> Logger.Metadata? = nil, - baggage: Baggage?, + baggage: ContextualBaggage, file: String = #file, function: String = #function, line: UInt = #line) { self.trace(message(), metadata: metadata(), baggage: baggage, source: nil, file: file, function: function, line: line) } @@ -427,23 +405,34 @@ extension Logger { @inlinable public func debug(_ message: @autoclosure () -> Logger.Message, metadata: @autoclosure () -> Logger.Metadata? = nil, - baggage: Baggage?, + baggage: Baggage, source: @autoclosure () -> String? = nil, file: String = #fileID, function: String = #function, line: UInt = #line) { - self.log(level: .debug, message(), metadata: metadata(), baggage: baggage, source: source(), file: file, function: function, line: line) + self.log(level: .debug, message(), metadata: metadata(), baggage: .explicitlyPassed(baggage), source: source(), file: file, function: function, line: line) } #else @inlinable public func debug(_ message: @autoclosure () -> Logger.Message, metadata: @autoclosure () -> Logger.Metadata? = nil, - baggage: Baggage?, + baggage: ContextualBaggage, source: @autoclosure () -> String? = nil, file: String = #file, function: String = #function, line: UInt = #line) { self.log(level: .debug, message(), metadata: metadata(), baggage: baggage, source: source(), file: file, function: function, line: line) } #endif + #if swift(>=5.5.0) + @inlinable + public func debug(_ message: @autoclosure () -> Logger.Message, + metadata: @autoclosure () -> Logger.Metadata? = nil, + baggage: ContextualBaggage = .taskLocal, + source: @autoclosure () -> String? = nil, + file: String = #fileID, function: String = #function, line: UInt = #line) { + self.log(level: .debug, message(), metadata: metadata(), baggage: baggage, source: source(), file: file, function: function, line: line) + } + #endif + /// Log a message passing with the ``Logger/Level/debug`` log level. /// /// If `.debug` is at least as severe as the `Logger`'s ``logLevel``, it will be logged, @@ -500,7 +489,7 @@ extension Logger { @inlinable public func debug(_ message: @autoclosure () -> Logger.Message, metadata: @autoclosure () -> Logger.Metadata? = nil, - baggage: Baggage?, + baggage: BaggageStrategy, file: String = #fileID, function: String = #function, line: UInt = #line) { self.debug(message(), metadata: metadata(), baggage: baggage, source: nil, file: file, function: function, line: line) } @@ -509,7 +498,7 @@ extension Logger { @inlinable public func debug(_ message: @autoclosure () -> Logger.Message, metadata: @autoclosure () -> Logger.Metadata? = nil, - baggage: Baggage?, + baggage: ContextualBaggage, file: String = #file, function: String = #function, line: UInt = #line) { self.debug(message(), metadata: metadata(), baggage: baggage, source: nil, file: file, function: function, line: line) } @@ -569,23 +558,34 @@ extension Logger { @inlinable public func info(_ message: @autoclosure () -> Logger.Message, metadata: @autoclosure () -> Logger.Metadata? = nil, - baggage: Baggage?, + baggage: Baggage, source: @autoclosure () -> String? = nil, file: String = #fileID, function: String = #function, line: UInt = #line) { - self.log(level: .info, message(), metadata: metadata(), baggage: baggage, source: source(), file: file, function: function, line: line) + self.log(level: .info, message(), metadata: metadata(), baggage: .explicitlyPassed(baggage), source: source(), file: file, function: function, line: line) } #else @inlinable public func info(_ message: @autoclosure () -> Logger.Message, metadata: @autoclosure () -> Logger.Metadata? = nil, - baggage: Baggage?, + baggage: ContextualBaggage, source: @autoclosure () -> String? = nil, file: String = #file, function: String = #function, line: UInt = #line) { self.log(level: .info, message(), metadata: metadata(), baggage: baggage, source: source(), file: file, function: function, line: line) } #endif + #if swift(>=5.5.0) + @inlinable + public func info(_ message: @autoclosure () -> Logger.Message, + metadata: @autoclosure () -> Logger.Metadata? = nil, + baggage: ContextualBaggage = .taskLocal, + source: @autoclosure () -> String? = nil, + file: String = #fileID, function: String = #function, line: UInt = #line) { + self.log(level: .info, message(), metadata: metadata(), baggage: baggage, source: source(), file: file, function: function, line: line) + } + #endif + /// Log a message passing with the ``Logger/Level/info`` log level. /// /// If `.info` is at least as severe as the `Logger`'s ``logLevel``, it will be logged, @@ -642,7 +642,7 @@ extension Logger { @inlinable public func info(_ message: @autoclosure () -> Logger.Message, metadata: @autoclosure () -> Logger.Metadata? = nil, - baggage: Baggage?, + baggage: BaggageStrategy, file: String = #fileID, function: String = #function, line: UInt = #line) { self.info(message(), metadata: metadata(), baggage: baggage, source: nil, file: file, function: function, line: line) } @@ -651,7 +651,7 @@ extension Logger { @inlinable public func info(_ message: @autoclosure () -> Logger.Message, metadata: @autoclosure () -> Logger.Metadata? = nil, - baggage: Baggage?, + baggage: ContextualBaggage, file: String = #file, function: String = #function, line: UInt = #line) { self.info(message(), metadata: metadata(), baggage: baggage, source: nil, file: file, function: function, line: line) } @@ -711,23 +711,34 @@ extension Logger { @inlinable public func notice(_ message: @autoclosure () -> Logger.Message, metadata: @autoclosure () -> Logger.Metadata? = nil, - baggage: Baggage?, + baggage: Baggage, source: @autoclosure () -> String? = nil, file: String = #fileID, function: String = #function, line: UInt = #line) { - self.log(level: .notice, message(), metadata: metadata(), baggage: baggage, source: source(), file: file, function: function, line: line) + self.log(level: .notice, message(), metadata: metadata(), baggage: .explicitlyPassed(baggage), source: source(), file: file, function: function, line: line) } #else @inlinable public func notice(_ message: @autoclosure () -> Logger.Message, metadata: @autoclosure () -> Logger.Metadata? = nil, - baggage: Baggage?, + baggage: ContextualBaggage, source: @autoclosure () -> String? = nil, file: String = #file, function: String = #function, line: UInt = #line) { self.log(level: .notice, message(), metadata: metadata(), baggage: baggage, source: source(), file: file, function: function, line: line) } #endif + #if swift(>=5.5.0) + @inlinable + public func notice(_ message: @autoclosure () -> Logger.Message, + metadata: @autoclosure () -> Logger.Metadata? = nil, + baggage: ContextualBaggage = .taskLocal, + source: @autoclosure () -> String? = nil, + file: String = #fileID, function: String = #function, line: UInt = #line) { + self.log(level: .notice, message(), metadata: metadata(), baggage: baggage, source: source(), file: file, function: function, line: line) + } + #endif + /// Log a message passing with the ``Logger/Level/notice`` log level. /// /// If `.notice` is at least as severe as the `Logger`'s ``logLevel``, it will be logged, @@ -784,7 +795,7 @@ extension Logger { @inlinable public func notice(_ message: @autoclosure () -> Logger.Message, metadata: @autoclosure () -> Logger.Metadata? = nil, - baggage: Baggage?, + baggage: BaggageStrategy, file: String = #fileID, function: String = #function, line: UInt = #line) { self.notice(message(), metadata: metadata(), baggage: baggage, source: nil, file: file, function: function, line: line) } @@ -793,7 +804,7 @@ extension Logger { @inlinable public func notice(_ message: @autoclosure () -> Logger.Message, metadata: @autoclosure () -> Logger.Metadata? = nil, - baggage: Baggage?, + baggage: ContextualBaggage, file: String = #file, function: String = #function, line: UInt = #line) { self.notice(message(), metadata: metadata(), baggage: baggage, source: nil, file: file, function: function, line: line) } @@ -853,23 +864,34 @@ extension Logger { @inlinable public func warning(_ message: @autoclosure () -> Logger.Message, metadata: @autoclosure () -> Logger.Metadata? = nil, - baggage: Baggage?, + baggage: Baggage, source: @autoclosure () -> String? = nil, file: String = #fileID, function: String = #function, line: UInt = #line) { - self.log(level: .warning, message(), metadata: metadata(), baggage: baggage, source: source(), file: file, function: function, line: line) + self.log(level: .warning, message(), metadata: metadata(), baggage: .explicitlyPassed(baggage), source: source(), file: file, function: function, line: line) } #else @inlinable public func warning(_ message: @autoclosure () -> Logger.Message, metadata: @autoclosure () -> Logger.Metadata? = nil, - baggage: Baggage?, + baggage: ContextualBaggage, source: @autoclosure () -> String? = nil, file: String = #file, function: String = #function, line: UInt = #line) { self.log(level: .warning, message(), metadata: metadata(), baggage: baggage, source: source(), file: file, function: function, line: line) } #endif + #if swift(>=5.5.0) + @inlinable + public func warning(_ message: @autoclosure () -> Logger.Message, + metadata: @autoclosure () -> Logger.Metadata? = nil, + baggage: ContextualBaggage = .taskLocal, + source: @autoclosure () -> String? = nil, + file: String = #fileID, function: String = #function, line: UInt = #line) { + self.log(level: .warning, message(), metadata: metadata(), baggage: baggage, source: source(), file: file, function: function, line: line) + } + #endif + /// Log a message passing with the ``Logger/Level/warning`` log level. /// /// If `.warning` is at least as severe as the `Logger`'s ``logLevel``, it will be logged, @@ -926,7 +948,7 @@ extension Logger { @inlinable public func warning(_ message: @autoclosure () -> Logger.Message, metadata: @autoclosure () -> Logger.Metadata? = nil, - baggage: Baggage?, + baggage: BaggageStrategy, file: String = #fileID, function: String = #function, line: UInt = #line) { self.warning(message(), metadata: metadata(), baggage: baggage, source: nil, file: file, function: function, line: line) } @@ -935,7 +957,7 @@ extension Logger { @inlinable public func warning(_ message: @autoclosure () -> Logger.Message, metadata: @autoclosure () -> Logger.Metadata? = nil, - baggage: Baggage?, + baggage: ContextualBaggage, file: String = #file, function: String = #function, line: UInt = #line) { self.warning(message(), metadata: metadata(), baggage: baggage, source: nil, file: file, function: function, line: line) } @@ -995,23 +1017,34 @@ extension Logger { @inlinable public func error(_ message: @autoclosure () -> Logger.Message, metadata: @autoclosure () -> Logger.Metadata? = nil, - baggage: Baggage?, + baggage: Baggage, source: @autoclosure () -> String? = nil, file: String = #fileID, function: String = #function, line: UInt = #line) { - self.log(level: .error, message(), metadata: metadata(), baggage: baggage, source: source(), file: file, function: function, line: line) + self.log(level: .error, message(), metadata: metadata(), baggage: .explicitlyPassed(baggage), source: source(), file: file, function: function, line: line) } #else @inlinable public func error(_ message: @autoclosure () -> Logger.Message, metadata: @autoclosure () -> Logger.Metadata? = nil, - baggage: Baggage?, + baggage: ContextualBaggage, source: @autoclosure () -> String? = nil, file: String = #file, function: String = #function, line: UInt = #line) { self.log(level: .error, message(), metadata: metadata(), baggage: baggage, source: source(), file: file, function: function, line: line) } #endif + #if swift(>=5.5.0) + @inlinable + public func error(_ message: @autoclosure () -> Logger.Message, + metadata: @autoclosure () -> Logger.Metadata? = nil, + baggage: ContextualBaggage = .taskLocal, + source: @autoclosure () -> String? = nil, + file: String = #fileID, function: String = #function, line: UInt = #line) { + self.log(level: .error, message(), metadata: metadata(), baggage: baggage, source: source(), file: file, function: function, line: line) + } + #endif + /// Log a message passing with the ``Logger/Level/error`` log level. /// /// If `.error` is at least as severe as the `Logger`'s ``logLevel``, it will be logged, @@ -1068,7 +1101,7 @@ extension Logger { @inlinable public func error(_ message: @autoclosure () -> Logger.Message, metadata: @autoclosure () -> Logger.Metadata? = nil, - baggage: Baggage?, + baggage: BaggageStrategy, file: String = #fileID, function: String = #function, line: UInt = #line) { self.error(message(), metadata: metadata(), baggage: baggage, source: nil, file: file, function: function, line: line) } @@ -1077,7 +1110,7 @@ extension Logger { @inlinable public func error(_ message: @autoclosure () -> Logger.Message, metadata: @autoclosure () -> Logger.Metadata? = nil, - baggage: Baggage?, + baggage: ContextualBaggage, file: String = #file, function: String = #function, line: UInt = #line) { self.error(message(), metadata: metadata(), baggage: baggage, source: nil, file: file, function: function, line: line) } @@ -1137,23 +1170,34 @@ extension Logger { @inlinable public func critical(_ message: @autoclosure () -> Logger.Message, metadata: @autoclosure () -> Logger.Metadata? = nil, - baggage: Baggage?, + baggage: Baggage, source: @autoclosure () -> String? = nil, file: String = #fileID, function: String = #function, line: UInt = #line) { - self.log(level: .critical, message(), metadata: metadata(), baggage: baggage, source: source(), file: file, function: function, line: line) + self.log(level: .critical, message(), metadata: metadata(), baggage: .explicitlyPassed(baggage), source: source(), file: file, function: function, line: line) } #else @inlinable public func critical(_ message: @autoclosure () -> Logger.Message, metadata: @autoclosure () -> Logger.Metadata? = nil, - baggage: Baggage?, + baggage: ContextualBaggage, source: @autoclosure () -> String? = nil, file: String = #file, function: String = #function, line: UInt = #line) { self.log(level: .critical, message(), metadata: metadata(), baggage: baggage, source: source(), file: file, function: function, line: line) } #endif + #if swift(>=5.5.0) + @inlinable + public func critical(_ message: @autoclosure () -> Logger.Message, + metadata: @autoclosure () -> Logger.Metadata? = nil, + baggage: ContextualBaggage = .taskLocal, + source: @autoclosure () -> String? = nil, + file: String = #fileID, function: String = #function, line: UInt = #line) { + self.log(level: .critical, message(), metadata: metadata(), baggage: baggage, source: source(), file: file, function: function, line: line) + } + #endif + /// Log a message passing with the ``Logger/Level/critical`` log level. /// /// If `.critical` is at least as severe as the `Logger`'s ``logLevel``, it will be logged, @@ -1210,7 +1254,7 @@ extension Logger { @inlinable public func critical(_ message: @autoclosure () -> Logger.Message, metadata: @autoclosure () -> Logger.Metadata? = nil, - baggage: Baggage?, + baggage: BaggageStrategy, file: String = #fileID, function: String = #function, line: UInt = #line) { self.critical(message(), metadata: metadata(), baggage: baggage, source: nil, file: file, function: function, line: line) } @@ -1219,7 +1263,7 @@ extension Logger { @inlinable public func critical(_ message: @autoclosure () -> Logger.Message, metadata: @autoclosure () -> Logger.Metadata? = nil, - baggage: Baggage?, + baggage: ContextualBaggage, file: String = #file, function: String = #function, line: UInt = #line) { self.critical(message(), metadata: metadata(), baggage: baggage, source: nil, file: file, function: function, line: line) } @@ -1272,7 +1316,7 @@ public enum LoggingSystem { /// - metadataProvider: The `MetadataProvider` used to inject runtime-generated metadata, defaults to nil. /// - factory: A closure that given a `Logger` identifier, produces an instance of the `LogHandler`. public static func bootstrap(metadataProvider: Logger.MetadataProvider? = nil, - _ factory: @escaping (String) -> LogHandler) { + _ factory: @escaping (String, Logger.MetadataProvider?) -> LogHandler) { self._metadataProvider.replaceMetadataProvider(metadataProvider, validate: true) self._factory.replaceFactory(factory, validate: true) } @@ -1284,25 +1328,40 @@ public enum LoggingSystem { /// - parameters: /// - factory: A closure that given a `Logger` identifier, produces an instance of the `LogHandler`. public static func bootstrap(_ factory: @escaping (String) -> LogHandler) { - self.bootstrap(metadataProvider: nil, factory) + self.bootstrap(metadataProvider: nil) { label, metadataProvider in + factory(label) + } } // for our testing we want to allow multiple bootstraping - internal static func bootstrapInternal(metadataProvider: Logger.MetadataProvider? = nil, - _ factory: @escaping (String) -> LogHandler) { + internal static func bootstrapInternal(_ factory: @escaping (String, Logger.MetadataProvider?) -> LogHandler) { + self._factory.replaceFactory(factory, validate: false) + } + + // for our testing we want to allow multiple bootstraping + internal static func bootstrapInternal(metadataProvider: Logger.MetadataProvider, + _ factory: @escaping (String, Logger.MetadataProvider?) -> LogHandler) { self._metadataProvider.replaceMetadataProvider(metadataProvider, validate: false) self._factory.replaceFactory(factory, validate: false) } internal static func bootstrapInternal(_ factory: @escaping (String) -> LogHandler) { - self.bootstrapInternal(metadataProvider: nil, factory) + self.bootstrapInternal { label, _ in + factory(label) + } } - fileprivate static var metadataProvider: Logger.MetadataProvider? { + public static var metadataProvider: Logger.MetadataProvider? { return self._metadataProvider.underlying } fileprivate static var factory: (String) -> LogHandler { + return { label in + self._factory._underlying(label, LoggingSystem.metadataProvider) + } + } + + fileprivate static var factoryWithMetadataProvider: (String, Logger.MetadataProvider?) -> LogHandler { return self._factory.underlying } @@ -1332,14 +1391,26 @@ public enum LoggingSystem { private final class FactoryBox { private let lock = ReadWriteLock() - fileprivate var _underlying: (String) -> LogHandler + fileprivate var _underlying: (String, Logger.MetadataProvider?) -> LogHandler private var initialized = false init(_ underlying: @escaping (String) -> LogHandler) { - self._underlying = underlying + self._underlying = { label, _ in + underlying(label) + } } func replaceFactory(_ factory: @escaping (String) -> LogHandler, validate: Bool) { + self.lock.withWriterLock { + precondition(!validate || !self.initialized, "logging system can only be initialized once per process.") + self._underlying = { label, _ in + factory(label) + } + self.initialized = true + } + } + + func replaceFactory(_ factory: @escaping (String, Logger.MetadataProvider?) -> LogHandler, validate: Bool) { self.lock.withWriterLock { precondition(!validate || !self.initialized, "logging system can only be initialized once per process.") self._underlying = factory @@ -1347,7 +1418,7 @@ public enum LoggingSystem { } } - var underlying: (String) -> LogHandler { + var underlying: (String, Logger.MetadataProvider?) -> LogHandler { return self.lock.withReaderLock { return self._underlying } @@ -1359,6 +1430,25 @@ extension Logger { /// `Metadata` is a typealias for `[String: Logger.MetadataValue]` the type of the metadata storage. public typealias Metadata = [String: MetadataValue] + /// Defines where contextual `Baggage` metadata should be obtained from. + /// Generally, the default of the ``ContextualBaggage/taskLocal`` strategy is the best to use in most applications. + /// However, some systems may not be able to use task-locals, or want to pass baggage values explicitly. + public enum BaggageStrategy { + /// Instructs the ``LogHandler`` to pick-up the task-local `Baggage`, + /// by querying `Baggage/current` when about to emit a log statement. + case taskLocal + + /// Instructs the logger backend to use the explicitly passed Baggage when extracting metadata to include + // in log statements. + case explicitlyPassed(InstrumentationBaggage.Baggage) + + /// Completely ignore contextual Baggage, and do not attempt to pick-up, + /// or extract values from a passed Baggage value. + /// + /// Effectively, this disables any configured ``Logger/MetadataProvider``. + case ignore + } + /// A logging metadata value. `Logger.MetadataValue` is string, array, and dictionary literal convertible. /// /// `MetadataValue` provides convenient conformances to `ExpressibleByStringInterpolation`, @@ -1442,7 +1532,7 @@ extension Logger { /// - parameters: /// - label: An identifier for the creator of a `Logger`. public init(label: String) { - self.init(label: label, LoggingSystem.factory(label), metadataProvider: LoggingSystem.metadataProvider) + self.init(label: label, LoggingSystem.factoryWithMetadataProvider(label, LoggingSystem.metadataProvider)) } /// Construct a `Logger` given a `label` identifying the creator of the `Logger` and a `MetadataProvider`. @@ -1454,7 +1544,7 @@ extension Logger { /// - label: An identifier for the creator of a `Logger`. /// - metadataProvider: The `MetadataProvider` used to inject runtime-generated metadata, defaults to nil. public init(label: String, metadataProvider: MetadataProvider) { - self.init(label: label, LoggingSystem.factory(label), metadataProvider: metadataProvider) + self.init(label: label, LoggingSystem.factoryWithMetadataProvider(label, metadataProvider)) } /// Construct a `Logger` given a `label` identifying the creator of the `Logger` or a non-standard `LogHandler`. @@ -1470,7 +1560,7 @@ extension Logger { /// - factory: A closure creating non-standard `LogHandler`s. public init(label: String, factory: (String) -> LogHandler) { - self = Logger(label: label, factory(label), metadataProvider: LoggingSystem.metadataProvider) + self = Logger(label: label, factory(label)) } /// Construct a `Logger` given a `label` identifying the creator of the `Logger` or a non-standard `LogHandler` and a `MetadataProvider`. @@ -1483,12 +1573,10 @@ extension Logger { /// /// - parameters: /// - label: An identifier for the creator of a `Logger`. - /// - factory: A closure creating non-standard `LogHandler`s. - /// - metadataProvider: The `MetadataProvider` used to inject runtime-generated metadata. + /// - factory: A closure creating non-standard `LogHandler`s, which will be passed a label and the global ``LoggingSystem/metadataProvider`` public init(label: String, - factory: (String) -> LogHandler, - metadataProvider: MetadataProvider) { - self = Logger(label: label, factory(label), metadataProvider: metadataProvider) + factory: (String, MetadataProvider?) -> LogHandler) { + self = Logger(label: label, factory(label, LoggingSystem.metadataProvider)) } } @@ -1513,21 +1601,25 @@ extension Logger { /// ``` #if swift(>=5.5) && canImport(_Concurrency) public struct MetadataProvider: Sendable { - /// Extract `Metadata` from the given `Baggage`. - public let metadata: @Sendable(_ baggage: Baggage?) -> Metadata? + /// Extract `Metadata` from the given `InstrumentationBaggage/Baggage`. + public let fn: @Sendable(_ baggage: Baggage?) -> Metadata? /// Create a new `MetadataProvider`. /// /// - Parameter metadata: A closure extracting metadata from a given `Baggage`. - public init(metadata: @escaping @Sendable(Baggage?) -> Metadata?) { - self.metadata = metadata + public init(_ fn: @escaping @Sendable(Baggage?) -> Metadata?) { + self.fn = fn + } + + public func provideMetadata(from baggage: Baggage?) -> Metadata? { + fn(baggage) } } #else public struct MetadataProvider { - /// Extract `Metadata` from the given `Baggage`. - public let metadata: (_ baggage: Baggage?) -> Metadata? + /// Extract `Metadata` from the given `InstrumentationBaggage/Baggage`. + internal let fn: (_ baggage: Baggage?) -> Metadata? /// Create a new `MetadataProvider`. /// @@ -1535,6 +1627,10 @@ extension Logger { public init(metadata: @escaping (Baggage?) -> Metadata?) { self.metadata = metadata } + + public func provideMetadata(from baggage: Baggage?) -> Metadata? { + fn(baggage) + } } #endif } @@ -1553,7 +1649,7 @@ extension 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 let providedMetadata = provider.provideMetadata(from: baggage) { if metadata != nil { metadata!.merge(providedMetadata, uniquingKeysWith: { _, rhs in rhs }) } else { @@ -1713,12 +1809,13 @@ public struct MultiplexLogHandler: LogHandler { public func log(level: Logger.Level, message: Logger.Message, metadata: Logger.Metadata?, + baggage: Logger.BaggageStrategy, source: String, file: String, function: String, line: UInt) { for handler in self.handlers where handler.logLevel <= level { - handler.log(level: level, message: message, metadata: metadata, source: source, file: file, function: function, line: line) + handler.log(level: level, message: message, metadata: metadata, baggage: baggage, source: source, file: file, function: function, line: line) } } @@ -1850,14 +1947,25 @@ public struct StreamLogHandler: LogHandler { /// Factory that makes a `StreamLogHandler` to directs its output to `stdout` public static func standardOutput(label: String) -> StreamLogHandler { - return StreamLogHandler(label: label, stream: StdioOutputStream.stdout) + return StreamLogHandler(label: label, metadataProvider: nil, stream: StdioOutputStream.stdout) + } + + /// Factory that makes a `StreamLogHandler` to directs its output to `stdout` + public static func standardOutput(label: String, metadataProvider: Logger.MetadataProvider?) -> StreamLogHandler { + return StreamLogHandler(label: label, metadataProvider: nil, stream: StdioOutputStream.stdout) } /// Factory that makes a `StreamLogHandler` to directs its output to `stderr` public static func standardError(label: String) -> StreamLogHandler { - return StreamLogHandler(label: label, stream: StdioOutputStream.stderr) + return StreamLogHandler(label: label, metadataProvider: nil, stream: StdioOutputStream.stderr) } + /// Factory that makes a `StreamLogHandler` to directs its output to `stderr` + public static func standardError(label: String, metadataProvider: Logger.MetadataProvider?) -> StreamLogHandler { + return StreamLogHandler(label: label, metadataProvider: metadataProvider, stream: StdioOutputStream.stderr) + } + + private let metadataProvider: Logger.MetadataProvider? private let stream: _SendableTextOutputStream private let label: String @@ -1880,24 +1988,72 @@ public struct StreamLogHandler: LogHandler { } // internal for testing only - internal init(label: String, stream: _SendableTextOutputStream) { + internal init(label: String, + stream: _SendableTextOutputStream) { self.label = label + self.metadataProvider = nil + self.stream = stream + } + + // internal for testing only + internal init(label: String, + metadataProvider: Logger.MetadataProvider?, + stream: _SendableTextOutputStream) { + self.label = label + self.metadataProvider = metadataProvider self.stream = stream } public func log(level: Logger.Level, message: Logger.Message, metadata: Logger.Metadata?, + baggage whereIsTheBaggage: Logger.BaggageStrategy, source: String, file: String, function: String, line: UInt) { - let prettyMetadata = metadata?.isEmpty ?? true - ? self.prettyMetadata - : self.prettify(self.metadata.merging(metadata!, uniquingKeysWith: { _, new in new })) + + 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 stream = self.stream - stream.write("\(self.timestamp()) \(level) \(self.label) :\(prettyMetadata.map { " \($0)" } ?? "") [\(source)] \(message)\n") + if let baggage, + let extraMetadata = LoggingSystem.metadataProvider?.provideMetadata(from: baggage) { + + let prettyMetadata = metadata?.isEmpty ?? true + ? self.prettyMetadata + : self.prettify( + extraMetadata.merging( + self.metadata.merging( + metadata!, + uniquingKeysWith: { _, new in new } + ), + uniquingKeysWith: { _, new in new })) + + + stream.write("\(self.timestamp()) \(level) \(self.label) :\(prettyMetadata.map { " \($0)" } ?? "") \(self.prettify(extraMetadata).map { " \($0)" }) [\(source)] \(message)\n") + } else { + let prettyMetadata = metadata?.isEmpty ?? true + ? self.prettyMetadata + : self.prettify(self.metadata.merging(metadata!, uniquingKeysWith: { _, new in new })) + + stream.write("\(self.timestamp()) \(level) \(self.label) :\(prettyMetadata.map { " \($0)" } ?? "") [\(source)] \(message)\n") + } } private func prettify(_ metadata: Logger.Metadata) -> String? { diff --git a/Tests/LoggingTests/CompatibilityTest.swift b/Tests/LoggingTests/CompatibilityTest.swift index 3ede79a..af139bc 100644 --- a/Tests/LoggingTests/CompatibilityTest.swift +++ b/Tests/LoggingTests/CompatibilityTest.swift @@ -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) { diff --git a/Tests/LoggingTests/GlobalLoggingTest.swift b/Tests/LoggingTests/GlobalLoggingTest.swift index a1ffb8e..ad85c4d 100644 --- a/Tests/LoggingTests/GlobalLoggingTest.swift +++ b/Tests/LoggingTests/GlobalLoggingTest.swift @@ -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) diff --git a/Tests/LoggingTests/LocalLoggingTest.swift b/Tests/LoggingTests/LocalLoggingTest.swift index 2f15e22..c98317b 100644 --- a/Tests/LoggingTests/LocalLoggingTest.swift +++ b/Tests/LoggingTests/LocalLoggingTest.swift @@ -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) diff --git a/Tests/LoggingTests/LoggingTest.swift b/Tests/LoggingTests/LoggingTest.swift index 63190ca..cbd0828 100644 --- a/Tests/LoggingTests/LoggingTest.swift +++ b/Tests/LoggingTests/LoggingTest.swift @@ -27,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 @@ -231,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"] @@ -247,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"] @@ -290,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") @@ -310,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 @@ -324,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"]) @@ -365,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 @@ -389,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 @@ -413,26 +413,26 @@ 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 - let trace = logger.trace(_:metadata:baggage:source:file:function:line:) - let debug = logger.debug(_:metadata:baggage:source:file:function:line:) - let info = logger.info(_:metadata:baggage:source:file:function:line:) - let notice = logger.notice(_:metadata:baggage:source:file:function:line:) - let warning = logger.warning(_:metadata:baggage:source:file:function:line:) - let error = logger.error(_:metadata:baggage:source:file:function:line:) - let critical = logger.critical(_:metadata:baggage:source:file:function:line:) + let trace = logger.trace(_:metadata:source:file:function:line:) + let debug = logger.debug(_:metadata:source:file:function:line:) + let info = logger.info(_:metadata:source:file:function:line:) + let notice = logger.notice(_:metadata:source:file:function:line:) + let warning = logger.warning(_:metadata:source:file:function:line:) + let error = logger.error(_:metadata:source:file:function:line:) + let critical = logger.critical(_:metadata:source:file:function:line:) - trace("yes: trace", [:], nil, "foo", #file, #function, #line) - debug("yes: debug", [:], nil, "foo", #file, #function, #line) - info("yes: info", [:], nil, "foo", #file, #function, #line) - notice("yes: notice", [:], nil, "foo", #file, #function, #line) - warning("yes: warning", [:], nil, "foo", #file, #function, #line) - error("yes: error", [:], nil, "foo", #file, #function, #line) - critical("yes: critical", [:], nil, "foo", #file, #function, #line) + trace("yes: trace", [:], "foo", #file, #function, #line) + debug("yes: debug", [:], "foo", #file, #function, #line) + info("yes: info", [:], "foo", #file, #function, #line) + notice("yes: notice", [:], "foo", #file, #function, #line) + warning("yes: warning", [:], "foo", #file, #function, #line) + error("yes: error", [:], "foo", #file, #function, #line) + critical("yes: critical", [:], "foo", #file, #function, #line) testLogging.history.assertExist(level: .trace, message: "yes: trace", source: "foo") testLogging.history.assertExist(level: .debug, message: "yes: debug", source: "foo") @@ -445,27 +445,27 @@ 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 - let trace = logger.trace(_:metadata:baggage:file:function:line:) - let debug = logger.debug(_:metadata:baggage:file:function:line:) - let info = logger.info(_:metadata:baggage:file:function:line:) - let notice = logger.notice(_:metadata:baggage:file:function:line:) - let warning = logger.warning(_:metadata:baggage:file:function:line:) - let error = logger.error(_:metadata:baggage:file:function:line:) - let critical = logger.critical(_:metadata:baggage:file:function:line:) + let trace = logger.trace(_:metadata:file:function:line:) + let debug = logger.debug(_:metadata:file:function:line:) + let info = logger.info(_:metadata:file:function:line:) + let notice = logger.notice(_:metadata:file:function:line:) + let warning = logger.warning(_:metadata:file:function:line:) + let error = logger.error(_:metadata:file:function:line:) + let critical = logger.critical(_:metadata:file:function:line:) #if compiler(>=5.3) - trace("yes: trace", [:], nil, #fileID, #function, #line) - debug("yes: debug", [:], nil, #fileID, #function, #line) - info("yes: info", [:], nil, #fileID, #function, #line) - notice("yes: notice", [:], nil, #fileID, #function, #line) - warning("yes: warning", [:], nil, #fileID, #function, #line) - error("yes: error", [:], nil, #fileID, #function, #line) - critical("yes: critical", [:], nil, #fileID, #function, #line) + trace("yes: trace", [:], #fileID, #function, #line) + debug("yes: debug", [:], #fileID, #function, #line) + info("yes: info", [:], #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", [:], nil, #file, #function, #line) debug("yes: debug", [:], nil, #file, #function, #line) @@ -487,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 @@ -511,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 @@ -524,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 @@ -542,7 +542,7 @@ class LoggingTest: XCTestCase { func testLoggingCallsMetadataProviderWithTaskLocalBaggage() throws { #if swift(>=5.5) && canImport(_Concurrency) let logging = TestLogging() - LoggingSystem.bootstrapInternal(logging.make) + 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 { @@ -582,7 +582,7 @@ class LoggingTest: XCTestCase { func testLoggingCallsMetadataProviderWithExplicitlyPassedBaggage() throws { let logging = TestLogging() - LoggingSystem.bootstrapInternal(logging.make) + 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 { @@ -621,7 +621,7 @@ class LoggingTest: XCTestCase { func testLoggingMergesOneOffMetadataWithProvidedMetadataFromTaskLocalBaggage() throws { #if swift(>=5.5) && canImport(_Concurrency) let logging = TestLogging() - LoggingSystem.bootstrapInternal(logging.make) + LoggingSystem.bootstrapInternal(logging.make(label:metadataProvider:)) let logger = Logger(label: #function, metadataProvider: .init { _ in [ @@ -642,7 +642,7 @@ class LoggingTest: XCTestCase { func testLoggingMergesOneOffMetadataWithProvidedMetadataFromExplicitlyPassedBaggage() throws { let logging = TestLogging() - LoggingSystem.bootstrapInternal(logging.make) + LoggingSystem.bootstrapInternal(logging.make(label:metadataProvider:)) let logger = Logger(label: #function, metadataProvider: .init { _ in [ @@ -651,7 +651,7 @@ class LoggingTest: XCTestCase { ] }) - logger.log(level: .info, "test", metadata: ["one-off": "42", "common": "one-off"], baggage: .topLevel) + logger.log(level: .info, "test", metadata: ["one-off": "42", "common": "one-off"], baggage: .explicitlyPassed(.topLevel)) logging.history.assertExist(level: .info, message: "test", @@ -662,7 +662,7 @@ class LoggingTest: XCTestCase { func testLoggingPrefersExplicitBaggageOverTaskLocal() { #if swift(>=5.5) && canImport(_Concurrency) let logging = TestLogging() - LoggingSystem.bootstrapInternal(logging.make) + 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 { @@ -707,7 +707,7 @@ class LoggingTest: XCTestCase { func testLoggingWithExplicitlyPassedNilBaggageDoesNotPickUpTaskLocalBaggage() { #if swift(>=5.5) && canImport(_Concurrency) let logging = TestLogging() - LoggingSystem.bootstrapInternal(logging.make) + LoggingSystem.bootstrapInternal(logging.make(label:metadataProvider:)) let logger = Logger(label: #function, metadataProvider: .init { baggage in XCTAssertNil(baggage) @@ -715,7 +715,7 @@ class LoggingTest: XCTestCase { }) Baggage.$current.withValue(.topLevel) { - logger.log(level: .info, "test", baggage: nil) + logger.log(level: .info, "test", baggage: .ignore) } logging.history.assertExist(level: .info, message: "test", metadata: ["provider": "42"]) @@ -728,8 +728,9 @@ class LoggingTest: XCTestCase { let providerA = Logger.MetadataProvider { _ in ["provider": "a", "a": "foo"] } let providerB = Logger.MetadataProvider { _ in ["provider": "b", "b": "bar"] } let logger = Logger(label: #function, - factory: logging.make, - metadataProvider: .multiplex([providerA, providerB])) + factory: { label in + logging.make(label: label, metadataProvider: .multiplex([providerA, providerB])) + }) logger.log(level: .info, "test", metadata: ["one-off": "42"]) @@ -740,7 +741,9 @@ class LoggingTest: XCTestCase { func testLoggerWithoutFactoryOverrideDefaultsToUsingLoggingSystemMetadataProvider() { let logging = TestLogging() - LoggingSystem.bootstrapInternal(metadataProvider: .init(metadata: { _ in ["provider": "42"] }), logging.make) + LoggingSystem.bootstrapInternal { label in + logging.make(label: label, metadataProvider: .init({ _ in ["provider": "42"] })) + } let logger = Logger(label: #function) @@ -753,9 +756,11 @@ class LoggingTest: XCTestCase { func testLoggerWithFactoryOverrideDefaultsToUsingLoggingSystemMetadataProvider() { let logging = TestLogging() - LoggingSystem.bootstrapInternal(metadataProvider: .init(metadata: { _ in ["provider": "42"] }), logging.make) + LoggingSystem.bootstrapInternal( + metadataProvider: .init({ _ in ["provider": "42"] }), + logging.make(label:metadataProvider:)) - let logger = Logger(label: #function, factory: logging.make) + let logger = Logger(label: #function, factory: logging.make(label:metadataProvider:)) logger.log(level: .info, "test", metadata: ["one-off": "42"]) @@ -1090,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 diff --git a/Tests/LoggingTests/MDCTest.swift b/Tests/LoggingTests/MDCTest.swift index c5cef47..79cb77d 100644 --- a/Tests/LoggingTests/MDCTest.swift +++ b/Tests/LoggingTests/MDCTest.swift @@ -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" diff --git a/Tests/LoggingTests/TestLogger.swift b/Tests/LoggingTests/TestLogger.swift index 169132f..2bfdac0 100644 --- a/Tests/LoggingTests/TestLogger.swift +++ b/Tests/LoggingTests/TestLogger.swift @@ -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), metadataProvider: nil) + 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) } diff --git a/Tests/LoggingTests/TestSendable.swift b/Tests/LoggingTests/TestSendable.swift index 9e96e7b..7b1b491 100644 --- a/Tests/LoggingTests/TestSendable.swift +++ b/Tests/LoggingTests/TestSendable.swift @@ -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")