mirror of
https://github.com/apple/swift-log
synced 2026-11-26 04:07:49 +00:00
Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
33c2b451c9 | ||
|
|
f79ba6a75f | ||
|
|
6763fd0b73 | ||
|
|
32e8d72446 | ||
|
|
b2eff1c427 | ||
|
|
ba2a9f5b93 | ||
|
|
3e3ef75109 | ||
|
|
bd4519f1c2 | ||
|
|
e6ca651cbc | ||
|
|
dc77805fdc | ||
|
|
e979c6945c | ||
|
|
d86803715f |
No files matched your search
@@ -0,0 +1,4 @@
|
||||
version: 1
|
||||
builder:
|
||||
configs:
|
||||
- documentation_targets: [Logging]
|
||||
+1
-4
@@ -22,14 +22,11 @@ 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: [
|
||||
.product(name: "InstrumentationBaggage", package: "swift-distributed-tracing-baggage"),
|
||||
]
|
||||
dependencies: []
|
||||
),
|
||||
.testTarget(
|
||||
name: "LoggingTests",
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
// swift-tools-version:5.0
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Logging API open source project
|
||||
//
|
||||
// Copyright (c) 2018-2019 Apple Inc. and the Swift Logging API project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of Swift Logging API project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "swift-log",
|
||||
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: [
|
||||
.product(name: "InstrumentationBaggage", package: "swift-distributed-tracing-baggage"),
|
||||
]
|
||||
),
|
||||
.testTarget(
|
||||
name: "LoggingTests",
|
||||
dependencies: ["Logging"]
|
||||
),
|
||||
]
|
||||
)
|
||||
@@ -20,15 +20,10 @@ 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: [
|
||||
.product(name: "InstrumentationBaggage", package: "swift-distributed-tracing-baggage"),
|
||||
]
|
||||
dependencies: []
|
||||
),
|
||||
.testTarget(
|
||||
name: "LoggingTests",
|
||||
|
||||
@@ -20,15 +20,10 @@ 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: [
|
||||
.product(name: "InstrumentationBaggage", package: "swift-distributed-tracing-baggage"),
|
||||
]
|
||||
dependencies: []
|
||||
),
|
||||
.testTarget(
|
||||
name: "LoggingTests",
|
||||
|
||||
@@ -20,15 +20,10 @@ 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: [
|
||||
.product(name: "InstrumentationBaggage", package: "swift-distributed-tracing-baggage"),
|
||||
]
|
||||
dependencies: []
|
||||
),
|
||||
.testTarget(
|
||||
name: "LoggingTests",
|
||||
|
||||
@@ -20,15 +20,10 @@ 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: [
|
||||
.product(name: "InstrumentationBaggage", package: "swift-distributed-tracing-baggage"),
|
||||
]
|
||||
dependencies: []
|
||||
),
|
||||
.testTarget(
|
||||
name: "LoggingTests",
|
||||
|
||||
@@ -20,15 +20,10 @@ 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: [
|
||||
.product(name: "InstrumentationBaggage", package: "swift-distributed-tracing-baggage"),
|
||||
]
|
||||
dependencies: []
|
||||
),
|
||||
.testTarget(
|
||||
name: "LoggingTests",
|
||||
|
||||
@@ -84,7 +84,8 @@ As the API has just launched, not many implementations exist yet. If you are int
|
||||
| [luoxiu/LogDog](https://github.com/luoxiu/LogDog) | user-friendly logging with sinks and appenders |
|
||||
| [ShivaHuang/swift-log-SwiftyBeaver](https://github.com/ShivaHuang/swift-log-SwiftyBeaver) | a logging backend for printing colored logging to Xcode console / file, or sending encrypted logging to [SwiftyBeaver](https://swiftybeaver.com) platform. |
|
||||
| [Apodini/swift-log-elk](https://github.com/Apodini/swift-log-elk) | a logging backend that formats, caches and sends log data to [elastic/logstash](https://github.com/elastic/logstash) |
|
||||
| [binaryscraping/swift-log-supabase](https://github.com/binaryscraping/swift-log-supabase) | a logging backend that sends log entries to [Supabase](https://github.com/supabase/supbase). |
|
||||
| [binaryscraping/swift-log-supabase](https://github.com/binaryscraping/swift-log-supabase) | a logging backend that sends log entries to [Supabase](https://github.com/supabase/supabase). |
|
||||
| [MahdiBM/DiscordBM](https://github.com/MahdiBM/DiscordBM) | a Discord client package containing a standalone [DiscordLogger library](https://github.com/MahdiBM/DiscordBM/blob/discord-logger/README.md#discord-logger) |
|
||||
| Your library? | [Get in touch!](https://forums.swift.org/c/server) |
|
||||
|
||||
## What is an API package?
|
||||
@@ -217,3 +218,5 @@ This logging API was designed with the contributors to the Swift on Server commu
|
||||
- [log levels](https://forums.swift.org/t/logging-levels-for-swifts-server-side-logging-apis-and-new-os-log-apis/20365)
|
||||
|
||||
[api-docs]: https://apple.github.io/swift-log/docs/current/Logging/Structs/Logger.html
|
||||
|
||||
|
||||
@@ -45,7 +45,9 @@ import Glibc
|
||||
/// one used by NIO. On Windows, the lock is based on the substantially similar
|
||||
/// `SRWLOCK` type.
|
||||
internal final class Lock {
|
||||
#if os(Windows)
|
||||
#if canImport(WASILibc)
|
||||
// WASILibc is single threaded, provides no locks
|
||||
#elseif os(Windows)
|
||||
fileprivate let mutex: UnsafeMutablePointer<SRWLOCK> =
|
||||
UnsafeMutablePointer.allocate(capacity: 1)
|
||||
#else
|
||||
@@ -55,7 +57,9 @@ internal final class Lock {
|
||||
|
||||
/// Create a new lock.
|
||||
public init() {
|
||||
#if os(Windows)
|
||||
#if canImport(WASILibc)
|
||||
// WASILibc is single threaded, provides no locks
|
||||
#elseif os(Windows)
|
||||
InitializeSRWLock(self.mutex)
|
||||
#else
|
||||
var attr = pthread_mutexattr_t()
|
||||
@@ -68,13 +72,16 @@ internal final class Lock {
|
||||
}
|
||||
|
||||
deinit {
|
||||
#if os(Windows)
|
||||
#if canImport(WASILibc)
|
||||
// WASILibc is single threaded, provides no locks
|
||||
#elseif os(Windows)
|
||||
// SRWLOCK does not need to be free'd
|
||||
self.mutex.deallocate()
|
||||
#else
|
||||
let err = pthread_mutex_destroy(self.mutex)
|
||||
precondition(err == 0, "\(#function) failed in pthread_mutex with error \(err)")
|
||||
#endif
|
||||
self.mutex.deallocate()
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Acquire the lock.
|
||||
@@ -82,7 +89,9 @@ internal final class Lock {
|
||||
/// Whenever possible, consider using `withLock` instead of this method and
|
||||
/// `unlock`, to simplify lock handling.
|
||||
public func lock() {
|
||||
#if os(Windows)
|
||||
#if canImport(WASILibc)
|
||||
// WASILibc is single threaded, provides no locks
|
||||
#elseif os(Windows)
|
||||
AcquireSRWLockExclusive(self.mutex)
|
||||
#else
|
||||
let err = pthread_mutex_lock(self.mutex)
|
||||
@@ -95,7 +104,9 @@ internal final class Lock {
|
||||
/// Whenever possible, consider using `withLock` instead of this method and
|
||||
/// `lock`, to simplify lock handling.
|
||||
public func unlock() {
|
||||
#if os(Windows)
|
||||
#if canImport(WASILibc)
|
||||
// WASILibc is single threaded, provides no locks
|
||||
#elseif os(Windows)
|
||||
ReleaseSRWLockExclusive(self.mutex)
|
||||
#else
|
||||
let err = pthread_mutex_unlock(self.mutex)
|
||||
@@ -164,11 +175,12 @@ internal final class ReadWriteLock {
|
||||
// WASILibc is single threaded, provides no locks
|
||||
#elseif os(Windows)
|
||||
// SRWLOCK does not need to be free'd
|
||||
self.rwlock.deallocate()
|
||||
#else
|
||||
let err = pthread_rwlock_destroy(self.rwlock)
|
||||
precondition(err == 0, "\(#function) failed in pthread_rwlock with error \(err)")
|
||||
#endif
|
||||
self.rwlock.deallocate()
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Acquire a reader lock.
|
||||
|
||||
@@ -114,6 +114,12 @@
|
||||
/// level has not been overridden. And most importantly it passes the requirement listed above: A change to the log
|
||||
/// level on one `Logger` should not affect the log level of another `Logger` variable.
|
||||
public protocol LogHandler: _SwiftLogSendableLogHandler {
|
||||
/// The metadata provider this `LogHandler` will use when a log statement is about to be emitted.
|
||||
///
|
||||
/// A ``Logger/MetadataProvider`` may add a constant set of metadata,
|
||||
/// or use task-local values to pick up contextual metadata and add it to emitted logs.
|
||||
var metadataProvider: Logger.MetadataProvider? { get set }
|
||||
|
||||
/// This method is called when a `LogHandler` must emit a log message. There is no need for the `LogHandler` to
|
||||
/// check if the `level` is above or below the configured `logLevel` as `Logger` already performed this check and
|
||||
/// determined that a message should be logged.
|
||||
@@ -126,18 +132,6 @@ 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?,
|
||||
@@ -175,35 +169,37 @@ public protocol LogHandler: _SwiftLogSendableLogHandler {
|
||||
var logLevel: Logger.Level { get set }
|
||||
}
|
||||
|
||||
extension LogHandler {
|
||||
/// Default implementation for `metadataProvider` which defaults to `nil`.
|
||||
/// This default exists in order to facilitate source-compatible introduction of the `metadataProvider` protocol requirement.
|
||||
public var metadataProvider: Logger.MetadataProvider? {
|
||||
get {
|
||||
nil
|
||||
}
|
||||
set {
|
||||
#if DEBUG
|
||||
if LoggingSystem.warnOnceLogHandlerNotSupportedMetadataProvider(Self.self) {
|
||||
self.log(level: .warning, message: "Attempted to set metadataProvider on \(Self.self) that did not implement support for them. Please contact the log handler maintainer to implement metadata provider support.", metadata: nil, source: "Logging", file: #file, function: #function, line: #line)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension LogHandler {
|
||||
@available(*, deprecated, message: "You should implement this method instead of using the default implementation")
|
||||
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,
|
||||
|
||||
+267
-931
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,113 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Logging API open source project
|
||||
//
|
||||
// Copyright (c) 2018-2022 Apple Inc. and the Swift Logging API project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of Swift Logging API project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
|
||||
import Darwin
|
||||
#elseif os(Windows)
|
||||
import CRT
|
||||
#elseif canImport(Glibc)
|
||||
import Glibc
|
||||
#elseif canImport(WASILibc)
|
||||
import WASILibc
|
||||
#else
|
||||
#error("Unsupported runtime")
|
||||
#endif
|
||||
|
||||
#if compiler(>=5.6)
|
||||
@preconcurrency protocol _SwiftLogSendable: Sendable {}
|
||||
#else
|
||||
protocol _SwiftLogSendable {}
|
||||
#endif
|
||||
|
||||
extension Logger {
|
||||
/// A `MetadataProvider` is used to automatically inject runtime-generated metadata
|
||||
/// to all logs emitted by a logger.
|
||||
///
|
||||
/// ### Example
|
||||
/// A metadata provider may be used to automatically inject metadata such as
|
||||
/// trace IDs:
|
||||
///
|
||||
/// ```swift
|
||||
/// import Tracing // https://github.com/apple/swift-distributed-tracing
|
||||
///
|
||||
/// let metadataProvider = MetadataProvider {
|
||||
/// guard let traceID = Baggage.current?.traceID else { return nil }
|
||||
/// return ["traceID": "\(traceID)"]
|
||||
/// }
|
||||
/// let logger = Logger(label: "example", metadataProvider: metadataProvider)
|
||||
/// var baggage = Baggage.topLevel
|
||||
/// baggage.traceID = 42
|
||||
/// Baggage.withValue(baggage) {
|
||||
/// logger.info("hello") // automatically includes ["traceID": "42"] metadata
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// We recommend referring to [swift-distributed-tracing](https://github.com/apple/swift-distributed-tracing)
|
||||
/// for metadata providers which make use of its tracing and metadata propagation infrastructure. It is however
|
||||
/// possible to make use of metadata providers independently of tracing and instruments provided by that library,
|
||||
/// if necessary.
|
||||
public struct MetadataProvider: _SwiftLogSendable {
|
||||
/// Provide ``Logger.Metadata`` from current context.
|
||||
#if swift(>=5.5) && canImport(_Concurrency) // we could instead typealias the function type, but it was requested that we avoid this for better developer experience
|
||||
@usableFromInline
|
||||
internal let _provideMetadata: @Sendable() -> Metadata
|
||||
#else
|
||||
@usableFromInline
|
||||
internal let _provideMetadata: () -> Metadata
|
||||
#endif
|
||||
|
||||
/// Create a new `MetadataProvider`.
|
||||
///
|
||||
/// - Parameter provideMetadata: A closure extracting metadata from the current execution context.
|
||||
#if swift(>=5.5) && canImport(_Concurrency)
|
||||
public init(_ provideMetadata: @escaping @Sendable() -> Metadata) {
|
||||
self._provideMetadata = provideMetadata
|
||||
}
|
||||
|
||||
#else
|
||||
public init(_ provideMetadata: @escaping () -> Metadata) {
|
||||
self._provideMetadata = provideMetadata
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Invoke the metadata provider and return the generated contextual ``Logger/Metadata``.
|
||||
public func get() -> Metadata {
|
||||
return self._provideMetadata()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Logger.MetadataProvider {
|
||||
/// A pseudo-`MetadataProvider` that can be used to merge metadata from multiple other `MetadataProvider`s.
|
||||
///
|
||||
/// ### Merging conflicting keys
|
||||
///
|
||||
/// `MetadataProvider`s are invoked left to right in the order specified in the `providers` argument.
|
||||
/// In case multiple providers try to add a value for the same key, the last provider "wins" and its value is being used.
|
||||
///
|
||||
/// - Parameter providers: An array of `MetadataProvider`s to delegate to. The array must not be empty.
|
||||
/// - Returns: A pseudo-`MetadataProvider` merging metadata from the given `MetadataProvider`s.
|
||||
public static func multiplex(_ providers: [Logger.MetadataProvider]) -> Logger.MetadataProvider? {
|
||||
assert(!providers.isEmpty, "providers MUST NOT be empty")
|
||||
return Logger.MetadataProvider {
|
||||
providers.reduce(into: [:]) { metadata, provider in
|
||||
let providedMetadata = provider.get()
|
||||
guard !providedMetadata.isEmpty else {
|
||||
return
|
||||
}
|
||||
metadata.merge(providedMetadata, uniquingKeysWith: { _, rhs in rhs })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -31,5 +31,6 @@ XCTMain([
|
||||
testCase(LocalLoggerTest.allTests),
|
||||
testCase(LoggingTest.allTests),
|
||||
testCase(MDCTest.allTests),
|
||||
testCase(MetadataProviderTest.allTests),
|
||||
])
|
||||
#endif
|
||||
@@ -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, metadataProvider: LoggingSystem.metadataProvider)
|
||||
return TestLogHandler(label: label, config: self.config, recorder: self.recorder)
|
||||
}
|
||||
|
||||
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(label:metadataProvider:))
|
||||
LoggingSystem.bootstrapInternal(logging.make)
|
||||
|
||||
// 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(label:metadataProvider:))
|
||||
LoggingSystem.bootstrapInternal(logging.make)
|
||||
|
||||
// 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(label:metadataProvider:))
|
||||
LoggingSystem.bootstrapInternal(logging.make)
|
||||
|
||||
// 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(label:metadataProvider:))
|
||||
LoggingSystem.bootstrapInternal(logging.make)
|
||||
|
||||
// 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(label:metadataProvider:))
|
||||
LoggingSystem.bootstrapInternal(logging.make)
|
||||
|
||||
// change test logging config to log errors and above
|
||||
logging.config.set(value: Logger.Level.error)
|
||||
|
||||
@@ -31,6 +31,8 @@ extension LoggingTest {
|
||||
("testMultiplexLogHandlerNeedNotMaterializeValuesMultipleTimes", testMultiplexLogHandlerNeedNotMaterializeValuesMultipleTimes),
|
||||
("testMultiplexLogHandlerMetadata_settingMetadataThroughToUnderlyingHandlers", testMultiplexLogHandlerMetadata_settingMetadataThroughToUnderlyingHandlers),
|
||||
("testMultiplexLogHandlerMetadata_readingHandlerMetadata", testMultiplexLogHandlerMetadata_readingHandlerMetadata),
|
||||
("testMultiplexMetadataProviderSet", testMultiplexMetadataProviderSet),
|
||||
("testMultiplexMetadataProviderExtract", testMultiplexMetadataProviderExtract),
|
||||
("testDictionaryMetadata", testDictionaryMetadata),
|
||||
("testListMetadata", testListMetadata),
|
||||
("testStringConvertibleMetadata", testStringConvertibleMetadata),
|
||||
@@ -44,14 +46,9 @@ extension LoggingTest {
|
||||
("testLogsEmittedFromSubdirectoryGetCorrectModuleInNewerSwifts", testLogsEmittedFromSubdirectoryGetCorrectModuleInNewerSwifts),
|
||||
("testLogMessageWithStringInterpolation", testLogMessageWithStringInterpolation),
|
||||
("testLoggingAString", testLoggingAString),
|
||||
("testLoggingCallsMetadataProviderWithTaskLocalBaggage", testLoggingCallsMetadataProviderWithTaskLocalBaggage),
|
||||
("testLoggingCallsMetadataProviderWithExplicitlyPassedBaggage", testLoggingCallsMetadataProviderWithExplicitlyPassedBaggage),
|
||||
("testLoggingMergesOneOffMetadataWithProvidedMetadataFromTaskLocalBaggage", testLoggingMergesOneOffMetadataWithProvidedMetadataFromTaskLocalBaggage),
|
||||
("testLoggingMergesOneOffMetadataWithProvidedMetadataFromExplicitlyPassedBaggage", testLoggingMergesOneOffMetadataWithProvidedMetadataFromExplicitlyPassedBaggage),
|
||||
("testLoggingPrefersExplicitBaggageOverTaskLocal", testLoggingPrefersExplicitBaggageOverTaskLocal),
|
||||
("testLoggingWithExplicitlyPassedNilBaggageDoesNotPickUpTaskLocalBaggage", testLoggingWithExplicitlyPassedNilBaggageDoesNotPickUpTaskLocalBaggage),
|
||||
("testMultiplexMetadataProviderMergesInSpecifiedOrder", testMultiplexMetadataProviderMergesInSpecifiedOrder),
|
||||
("testLoggerWithoutFactoryOverrideDefaultsToUsingLoggingSystemMetadataProvider", testLoggerWithoutFactoryOverrideDefaultsToUsingLoggingSystemMetadataProvider),
|
||||
("testLoggerWithPredefinedLibraryMetadataProvider", testLoggerWithPredefinedLibraryMetadataProvider),
|
||||
("testLoggerWithFactoryOverrideDefaultsToUsingLoggingSystemMetadataProvider", testLoggerWithFactoryOverrideDefaultsToUsingLoggingSystemMetadataProvider),
|
||||
("testMultiplexerIsValue", testMultiplexerIsValue),
|
||||
("testLoggerWithGlobalOverride", testLoggerWithGlobalOverride),
|
||||
@@ -61,9 +58,11 @@ extension LoggingTest {
|
||||
("testStreamLogHandlerOutputFormat", testStreamLogHandlerOutputFormat),
|
||||
("testStreamLogHandlerOutputFormatWithMetaData", testStreamLogHandlerOutputFormatWithMetaData),
|
||||
("testStreamLogHandlerOutputFormatWithOrderedMetadata", testStreamLogHandlerOutputFormatWithOrderedMetadata),
|
||||
("testStreamLogHandlerWritesIncludeMetadataProviderMetadata", testStreamLogHandlerWritesIncludeMetadataProviderMetadata),
|
||||
("testStdioOutputStreamWrite", testStdioOutputStreamWrite),
|
||||
("testStdioOutputStreamFlush", testStdioOutputStreamFlush),
|
||||
("testOverloadingError", testOverloadingError),
|
||||
("testCompileInitializeStandardStreamLogHandlersWithMetadataProviders", testCompileInitializeStandardStreamLogHandlersWithMetadataProviders),
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
import InstrumentationBaggage
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Logging API open source project
|
||||
@@ -27,7 +26,7 @@ class LoggingTest: XCTestCase {
|
||||
func testAutoclosure() throws {
|
||||
// bootstrap with our test logging impl
|
||||
let logging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal(logging.make(label:metadataProvider:))
|
||||
LoggingSystem.bootstrapInternal(logging.make)
|
||||
|
||||
var logger = Logger(label: "test")
|
||||
logger.logLevel = .info
|
||||
@@ -221,7 +220,84 @@ class LoggingTest: XCTestCase {
|
||||
XCTAssertEqual(multiplexLogger.handler.metadata, [
|
||||
"one": "111",
|
||||
"two": "222",
|
||||
"in": "in-1",
|
||||
"in": "in-2",
|
||||
])
|
||||
}
|
||||
|
||||
func testMultiplexMetadataProviderSet() {
|
||||
let logging1 = TestLogging()
|
||||
let logging2 = TestLogging()
|
||||
|
||||
var handler1 = logging1.make(label: "1")
|
||||
handler1.metadata["one"] = "111"
|
||||
handler1.metadata["in"] = "in-1"
|
||||
handler1.metadataProvider = .constant([
|
||||
"provider-1": "provided-111",
|
||||
"provider-overlap": "provided-111",
|
||||
])
|
||||
var handler2 = logging2.make(label: "2")
|
||||
handler2.metadata["two"] = "222"
|
||||
handler2.metadata["in"] = "in-2"
|
||||
handler2.metadataProvider = .constant([
|
||||
"provider-2": "provided-222",
|
||||
"provider-overlap": "provided-222",
|
||||
])
|
||||
|
||||
LoggingSystem.bootstrapInternal { _ in
|
||||
MultiplexLogHandler([handler1, handler2])
|
||||
}
|
||||
|
||||
let multiplexLogger = Logger(label: "test")
|
||||
|
||||
XCTAssertEqual(multiplexLogger.handler.metadata, [
|
||||
"one": "111",
|
||||
"two": "222",
|
||||
"in": "in-2",
|
||||
"provider-1": "provided-111",
|
||||
"provider-2": "provided-222",
|
||||
"provider-overlap": "provided-222",
|
||||
])
|
||||
XCTAssertEqual(multiplexLogger.handler.metadataProvider?.get(), [
|
||||
"provider-1": "provided-111",
|
||||
"provider-2": "provided-222",
|
||||
"provider-overlap": "provided-222",
|
||||
])
|
||||
}
|
||||
|
||||
func testMultiplexMetadataProviderExtract() {
|
||||
let logging1 = TestLogging()
|
||||
let logging2 = TestLogging()
|
||||
|
||||
var handler1 = logging1.make(label: "1")
|
||||
handler1.metadataProvider = .constant([
|
||||
"provider-1": "provided-111",
|
||||
"provider-overlap": "provided-111",
|
||||
])
|
||||
var handler2 = logging2.make(label: "2")
|
||||
handler2.metadata["two"] = "222"
|
||||
handler2.metadata["in"] = "in-2"
|
||||
handler2.metadataProvider = .constant([
|
||||
"provider-2": "provided-222",
|
||||
"provider-overlap": "provided-222",
|
||||
])
|
||||
|
||||
LoggingSystem.bootstrapInternal({ _, metadataProvider in
|
||||
MultiplexLogHandler(
|
||||
[handler1, handler2],
|
||||
metadataProvider: metadataProvider
|
||||
)
|
||||
}, metadataProvider: .constant([
|
||||
"provider-overlap": "provided-outer",
|
||||
]))
|
||||
|
||||
let multiplexLogger = Logger(label: "test")
|
||||
|
||||
let provider = multiplexLogger.metadataProvider!
|
||||
|
||||
XCTAssertEqual(provider.get(), [
|
||||
"provider-1": "provided-111",
|
||||
"provider-2": "provided-222",
|
||||
"provider-overlap": "provided-outer",
|
||||
])
|
||||
}
|
||||
|
||||
@@ -231,7 +307,7 @@ class LoggingTest: XCTestCase {
|
||||
|
||||
func testDictionaryMetadata() {
|
||||
let testLogging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal(testLogging.make(label:metadataProvider:))
|
||||
LoggingSystem.bootstrapInternal(testLogging.make)
|
||||
|
||||
var logger = Logger(label: "\(#function)")
|
||||
logger[metadataKey: "foo"] = ["bar": "buz"]
|
||||
@@ -247,7 +323,7 @@ class LoggingTest: XCTestCase {
|
||||
|
||||
func testListMetadata() {
|
||||
let testLogging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal(testLogging.make(label:metadataProvider:))
|
||||
LoggingSystem.bootstrapInternal(testLogging.make)
|
||||
|
||||
var logger = Logger(label: "\(#function)")
|
||||
logger[metadataKey: "foo"] = ["bar", "buz"]
|
||||
@@ -290,7 +366,7 @@ class LoggingTest: XCTestCase {
|
||||
|
||||
func testStringConvertibleMetadata() {
|
||||
let testLogging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal(testLogging.make(label:metadataProvider:))
|
||||
LoggingSystem.bootstrapInternal(testLogging.make)
|
||||
var logger = Logger(label: "\(#function)")
|
||||
|
||||
logger[metadataKey: "foo"] = .stringConvertible("raw-string")
|
||||
@@ -310,7 +386,7 @@ class LoggingTest: XCTestCase {
|
||||
|
||||
func testAutoClosuresAreNotForcedUnlessNeeded() {
|
||||
let testLogging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal(testLogging.make(label:metadataProvider:))
|
||||
LoggingSystem.bootstrapInternal(testLogging.make)
|
||||
|
||||
var logger = Logger(label: "\(#function)")
|
||||
logger.logLevel = .error
|
||||
@@ -324,7 +400,7 @@ class LoggingTest: XCTestCase {
|
||||
|
||||
func testLocalMetadata() {
|
||||
let testLogging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal(testLogging.make(label:metadataProvider:))
|
||||
LoggingSystem.bootstrapInternal(testLogging.make)
|
||||
|
||||
var logger = Logger(label: "\(#function)")
|
||||
logger.info("hello world!", metadata: ["foo": "bar"])
|
||||
@@ -365,7 +441,7 @@ class LoggingTest: XCTestCase {
|
||||
|
||||
func testAllLogLevelsExceptCriticalCanBeBlocked() {
|
||||
let testLogging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal(testLogging.make(label:metadataProvider:))
|
||||
LoggingSystem.bootstrapInternal(testLogging.make)
|
||||
|
||||
var logger = Logger(label: "\(#function)")
|
||||
logger.logLevel = .critical
|
||||
@@ -389,7 +465,7 @@ class LoggingTest: XCTestCase {
|
||||
|
||||
func testAllLogLevelsWork() {
|
||||
let testLogging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal(testLogging.make(label:metadataProvider:))
|
||||
LoggingSystem.bootstrapInternal(testLogging.make)
|
||||
|
||||
var logger = Logger(label: "\(#function)")
|
||||
logger.logLevel = .trace
|
||||
@@ -413,7 +489,7 @@ class LoggingTest: XCTestCase {
|
||||
|
||||
func testAllLogLevelByFunctionRefWithSource() {
|
||||
let testLogging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal(testLogging.make(label:metadataProvider:))
|
||||
LoggingSystem.bootstrapInternal(testLogging.make)
|
||||
|
||||
var logger = Logger(label: "\(#function)")
|
||||
logger.logLevel = .trace
|
||||
@@ -445,7 +521,7 @@ class LoggingTest: XCTestCase {
|
||||
|
||||
func testAllLogLevelByFunctionRefWithoutSource() {
|
||||
let testLogging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal(testLogging.make(label:metadataProvider:))
|
||||
LoggingSystem.bootstrapInternal(testLogging.make)
|
||||
|
||||
var logger = Logger(label: "\(#function)")
|
||||
logger.logLevel = .trace
|
||||
@@ -462,18 +538,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", [:], 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)
|
||||
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)
|
||||
#endif
|
||||
|
||||
testLogging.history.assertExist(level: .trace, message: "yes: trace")
|
||||
@@ -487,7 +563,7 @@ class LoggingTest: XCTestCase {
|
||||
|
||||
func testLogsEmittedFromSubdirectoryGetCorrectModuleInNewerSwifts() {
|
||||
let testLogging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal(testLogging.make(label:metadataProvider:))
|
||||
LoggingSystem.bootstrapInternal(testLogging.make)
|
||||
|
||||
var logger = Logger(label: "\(#function)")
|
||||
logger.logLevel = .trace
|
||||
@@ -511,7 +587,7 @@ class LoggingTest: XCTestCase {
|
||||
|
||||
func testLogMessageWithStringInterpolation() {
|
||||
let testLogging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal(testLogging.make(label:metadataProvider:))
|
||||
LoggingSystem.bootstrapInternal(testLogging.make)
|
||||
|
||||
var logger = Logger(label: "\(#function)")
|
||||
logger.logLevel = .debug
|
||||
@@ -524,7 +600,7 @@ class LoggingTest: XCTestCase {
|
||||
|
||||
func testLoggingAString() {
|
||||
let testLogging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal(testLogging.make(label:metadataProvider:))
|
||||
LoggingSystem.bootstrapInternal(testLogging.make)
|
||||
|
||||
var logger = Logger(label: "\(#function)")
|
||||
logger.logLevel = .debug
|
||||
@@ -538,199 +614,15 @@ 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 providerA = Logger.MetadataProvider { ["provider": "a", "a": "foo"] }
|
||||
let providerB = Logger.MetadataProvider { ["provider": "b", "b": "bar"] }
|
||||
let logger = Logger(label: #function,
|
||||
factory: { label in
|
||||
logging.make(label: label, metadataProvider: .multiplex([providerA, providerB]))
|
||||
})
|
||||
factory: { label in
|
||||
logging.makeWithMetadataProvider(label: label, metadataProvider: .multiplex([providerA, providerB]))
|
||||
})
|
||||
|
||||
logger.log(level: .info, "test", metadata: ["one-off": "42"])
|
||||
|
||||
@@ -741,9 +633,9 @@ class LoggingTest: XCTestCase {
|
||||
|
||||
func testLoggerWithoutFactoryOverrideDefaultsToUsingLoggingSystemMetadataProvider() {
|
||||
let logging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal { label in
|
||||
logging.make(label: label, metadataProvider: .init({ _ in ["provider": "42"] }))
|
||||
}
|
||||
LoggingSystem.bootstrapInternal({ label, metadataProvider in
|
||||
logging.makeWithMetadataProvider(label: label, metadataProvider: metadataProvider)
|
||||
}, metadataProvider: .init { ["provider": "42"] })
|
||||
|
||||
let logger = Logger(label: #function)
|
||||
|
||||
@@ -754,13 +646,29 @@ class LoggingTest: XCTestCase {
|
||||
metadata: ["provider": "42", "one-off": "42"])
|
||||
}
|
||||
|
||||
func testLoggerWithFactoryOverrideDefaultsToUsingLoggingSystemMetadataProvider() {
|
||||
func testLoggerWithPredefinedLibraryMetadataProvider() {
|
||||
let logging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal(
|
||||
metadataProvider: .init({ _ in ["provider": "42"] }),
|
||||
logging.make(label:metadataProvider:))
|
||||
logging.makeWithMetadataProvider,
|
||||
metadataProvider: .exampleMetadataProvider
|
||||
)
|
||||
|
||||
let logger = Logger(label: #function, factory: logging.make(label:metadataProvider:))
|
||||
let logger = Logger(label: #function)
|
||||
|
||||
logger.log(level: .info, "test", metadata: ["one-off": "42"])
|
||||
|
||||
logging.history.assertExist(level: .info,
|
||||
message: "test",
|
||||
metadata: ["example": "example-value", "one-off": "42"])
|
||||
}
|
||||
|
||||
func testLoggerWithFactoryOverrideDefaultsToUsingLoggingSystemMetadataProvider() {
|
||||
let logging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal(logging.makeWithMetadataProvider, metadataProvider: .init { ["provider": "42"] })
|
||||
|
||||
let logger = Logger(label: #function, factory: { label in
|
||||
logging.makeWithMetadataProvider(label: label, metadataProvider: LoggingSystem.metadataProvider)
|
||||
})
|
||||
|
||||
logger.log(level: .info, "test", metadata: ["one-off": "42"])
|
||||
|
||||
@@ -934,7 +842,7 @@ class LoggingTest: XCTestCase {
|
||||
func testStreamLogHandlerOutputFormat() {
|
||||
let interceptStream = InterceptStream()
|
||||
let label = "testLabel"
|
||||
LoggingSystem.bootstrapInternal { _ in
|
||||
LoggingSystem.bootstrapInternal { label in
|
||||
StreamLogHandler(label: label, stream: interceptStream)
|
||||
}
|
||||
let source = "testSource"
|
||||
@@ -954,7 +862,7 @@ class LoggingTest: XCTestCase {
|
||||
func testStreamLogHandlerOutputFormatWithMetaData() {
|
||||
let interceptStream = InterceptStream()
|
||||
let label = "testLabel"
|
||||
LoggingSystem.bootstrapInternal { _ in
|
||||
LoggingSystem.bootstrapInternal { label in
|
||||
StreamLogHandler(label: label, stream: interceptStream)
|
||||
}
|
||||
let source = "testSource"
|
||||
@@ -974,7 +882,7 @@ class LoggingTest: XCTestCase {
|
||||
func testStreamLogHandlerOutputFormatWithOrderedMetadata() {
|
||||
let interceptStream = InterceptStream()
|
||||
let label = "testLabel"
|
||||
LoggingSystem.bootstrapInternal { _ in
|
||||
LoggingSystem.bootstrapInternal { label in
|
||||
StreamLogHandler(label: label, stream: interceptStream)
|
||||
}
|
||||
let log = Logger(label: label)
|
||||
@@ -989,8 +897,26 @@ class LoggingTest: XCTestCase {
|
||||
return
|
||||
}
|
||||
|
||||
XCTAssert(interceptStream.strings[0].contains("a=a0 b=b0"))
|
||||
XCTAssert(interceptStream.strings[1].contains("a=a1 b=b1"))
|
||||
XCTAssert(interceptStream.strings[0].contains("a=a0 b=b0"), "LINES: \(interceptStream.strings[0])")
|
||||
XCTAssert(interceptStream.strings[1].contains("a=a1 b=b1"), "LINES: \(interceptStream.strings[1])")
|
||||
}
|
||||
|
||||
func testStreamLogHandlerWritesIncludeMetadataProviderMetadata() {
|
||||
let interceptStream = InterceptStream()
|
||||
LoggingSystem.bootstrapInternal({ _, metadataProvider in
|
||||
StreamLogHandler(label: "test", stream: interceptStream, metadataProvider: metadataProvider)
|
||||
}, metadataProvider: .exampleMetadataProvider)
|
||||
let log = Logger(label: "test")
|
||||
|
||||
let testString = "my message is better than yours"
|
||||
log.critical("\(testString)")
|
||||
|
||||
let messageSucceeded = interceptStream.interceptedText?.trimmingCharacters(in: .whitespacesAndNewlines).hasSuffix(testString)
|
||||
|
||||
XCTAssertTrue(messageSucceeded ?? false)
|
||||
XCTAssertEqual(interceptStream.strings.count, 1)
|
||||
let message = interceptStream.strings.first!
|
||||
XCTAssertTrue(message.contains("example=example-value"), "message must contain metadata, was: \(message)")
|
||||
}
|
||||
|
||||
func testStdioOutputStreamWrite() {
|
||||
@@ -1095,7 +1021,7 @@ class LoggingTest: XCTestCase {
|
||||
}
|
||||
// bootstrap with our test logging impl
|
||||
let logging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal(logging.make(label:metadataProvider:))
|
||||
LoggingSystem.bootstrapInternal(logging.make)
|
||||
|
||||
var logger = Logger(label: "test")
|
||||
logger.logLevel = .error
|
||||
@@ -1103,6 +1029,30 @@ class LoggingTest: XCTestCase {
|
||||
|
||||
logging.history.assertExist(level: .error, message: "errorDescription")
|
||||
}
|
||||
|
||||
func testCompileInitializeStandardStreamLogHandlersWithMetadataProviders() {
|
||||
// avoid "unreachable code" warnings
|
||||
let dontExecute = Int.random(in: 100 ... 200) == 1
|
||||
guard dontExecute else {
|
||||
return
|
||||
}
|
||||
|
||||
// default usage
|
||||
LoggingSystem.bootstrap(StreamLogHandler.standardOutput)
|
||||
LoggingSystem.bootstrap(StreamLogHandler.standardError)
|
||||
|
||||
// with metadata handler, explicitly, public api
|
||||
LoggingSystem.bootstrap({ label, metadataProvider in
|
||||
StreamLogHandler.standardOutput(label: label, metadataProvider: metadataProvider)
|
||||
}, metadataProvider: .exampleMetadataProvider)
|
||||
LoggingSystem.bootstrap({ label, metadataProvider in
|
||||
StreamLogHandler.standardError(label: label, metadataProvider: metadataProvider)
|
||||
}, metadataProvider: .exampleMetadataProvider)
|
||||
|
||||
// with metadata handler, still pretty
|
||||
LoggingSystem.bootstrap(StreamLogHandler.standardOutput, metadataProvider: .exampleMetadataProvider)
|
||||
LoggingSystem.bootstrap(StreamLogHandler.standardError, metadataProvider: .exampleMetadataProvider)
|
||||
}
|
||||
}
|
||||
|
||||
extension Logger {
|
||||
@@ -1122,6 +1072,16 @@ extension Logger {
|
||||
#endif
|
||||
}
|
||||
|
||||
extension Logger.MetadataProvider {
|
||||
static var exampleMetadataProvider: Self {
|
||||
.init { ["example": .string("example-value")] }
|
||||
}
|
||||
|
||||
static func constant(_ metadata: Logger.Metadata) -> Self {
|
||||
.init { metadata }
|
||||
}
|
||||
}
|
||||
|
||||
// Sendable
|
||||
|
||||
#if compiler(>=5.6)
|
||||
|
||||
@@ -19,7 +19,7 @@ class MDCTest: XCTestCase {
|
||||
func test1() throws {
|
||||
// bootstrap with our test logger
|
||||
let logging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal(logging.make(label:metadataProvider:))
|
||||
LoggingSystem.bootstrapInternal(logging.make)
|
||||
|
||||
// run the program
|
||||
MDC.global["foo"] = "bar"
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Logging API open source project
|
||||
//
|
||||
// Copyright (c) 2018-2019 Apple Inc. and the Swift Logging API project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of Swift Logging API project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// MetadataProviderTest+XCTest.swift
|
||||
//
|
||||
import XCTest
|
||||
|
||||
///
|
||||
/// NOTE: This file was generated by generate_linux_tests.rb
|
||||
///
|
||||
/// Do NOT edit this file directly as it will be regenerated automatically when needed.
|
||||
///
|
||||
|
||||
extension MetadataProviderTest {
|
||||
static var allTests: [(String, (MetadataProviderTest) -> () throws -> Void)] {
|
||||
return [
|
||||
("testLoggingMergesOneOffMetadataWithProvidedMetadataFromExplicitlyPassed", testLoggingMergesOneOffMetadataWithProvidedMetadataFromExplicitlyPassed),
|
||||
("testLogHandlerThatDidNotImplementProvidersButSomeoneAttemptsToSetOneOnIt", testLogHandlerThatDidNotImplementProvidersButSomeoneAttemptsToSetOneOnIt),
|
||||
("testLogHandlerThatDidImplementProvidersButSomeoneAttemptsToSetOneOnIt", testLogHandlerThatDidImplementProvidersButSomeoneAttemptsToSetOneOnIt),
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Logging API open source project
|
||||
//
|
||||
// Copyright (c) 2018-2019 Apple Inc. and the Swift Logging API project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of Swift Logging API project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
@testable import Logging
|
||||
import XCTest
|
||||
|
||||
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
|
||||
import Darwin
|
||||
#elseif os(Windows)
|
||||
import WinSDK
|
||||
#else
|
||||
import Glibc
|
||||
#endif
|
||||
|
||||
final class MetadataProviderTest: XCTestCase {
|
||||
func testLoggingMergesOneOffMetadataWithProvidedMetadataFromExplicitlyPassed() throws {
|
||||
let logging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal(logging.makeWithMetadataProvider,
|
||||
metadataProvider: .init { ["common": "initial"]
|
||||
})
|
||||
|
||||
let logger = Logger(label: #function, metadataProvider: .init {
|
||||
[
|
||||
"common": "provider",
|
||||
"provider": "42",
|
||||
]
|
||||
})
|
||||
|
||||
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"])
|
||||
}
|
||||
|
||||
func testLogHandlerThatDidNotImplementProvidersButSomeoneAttemptsToSetOneOnIt() {
|
||||
#if DEBUG
|
||||
// we only emit these warnings in debug mode
|
||||
let logging = TestLogging()
|
||||
var handler = LogHandlerThatDidNotImplementMetadataProviders(testLogging: logging)
|
||||
|
||||
handler.metadataProvider = .simpleTestProvider
|
||||
|
||||
logging.history.assertExist(level: .warning, message: "Attempted to set metadataProvider on LogHandlerThatDidNotImplementMetadataProviders that did not implement support for them. Please contact the log handler maintainer to implement metadata provider support.", source: "Logging")
|
||||
|
||||
let countBefore = logging.history.entries.count
|
||||
handler.metadataProvider = .simpleTestProvider
|
||||
XCTAssertEqual(countBefore, logging.history.entries.count, "Should only log the warning once")
|
||||
#endif
|
||||
}
|
||||
|
||||
func testLogHandlerThatDidImplementProvidersButSomeoneAttemptsToSetOneOnIt() {
|
||||
#if DEBUG
|
||||
// we only emit these warnings in debug mode
|
||||
let logging = TestLogging()
|
||||
var handler = LogHandlerThatDidImplementMetadataProviders(testLogging: logging)
|
||||
|
||||
handler.metadataProvider = .simpleTestProvider
|
||||
|
||||
logging.history.assertNotExist(level: .warning, message: "Attempted to set metadataProvider on LogHandlerThatDidImplementMetadataProviders that did not implement support for them. Please contact the log handler maintainer to implement metadata provider support.", source: "Logging")
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
extension Logger.MetadataProvider {
|
||||
static var simpleTestProvider: Logger.MetadataProvider {
|
||||
return Logger.MetadataProvider {
|
||||
return ["test": "provided"]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public struct LogHandlerThatDidNotImplementMetadataProviders: LogHandler {
|
||||
let testLogging: TestLogging
|
||||
init(testLogging: TestLogging) {
|
||||
self.testLogging = testLogging
|
||||
}
|
||||
|
||||
public subscript(metadataKey _: String) -> Logging.Logger.Metadata.Value? {
|
||||
get {
|
||||
return nil
|
||||
}
|
||||
set(newValue) {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
public var metadata: Logging.Logger.Metadata = [:]
|
||||
|
||||
public var logLevel: Logging.Logger.Level = .trace
|
||||
|
||||
public func log(level: Logger.Level,
|
||||
message: Logger.Message,
|
||||
metadata: Logger.Metadata?,
|
||||
source: String,
|
||||
file: String,
|
||||
function: String,
|
||||
line: UInt) {
|
||||
self.testLogging.make(label: "fake").log(level: level, message: message, metadata: metadata, source: source, file: file, function: function, line: line)
|
||||
}
|
||||
}
|
||||
|
||||
public struct LogHandlerThatDidImplementMetadataProviders: LogHandler {
|
||||
let testLogging: TestLogging
|
||||
init(testLogging: TestLogging) {
|
||||
self.testLogging = testLogging
|
||||
}
|
||||
|
||||
public subscript(metadataKey _: String) -> Logging.Logger.Metadata.Value? {
|
||||
get {
|
||||
return nil
|
||||
}
|
||||
set(newValue) {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
public var metadata: Logging.Logger.Metadata = [:]
|
||||
|
||||
public var logLevel: Logging.Logger.Level = .trace
|
||||
|
||||
public var metadataProvider: Logger.MetadataProvider?
|
||||
|
||||
public func log(level: Logger.Level,
|
||||
message: Logger.Message,
|
||||
metadata: Logger.Metadata?,
|
||||
source: String,
|
||||
file: String,
|
||||
function: String,
|
||||
line: UInt) {
|
||||
self.testLogging.make(label: "fake").log(level: level, message: message, metadata: metadata, source: source, file: file, function: function, line: line)
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,6 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
import Foundation
|
||||
@testable import Logging
|
||||
import InstrumentationBaggage
|
||||
import XCTest
|
||||
#if os(Windows)
|
||||
import WinSDK
|
||||
@@ -25,18 +24,20 @@ internal struct TestLogging {
|
||||
|
||||
func make(label: String) -> LogHandler {
|
||||
return TestLogHandler(
|
||||
label: label,
|
||||
config: self.config,
|
||||
recorder: self.recorder,
|
||||
metadataProvider: LoggingSystem.metadataProvider)
|
||||
label: label,
|
||||
config: self.config,
|
||||
recorder: self.recorder,
|
||||
metadataProvider: LoggingSystem.metadataProvider
|
||||
)
|
||||
}
|
||||
|
||||
func make(label: String, metadataProvider: Logger.MetadataProvider?) -> LogHandler {
|
||||
func makeWithMetadataProvider(label: String, metadataProvider: Logger.MetadataProvider?) -> LogHandler {
|
||||
return TestLogHandler(
|
||||
label: label,
|
||||
config: self.config,
|
||||
recorder: self.recorder,
|
||||
metadataProvider: metadataProvider)
|
||||
label: label,
|
||||
config: self.config,
|
||||
recorder: self.recorder,
|
||||
metadataProvider: metadataProvider
|
||||
)
|
||||
}
|
||||
|
||||
var config: Config { return self._config }
|
||||
@@ -49,47 +50,42 @@ internal struct TestLogHandler: LogHandler {
|
||||
private var logger: Logger // the actual logger
|
||||
|
||||
let label: String
|
||||
private let metadataProvider: Logger.MetadataProvider?
|
||||
public var 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))
|
||||
self.logger.logLevel = .debug
|
||||
self.metadataProvider = metadataProvider
|
||||
}
|
||||
|
||||
init(label: String, config: Config, recorder: Recorder) {
|
||||
self.label = label
|
||||
self.config = config
|
||||
self.recorder = recorder
|
||||
self.logger = Logger(label: "test", StreamLogHandler.standardOutput(label: label))
|
||||
self.logger.logLevel = .debug
|
||||
self.metadataProvider = LoggingSystem.metadataProvider
|
||||
}
|
||||
|
||||
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
|
||||
// baseline metadata, that was set on handler:
|
||||
var metadata = self._metadataSet ? self.metadata : MDC.global.metadata
|
||||
// contextual metadata, e.g. from task-locals:
|
||||
let contextualMetadata = self.metadataProvider?.get() ?? [:]
|
||||
if !contextualMetadata.isEmpty {
|
||||
metadata.merge(contextualMetadata, uniquingKeysWith: { _, contextual in contextual })
|
||||
}
|
||||
// override using any explicit metadata passed for this log statement:
|
||||
if let explicitMetadata = explicitMetadata {
|
||||
metadata.merge(explicitMetadata, uniquingKeysWith: { _, explicit in explicit })
|
||||
}
|
||||
|
||||
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)
|
||||
@@ -269,10 +265,36 @@ extension History {
|
||||
|
||||
func find(level: Logger.Level, message: String, metadata: Logger.Metadata? = nil, source: String) -> LogEntry? {
|
||||
return self.entries.first { entry in
|
||||
entry.level == level &&
|
||||
entry.message == message &&
|
||||
entry.metadata ?? [:] == metadata ?? [:] &&
|
||||
entry.source == source
|
||||
if entry.level != level {
|
||||
return false
|
||||
}
|
||||
if entry.message != message {
|
||||
return false
|
||||
}
|
||||
if let lhs = entry.metadata, let rhs = metadata {
|
||||
if lhs.count != rhs.count {
|
||||
return false
|
||||
}
|
||||
|
||||
for lk in lhs.keys {
|
||||
if lhs[lk] != rhs[lk] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
for rk in rhs.keys {
|
||||
if lhs[rk] != rhs[rk] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
if entry.source != source {
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ class SendableTest: XCTestCase {
|
||||
#if compiler(>=5.6)
|
||||
func testSendableLogger() async {
|
||||
let testLogging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal(testLogging.make(label:metadataProvider:))
|
||||
LoggingSystem.bootstrapInternal(testLogging.make)
|
||||
|
||||
let logger = Logger(label: "test")
|
||||
let message1 = Logger.Message(stringLiteral: "critical 1")
|
||||
|
||||
@@ -6,7 +6,8 @@ services:
|
||||
image: swift-log:20.04-5.7
|
||||
build:
|
||||
args:
|
||||
base_image: "swiftlang/swift:nightly-main-focal"
|
||||
ubuntu_version: "focal"
|
||||
swift_version: "5.7"
|
||||
|
||||
test:
|
||||
image: swift-log:20.04-5.7
|
||||
|
||||
@@ -3,16 +3,16 @@ version: "3"
|
||||
services:
|
||||
|
||||
runtime-setup:
|
||||
image: swift-log:20.04-main
|
||||
image: swift-log:20.04-5.8
|
||||
build:
|
||||
args:
|
||||
base_image: "swiftlang/swift:nightly-main-focal"
|
||||
base_image: "swiftlang/swift:nightly-5.8-focal"
|
||||
|
||||
test:
|
||||
image: swift-log:20.04-main
|
||||
image: swift-log:20.04-5.8
|
||||
environment:
|
||||
- FORCE_TEST_DISCOVERY=--enable-test-discovery
|
||||
#- SANITIZER_ARG=--sanitize=thread
|
||||
|
||||
shell:
|
||||
image: swift-log:20.04-main
|
||||
image: swift-log:20.04-5.8
|
||||
@@ -0,0 +1,18 @@
|
||||
version: "3"
|
||||
|
||||
services:
|
||||
|
||||
runtime-setup:
|
||||
image: swift-log:22.04-main
|
||||
build:
|
||||
args:
|
||||
base_image: "swiftlang/swift:nightly-main-jammy"
|
||||
|
||||
test:
|
||||
image: swift-log:22.04-main
|
||||
environment:
|
||||
- FORCE_TEST_DISCOVERY=--enable-test-discovery
|
||||
#- SANITIZER_ARG=--sanitize=thread
|
||||
|
||||
shell:
|
||||
image: swift-log:22.04-main
|
||||
@@ -34,26 +34,28 @@ These libraries, by design, don't know about the specific metadata keys that sho
|
||||
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
|
||||
that trace ID from a [Swift Distributed Tracing Baggage](https://github.com/apple/swift-distributed-tracing-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 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 (i.e. task local values).
|
||||
|
||||
We also have a desire to keep `swift-log` a "zero dependencies" library, as it intends only to focus on describing a logging API, and not incur any additional dependencies, so it can be used in the most minimal of projects.
|
||||
|
||||
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?`:
|
||||
`MetadataProvider` is a struct nested in the `Logger` type, sitting alongside `MetadataValue` and the `Metadata`.
|
||||
Its purpose is to _provide_ `Logger.Metadata` from the asynchronous context, by e.g. looking up various task-local values,
|
||||
and converting them into `Logger.Metadata`. This is performed by calling the `get()` function, like so:
|
||||
|
||||
```swift
|
||||
extension Logger {
|
||||
public struct MetadataProvider: Sendable {
|
||||
public var metadata: @Sendable (_ baggage: Baggage?) -> Metadata?
|
||||
|
||||
public init(metadata: @escaping @Sendable (Baggage?) -> Metadata?) {
|
||||
self.metadata = metadata
|
||||
}
|
||||
// ...
|
||||
public init(_ provideMetadata: @escaping @Sendable () -> Metadata)
|
||||
|
||||
public get() -> Metadata
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -61,13 +63,23 @@ extension Logger {
|
||||
### 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`:
|
||||
to define providers in.
|
||||
|
||||
For example, a `MyTracer` implementation of swift-distributed-tracing would be expected to provide a metadata provider
|
||||
that is aware of its own `Baggage` and specific keys it uses to carry the trace and span identifiers, like this:
|
||||
|
||||
```swift
|
||||
import Tracing // swift-distributed-tracing
|
||||
|
||||
extension Logger.MetadataProvider {
|
||||
static let tracer = Logger.MetadataProvider { baggage in
|
||||
guard let spanContext = baggage?.spanContext else { return nil }
|
||||
static let myTracer = Logger.MetadataProvider {
|
||||
guard let baggage = Baggage.current else {
|
||||
return [:]
|
||||
}
|
||||
guard let spanContext = baggage.spanContext else {
|
||||
return [:]
|
||||
}
|
||||
|
||||
return [
|
||||
"traceID": "\(spanContext.traceID)",
|
||||
"spanID": "\(spanContext.spanID)",
|
||||
@@ -82,33 +94,53 @@ A `MetadataProvider` can be set up either globally, on a boot-strapped logging s
|
||||
|
||||
```swift
|
||||
LoggingSystem.bootstrap(
|
||||
metadataProvider: .tracer,
|
||||
metadataProvider: .myTracer,
|
||||
StreamLogHandler.standardOutput
|
||||
)
|
||||
```
|
||||
|
||||
or, on a specific logger, in case some contexts should extract additional information:
|
||||
or, using the metadata provider specific bootstrap method:
|
||||
|
||||
```swift
|
||||
let logger = Logger(label: "example", metadataProvider: .init { baggage in
|
||||
guard let operationID = baggage?.operationID else { return nil }
|
||||
LoggingSystem.bootstrapMetadataProvider(.myTracer)
|
||||
```
|
||||
|
||||
It is also possible to configure a metadata provider on a per-logger basis, like this:
|
||||
|
||||
```swift
|
||||
let logger = Logger(label: "example", metadataProvider: Logger.MetadataProvider {
|
||||
guard let baggage = Baggage.current else {
|
||||
return [:]
|
||||
}
|
||||
guard let operationID = baggage.operationID else {
|
||||
return nil
|
||||
}
|
||||
return ["extra/opID": "\(opID)"]
|
||||
})
|
||||
```
|
||||
|
||||
which _overrides_ the default bootstrapped metadata provider.
|
||||
|
||||
> 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.
|
||||
Once a metadata provider was set up, when a log statement is about to be emitted, the log handler implementation shall
|
||||
invoke it whenever it is about to emit a log statement. This must be done from the same asynchronous context as the log statement
|
||||
was made; I.e. if a log handler were to asynchronously–in a _detached_ task–create the actual log message, the invocation of
|
||||
the metadata provider still _must_ be performed before passing the data over to the other detached task.
|
||||
|
||||
Usually, metadata providers will reach for the task's Swift Distributed Tracing [`Baggage`](https://github.com/apple/swift-distributed-tracing-baggage) which is the mechanism that swift-distributed-tracing
|
||||
and instrumentation libraries use to propagate metadata across asynchronous, as well as process, boundaries. Handlers
|
||||
may also inspect other task-local values, however they should not expect other libraries to be able to propagage those
|
||||
as well as they will propagate `Baggage` values.
|
||||
|
||||
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) {
|
||||
Baggage.withValue(baggage) {
|
||||
test()
|
||||
}
|
||||
|
||||
@@ -127,7 +159,7 @@ 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")
|
||||
precondition(!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) {
|
||||
@@ -144,139 +176,28 @@ extension Logger.MetadataProvider {
|
||||
```
|
||||
|
||||
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.
|
||||
the last provider in the array _wins_ and provides the value.
|
||||
|
||||
### Proposal: Using `Baggage` as the execution context dependent metadata container
|
||||
Note that it is possible to query the `LoggingSystem` for the configured, system-wide, metadata provider,
|
||||
and combine it using a `multiplex` provider if the system-wide provider should not be replaced, but augmented
|
||||
by additional providers.
|
||||
|
||||
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.
|
||||
### Understanding Swift Distributed Tracing `Baggage`
|
||||
|
||||
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.
|
||||
The `Baggage` type is more than just a fancy type-safe container for your values which are meant to be carried across
|
||||
using a single, well-known, [task-local value](https://developer.apple.com/documentation/swift/tasklocal).
|
||||
|
||||
> 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.
|
||||
Values stored in `Baggage` are intended to be carried _across process boundaries_, and e.g. libraries such as HTTP clients,
|
||||
or other RPC mechanisms, or even messaging systems implement distributed tracing [instruments](https://github.com/apple/swift-distributed-tracing/blob/main/Sources/Instrumentation/Instrument.swift)
|
||||
which `inject` and `extract` baggage values into their respective carrier objects, e.g. an `HTTPRequest` in the case of an HTTP client.
|
||||
|
||||
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:
|
||||
In other words, whenever intending to propagate information _across processes_ utilize the `Baggage` type to carry it,
|
||||
and ensure to provide an `Instrument` that is able to inject/extract the values of interest into the carrier types you are interested in.
|
||||
To learn more about baggage and instrumentation, refer to the [Swift Distributed Tracing](https://github.com/apple/swift-distributed-tracing/) library documentation.
|
||||
|
||||
```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]
|
||||
})
|
||||
```
|
||||
#### When to use `Baggage` vs. `Logger[metadataKey:]`
|
||||
|
||||
### 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:]`.
|
||||
While `Baggage` is context-dependent 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")
|
||||
@@ -317,107 +238,25 @@ Baggage.$current.withValue(baggage) {
|
||||
// [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
|
||||
|
||||
### MetadataProviders as a function of `Baggage -> Metadata`
|
||||
|
||||
This was considered and fully developed, however it would cause swift-log to have a dependency on the instrumentation type `Baggage`,
|
||||
which was seen as in-conflict-with the interest of swift-log remaining a zero-dependency library.
|
||||
|
||||
`Baggage` _is_ the well known type that is intended to be used for any kind of distributed systems instrumentation and tracing,
|
||||
however it adds additional complexity and confusion for users who are not interested in this domain. For example, developers
|
||||
may be confused about why `Baggage` and `Logger.Metadata` look somewhat similar, but behave very differently. This complexity
|
||||
is inherent to the two types actually being _very_ different, however we do not want to overwhelm newcomers or developers
|
||||
who are only intending to use swift-log within process. Such developers do not need to care about the added complexities
|
||||
of distributed systems.
|
||||
|
||||
The tradeoff we take here is that every metadata provider will have to perform its own task-local (and therefore also thread-local),
|
||||
access in order to obtain the `Baggage` value, rather than the lookup being able to be performed _once_ and shared between
|
||||
multiple providers when a multiplex provider was configured in the system. We view this tradeoff as worth taking, as the cost
|
||||
of actually formatting the metadata usually strongly dominates the cost of the task-local lookup.
|
||||
|
||||
### 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.
|
||||
@@ -441,7 +280,7 @@ Specifically in logging, this means that _every_ call site for _every_ log state
|
||||
```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
|
||||
InstrumentationSystem.tracer.withSpan("Fetch Store") { span in
|
||||
logger.info("Fetched store.", baggage: span.baggage)
|
||||
}
|
||||
}
|
||||
@@ -457,13 +296,13 @@ try await storesRepository.store(
|
||||
|
||||
### 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.
|
||||
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. Even 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)
|
||||
let contextualLogger = InstrumentationSystem.tracer.populateTraceMetadata(logger)
|
||||
contextualLogger.info("Request received.")
|
||||
```
|
||||
|
||||
|
||||
Reference in new issue
Block a user