From 5abb878a84ef65f251024dcc02e14c295f3de5c4 Mon Sep 17 00:00:00 2001 From: Konrad `ktoso` Malawski Date: Fri, 16 Sep 2022 19:41:38 +0900 Subject: [PATCH] Some additions --- proposals/xxxx-metadata-providers.md | 232 +++++++++++++++++++++------ 1 file changed, 187 insertions(+), 45 deletions(-) diff --git a/proposals/xxxx-metadata-providers.md b/proposals/xxxx-metadata-providers.md index 7eb9b4c..b333044 100644 --- a/proposals/xxxx-metadata-providers.md +++ b/proposals/xxxx-metadata-providers.md @@ -2,58 +2,105 @@ ## Introduction -While global metadata attributes may be manually set on a `LogHandler` level, -there's currently no way of providing runtime-generated metadata on a global level. +While global metadata attributes may be manually set on a `LogHandler` level, there's currently no way of reliably providing contextual, automatically propagated, metadata when logging with swift-log. ## Motivation -To benefit from tools such as [Distributed Tracing](https://github.com/apple/swift-distributed-tracing) it is of great -importance that all logs include runtime-generated metadata such as a trace ID. This allows for patterns such as -automatic log correlation. +To benefit from tools such as [Distributed Tracing](https://github.com/apple/swift-distributed-tracing) it is necessary for libraries to make use of the trace information. -The only currently supported way of providing such metadata is to pass them along to each log call explicitly: +Most notably, loggers should participate in tracing by including some trace metadata (such as e.g. a `trace-id`) when logging, as it transparently enables developers to benefit from log correlation using those IDs. + +Today, the only supported way of providing such metadata is to pass them along to each log call explicitly: ```swift -let traceID = "my-awesome-trace-id" -logger.info("first this ...", metadata: ["trace-id": traceID]) -logger.info("... now this", metadata: ["trace-id": traceID]) +logger.info("first this ...", metadata: ["trace-id": MyTracingLibrary.currentTraceID]) +logger.info("... now this", metadata: ["trace-id": MyTracingLibrary.currentTraceID]) ``` This comes with a couple of downsides: -### Easy to forget for end-users +### Error-prone and repetetive -It's easy to forget passing this metadata to all log statements, resulting in an inconsistent debugging -experience in the case of Distributed Tracing which doesn't paint the full picture. +It's easy to forget passing this metadata to _all_ log statements, resulting in an inconsistent debugging experience leading to log statements, resulting in log statements which cannot be found using correlation IDs. + +The repetetiveness and verboseness of logging multiple metadata in-line quickly becomes annoying and vastly decreases the signal-to-noise ratio of Swift code trying to be a good citizen and making use of log correlation techniques such as distributed tracing. ### Impossible to implement for libraries A large portion of logs are not generated by the end-user but by libraries such as AsyncHTTPClient, Vapor etc. -These libraries don't necesarilly have access to the elsewhere runtime-generated metadata that should be included in -their logs as well. +These libraries, by design, don't know about the specific metadata keys that should be included in the logs. +Those keys are after all runtime dependent, and may change depending on what tracing system is configured by the end user. For example, a specific `Tracer` implementation would use a type representing a trace ID, and has a way of extracting -that trace ID from a `Baggage`. But other libraries don't know about this specific trace ID so would inherently not be +that trace ID from a `Baggage`. But other libraries can't know about this _specific_ trace ID and therefore would not be able to pass such values along to their log statements. ## Proposed solution -To support this kind of runtime-generated metadata in `swift-log`, a new API is needed. Our proposed API is called -_metadata providers_, which boils down to a function with the following signature: +To support this kind of runtime-generated metadata in `swift-log`, we need to extend the logging APIs in an open-ended way, to allow any kinds of metadata to be provided from the asynchronous context. + +To solve this, we propose the extension of swift-log APIs with a new concept: _metadata providers_. + +Generally speaking, a metadata provider takes the form of the following function signature: ```swift -(Baggage?) -> Metadata? +typealias MetadataProvider = (Baggage?) -> Metadata? ``` -### Using Baggage as the metadata container +and can be set up either globally, on a boot-strapped logging system: -This proposal also includes adding a dependency -on [Swift Distributed Tracing Baggage](https://github.com/apple/swift-distributed-tracing-baggage) to be used as the -container passed to these metadata providers. +```swift +LoggingSystem.bootstrap(...) - +// tracer +LoggingSystem.provideMetadata { baggage in + guard let traceID = baggage?.traceID else { + return nil + + } + return ["trace-id": "\(traceID)"] +} +``` -The end-user configures a metadata provider on a specific `Logger` via a new initializer parameter: +or, on a specific logger, in case some contexts should extract additional information: + +```swift +var log = Logger(label: "example") + +log.provideMetadata { baggage in + guard let opID = baggage?.operationID else { return nil } + return ["extra/opID": "\(opID)"] +} +``` + +Once a metadata providers have been set up, they will be invoked when a log statement is about to be emitted. +Multiple metadata providers may be configured, and they are invoked in registration order. + +Next, when a log statement is about to be emitted, the logger will obtain the task-local `Baggage.current`, +and pass it to the metadata providers. The providers can then convert specific baggage items into logger metadata as they see fit. + +Those metadata will be then included in the log statement, e.g. like this: + +```swift +Extra.$operationID.withValue("1234-5678") { + test() +} + +func test() { + log.info("Test") + // info [extra/opID: 1234-5678] Test +} +``` + +### Proposal: Using `Baggage` as the execution context dependent metadata container + +We propose that swift-log should use [Swift Distributed Tracing Baggage](https://github.com/apple/swift-distributed-tracing-baggage) for its contextual metadata propagation type, meaning that swift-log would depend on this package. + +The `Baggage` type is modeled after the [Propagation format for distributed context: Baggage](https://www.w3.org/TR/baggage/), a W3C working draft, and is intended for all kinds of instrumentation of Swift applications both within and across processes. It is also used by [Swift Distributed Tracing](https://github.com/apple/swift-distributed-tracing-baggage), however it is usable even without tracing infrastructure. The baggage package contains the single `Baggage` type, and is expected to have a stable, unchanging API, fit for swift-log to depend upon. + +> NOTE: We could potentially even rename the baggage package, if the tracing wording in it is causing confusion here. But realistically, this is its primary purpose: to enable tracing in logging systems, so we think swift-log dependin on `swift-distributed-tracing-baggage` is fine. + +To start using contextual metadata, end-users configure a metadata provider on the entire logging on a specific `Logger` via a new initializer parameter: ```swift let logger = Logger(label: "example", metadataProvider: { baggage in @@ -66,35 +113,130 @@ let logger = Logger(label: "example", metadataProvider: { baggage in ### Task-local Baggage -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: +> 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 { - // unrelated code location parameters left out + @inlinable func log(level: Logger.Level, - _ message: @autoclosure () -> Logger.Message, - metadata: @autoclosure () -> Logger.Metadata? = nil, - baggage: Baggage? = .current) { - } { - // implementation + _ message: @autoclosure () -> Logger.Message, + metadata: @autoclosure () -> Logger.Metadata? = nil, + source: @autoclosure () -> String? = nil, + file: String = #fileID, function: String = #function, line: UInt = #line) + { + if self.logLevel <= level { + let baggage: Baggage? = Baggage.current + self.handler.log(level: level, + message: message(), + metadata: metadata(), + baggage: Baggage.current, // picks up the task-local 🧳 + source: source() ?? Logger.currentModule(fileID: (file)), + file: file, function: function, line: line) + } } } - -var baggage = Baggage.topLevel -baggage[TestIDKey.self] = "my-awesome-trace-id" -Baggage.$current.withValue(baggage) { - logger.log(level: .info, "example", metadata: ["one-off": "example"]) - // passes both "one-off" and "trace-id" metadata to the log handler -} ``` -This has the advantage of not having to specify the global metadata explicitly anymore. It 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 +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. + +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 + func log(level: Logger.Level, + _ message: @autoclosure () -> Logger.Message, + metadata: @autoclosure () -> Logger.Metadata? = nil, + baggage: Baggage? = nil, + source: @autoclosure () -> String? = nil, + file: String = #fileID, function: String = #function, line: UInt = #line) + { + if self.logLevel <= level { + let baggage: Baggage? = Baggage.current + self.handler.log(level: level, + message: message(), + metadata: metadata(), + baggage: baggage, + 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 to to benefit from contextual metadata, propagated with baggage is log, 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`. -### Explicitly passing Baggage +### Using Baggage in callback APIs -Some libraries currently provide an `async` API shell around a mostly NIO-based internal implementation. The proposed -strategy for such libraries is to capture the task-local `Baggage` within the `async` API, then pass it along inside the -NIO-based internals, and finally pass this `Baggage` along to their log statements. +Many libraries which provide a `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). + +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 wheretask-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` + - `*` 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() }` + + +## Alternatives considered + +### Removing `LogHandler.Metadata` in favor of `Baggage` + +Removing logger metadata is not a good option because it serves a slightly different style of metadata than the baggage. + +Baggage is intended for contextual, task-local, metadata which is _carried across multiple libraries_. The values stored in baggage are well-typed, and must declare keys for accessing values in a baggage, this works well for multiple pieces of an application needing to reach for specific baggage items: everyone aware of the `traceID` key, is able to query the baggage for this key (`baggage.traceID`) and obtain a well-typed value. This comes with a higher cost on declaring keys though, as well as a global namespace for those - which is desirable for such kinds of metadata. + +This is not the same usage pattern as emitting a plain structured log where we'd like to include the name of an item we just queried: + +```swift +log.info("Obtained item! Hooray!", metadata: ["item": "\(item)"]) +``` + +In this example, the key/value pair for `"item"` is pretty ad-hoc, and we never need to refer to it elsewhere in the program. It never is queried by other pieces of the application, nor would it be useful to set it in baggage metadata, as the only purpose of the `item` key here is to log, and forget about it. + +### Explicitly passing `Baggage` always + +Baggage is designed for use cases like distributed tracing, or similar instrumentation patterns where "all" participating code may need to reach for it. + +Specifically in logging, this means that _every_ call site for _every_ log statement would have to pass it explicitly resulting in annoying noisy code: + +```swift +log.info +```