From b93451412bb97298ee68ca6ee910e6520a6b9684 Mon Sep 17 00:00:00 2001 From: Samuel Murray Date: Thu, 12 Mar 2026 13:19:26 +0100 Subject: [PATCH] Update proposal SLG-0003 after public review (#419) Motivation: The public review of the original proposal (https://forums.swift.org/t/proposal-slg-0003-standardized-error-metadata-via-logger-convenience/84518) is done, and these changes adjust for what was decided on. Modifications: The main difference is to pass Error instances as-is to LogHandlers, rather than serializing it to metadata in Logger. Co-authored-by: Vladimir Kukushkin --- .../Logging/Docs.docc/Proposals/SLG-0003.md | 193 +++++++++--------- 1 file changed, 101 insertions(+), 92 deletions(-) diff --git a/Sources/Logging/Docs.docc/Proposals/SLG-0003.md b/Sources/Logging/Docs.docc/Proposals/SLG-0003.md index 42bda8d..3c4cc70 100644 --- a/Sources/Logging/Docs.docc/Proposals/SLG-0003.md +++ b/Sources/Logging/Docs.docc/Proposals/SLG-0003.md @@ -1,22 +1,22 @@ -# SLG-0003: Standardized Error Metadata via Logger Convenience +# SLG-0003: Support for Attaching Errors to Log Entries -Add standardized way of attaching data from `Error` instances to log posts. +Add standardized way of attaching data from `Error` instances to log entries. ## Overview - Proposal: SLG-0003 - Author(s): [Samuel Murray](https://github.com/samuelmurray) -- Status: **Awaiting Review** +- Status: **Ready for Implementation** - Issue: [apple/swift-log#291](https://github.com/apple/swift-log/issues/291) - Implementation: - - [apple/swift-log#406](https://github.com/apple/swift-log/pull/406) + - [apple/swift-log#425](https://github.com/apple/swift-log/pull/425) - Related links: - [Lightweight proposals process description](https://github.com/apple/swift-log/blob/main/Sources/Logging/Docs.docc/Proposals/Proposals.md) - [First attempt at solution](https://github.com/apple/swift-log/pull/384) ### Introduction -Add convenience methods on `Logger` that accepts an `Error` instance, which get serialized into `MetadataValue`s in a predefined way. +Add new methods on `Logger` that accept an `Error` instance, which is passed as-is to the underlying `LogHandler`. To ensure backwards compatibility and a smooth adoption, a default implementation where the error is serialized into `MetadataValue`s is provided. ### Motivation @@ -52,7 +52,7 @@ logger.warning("Something went wrong", metadata: ["error.message": "\(error)", " The above is a reasonable way to log a generic error, but it is unlikely that everyone will use the same metadata keys. It is also quite a lot of code, for something that feels like it should be easy to do - i.e. attach an error to a log. -Finally, even if you log errors in a consistent way in your code, you do not control logs generated in other modules/packages that you call. In practice, this makes it so that different parts of your application could log error information under different keys, which, again, makes it harder for tooling. +Finally, even if you log errors in a consistent way in your code, you do not control logs generated in other modules/packages that you use. In practice, this makes it so that different parts of your application could log error information under different keys, which, again, makes it harder for tooling. ### Proposed solution @@ -66,31 +66,46 @@ do { } ``` -This would serialize the error, by stringifying it and extracting the fully qualified type name. This information is added as metadata, merging it with any metadata passed to the `metadata`-parameter. Under the hood, an existing log function is called with the merged metadata. We propose that such convenience methods are added for all log methods (even if it arguably makes less sense for e.g. `trace` and `debug` than `warning`). +The error would get passed as-is to the underlying `LogHandler`, which is free to serialize it in an appropriate way. We propose that such convenience methods are added for all log methods (even if it arguably makes less sense for e.g. `trace` and `debug` than `warning`). There are two clear gains from this: -* It is obvious for the caller _how_ to attach an `Error` to a log (and the caller code also looks cleaner) -* We get a consistent format for logged errors +* It is obvious for the caller _how_ to attach an `Error` to a log (and the caller code also looks cleaner). +* `LogHandler`s are free to serialize the `Error` in an way appropriate to that handler. -Additionally, we propose to add a convenience method on `Logger` to allow the caller to attach error metadata on the logger instance: +A `LogHandler` instance can access the `Error` using a new protocol method. A typical `LogHandler` implementation could be to extract the string representation and type name, and serialize it as metadata. ```swift -do { - try someThrowingFunc() -} catch { - logger.recordError(error) - logger.warning("Something went wrong") +struct ErrorLogHandler: LogHandler { + func log( + level: Logger.Level, + message: Logger.Message, + error: (any Error)?, + metadata: Logger.Metadata?, + source: String, + file: String, + function: String, + line: UInt + ) { + var metadata = metadata ?? [:] + if let error { + metadata.merge([ + "error.message": "\(error)", + "error.type": "\(String(reflecting: type(of: error)))", + ]) { $1 } + } + // ... + } + + /* ... */ } ``` -Similarly to the new logging methods, this would serialize the error and add it as metadata on the logger. This is especially useful if multiple log statements are made, or the logger is passed to other functions where the error metadata is relevant. - -Of course, it might take time for this feature to be widely adopted, but the proposed solution is fully backwards compatible, meaning there is no added downside of having some parts of your code calling the new convenience methods, and other parts manually attaching an error. +As we extend the API of both `Logger` and `LogHandler`, we need to ensure compatibility with existing solutions on both sides. Specifically, users should be able to use the new `Logger` methods with existing `LogHandler`s, and get a reasonable serialization of the error. Otherwise, early adopters would have to manually serialize it _in addition to_ passing it using the new argument, until all `LogHandler`s have been updated. To achieve this, we add a default implementation on the `LogHandler` method, that serializes the `Error` as metadata, similar to the example above. ### Detailed design -The proposed solution is to add a new overload for each log method (`trace`, ..., `critical`) that accepts an `Error` as its second argument, as well as a new overload for `Logger.log`, that accepts an `Error` as its third argument. Similarly, we add a method `recordError` to attach an `Error` as metadata to a logger instance. +The proposed solution is to add a new overload for each log method (`trace`, ..., `critical`) that accepts an `Error` as its second argument, as well as a new overload for `Logger.log`, that accepts an `Error` as its third argument. ```swift extension Logger { @@ -101,7 +116,7 @@ extension Logger { /// /// - parameters: /// - message: The message to be logged. The `message` parameter supports any string interpolation literal. - /// - error: An `Error` related to the event. + /// - error: An `Error` to attach to this log message. /// - metadata: One-off metadata to attach to this log message. /// - source: The source this log message originates from. The value defaults /// to the module that emits the log message. @@ -114,13 +129,14 @@ extension Logger { @inlinable public func trace( _ message: @autoclosure () -> Logger.Message, - error: any Error, + error: (any Error)?, metadata: @autoclosure () -> Logger.Metadata? = nil, source: @autoclosure () -> String? = nil, file: String = #fileID, function: String = #function, line: UInt = #line ) + /// Log a message at the 'debug' log level with the source that you provide. /// /// If ``Level/debug`` is at least as severe as this logger's ``logLevel`` the system logs the message; @@ -128,7 +144,7 @@ extension Logger { /// /// - parameters: /// - message: The message to be logged. The `message` parameter supports any string interpolation literal. - /// - error: An `Error` related to the event. + /// - error: An `Error` to attach to this log message. /// - metadata: One-off metadata to attach to this log message. /// - source: The source this log message originates from. The value defaults /// to the module that emits the log message. @@ -141,7 +157,7 @@ extension Logger { @inlinable public func debug( _ message: @autoclosure () -> Logger.Message, - error: any Error, + error: (any Error)?, metadata: @autoclosure () -> Logger.Metadata? = nil, source: @autoclosure () -> String? = nil, file: String = #fileID, @@ -156,7 +172,7 @@ extension Logger { /// /// - parameters: /// - message: The message to be logged. The `message` parameter supports any string interpolation literal. - /// - error: An `Error` related to the event. + /// - error: An `Error` to attach to this log message. /// - metadata: One-off metadata to attach to this log message. /// - source: The source this log message originates from. The value defaults /// to the module that emits the log message. @@ -169,7 +185,7 @@ extension Logger { @inlinable public func info( _ message: @autoclosure () -> Logger.Message, - error: any Error, + error: (any Error)?, metadata: @autoclosure () -> Logger.Metadata? = nil, source: @autoclosure () -> String? = nil, file: String = #fileID, @@ -184,7 +200,7 @@ extension Logger { /// /// - parameters: /// - message: The message to be logged. The `message` parameter supports any string interpolation literal. - /// - error: An `Error` related to the event. + /// - error: An `Error` to attach to this log message. /// - metadata: One-off metadata to attach to this log message. /// - source: The source this log message originates from. The value defaults /// to the module that emits the log message. @@ -197,7 +213,7 @@ extension Logger { @inlinable public func notice( _ message: @autoclosure () -> Logger.Message, - error: any Error, + error: (any Error)?, metadata: @autoclosure () -> Logger.Metadata? = nil, source: @autoclosure () -> String? = nil, file: String = #fileID, @@ -212,7 +228,7 @@ extension Logger { /// /// - parameters: /// - message: The message to be logged. The `message` parameter supports any string interpolation literal. - /// - error: An `Error` related to the event. + /// - error: An `Error` to attach to this log message. /// - metadata: One-off metadata to attach to this log message. /// - source: The source this log message originates from. The value defaults /// to the module that emits the log message. @@ -225,7 +241,7 @@ extension Logger { @inlinable public func warning( _ message: @autoclosure () -> Logger.Message, - error: any Error, + error: (any Error)?, metadata: @autoclosure () -> Logger.Metadata? = nil, source: @autoclosure () -> String? = nil, file: String = #fileID, @@ -240,7 +256,7 @@ extension Logger { /// /// - parameters: /// - message: The message to be logged. The `message` parameter supports any string interpolation literal. - /// - error: An `Error` related to the event. + /// - error: An `Error` to attach to this log message. /// - metadata: One-off metadata to attach to this log message. /// - source: The source this log message originates from. The value defaults /// to the module that emits the log message. @@ -253,7 +269,7 @@ extension Logger { @inlinable public func error( _ message: @autoclosure () -> Logger.Message, - error: any Error, + error: (any Error)?, metadata: @autoclosure () -> Logger.Metadata? = nil, source: @autoclosure () -> String? = nil, file: String = #fileID, @@ -268,7 +284,7 @@ extension Logger { /// /// - parameters: /// - message: The message to be logged. The `message` parameter supports any string interpolation literal. - /// - error: An `Error` related to the event. + /// - error: An `Error` to attach to this log message. /// - metadata: One-off metadata to attach to this log message. /// - source: The source this log message originates from. The value defaults /// to the module that emits the log message. @@ -281,7 +297,7 @@ extension Logger { @inlinable public func critical( _ message: @autoclosure () -> Logger.Message, - error: any Error, + error: (any Error)?, metadata: @autoclosure () -> Logger.Metadata? = nil, source: @autoclosure () -> String? = nil, file: String = #fileID, @@ -297,7 +313,7 @@ extension Logger { /// - parameters: /// - level: The severity level of the `message`. /// - message: The message to be logged. The `message` parameter supports any string interpolation literal. - /// - error: An `Error` related to the event. + /// - error: An `Error` to attach to this log message. /// - metadata: One-off metadata to attach to this log message. /// - source: The source this log message originates from. The value defaults /// to the module that emits the log message. @@ -311,57 +327,59 @@ extension Logger { public func log( level: Logger.Level, _ message: @autoclosure () -> Logger.Message, - error: any Error, + error: (any Error)?, metadata: @autoclosure () -> Logger.Metadata? = nil, source: @autoclosure () -> String? = nil, file: String = #fileID, function: String = #function, line: UInt = #line ) +} +``` - /// Add an error as logging metadata. +A new method is also added to `LogHandler`, which receives the `Error` passed to `Logger`. + +```swift +protocol LogHandler { + /// The library calls this method when a log handler must emit a log message. /// - /// > Note: Changing the logging metadata only affects the instance of the `Logger` where you change it. - @inlinable - public mutating func recordError(_ error: any Error) + /// 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. + /// + /// - Parameters: + /// - level: The log level of the message. + /// - message: The message to log. To obtain a `String` representation call `message.description`. + /// - error: The `Error` associated to this log message. + /// - metadata: The metadata associated to this log message. + /// - source: The source where the log message originated, for example the logging module. + /// - file: The file this log message originates from. + /// - function: The function this log message originates from. + /// - line: The line this log message originates from. + func log( + level: Logger.Level, + message: Logger.Message, + error: (any Error)?, + metadata: Logger.Metadata?, + source: String, + file: String, + function: String, + line: UInt + ) } ``` -Calling any of the new methods will serialize the `Error`, extracting its string representation and fully qualified type name. These are added as metadata under the keys `"error.message"` and `"error.type"` respectively. A draft implementation can be found in [apple/swift-log#406](https://github.com/apple/swift-log/pull/406). +A default implementation is included via an extension method, that calls the existing `log` function. This is to ensure backwards compatibility, and is similar to how `source` was added. The default implementation will serialize the `Error`, extracting its string representation and fully qualified type name, and add those to the metadata under the keys `"error.message"` and `"error.type"` respectively. -We choose the keys `"error.message"` and `"error.type"` since they correspond to what [ECS](https://www.elastic.co/docs/reference/ecs/ecs-error) and [OpenTelemetry](https://opentelemetry.io/docs/specs/semconv/registry/attributes/error/#error-type) use. +A draft implementation can be found in [apple/swift-log#425](https://github.com/apple/swift-log/pull/425). -We propose that the metadata keys used should be considered stable and part of the `swift-log` API. This makes it so that `LogHandler`s can reliably access this information. This is useful if a `LogHandler` wants to output the logs in a format which uses other keys for error information (e.g. re-map the error to `"err.message"` and `"err.type"`). To facilitate this, we suggest adding these as public static properties. - -```swift -extension Logger { - /// Metadata keys with specific use-cases. - public struct WellKnownMetadataKey: String { - /// If an `Error` is passed to ``Logger/log(level:_:error:metadata:source:file:function:line:)``, this metadata entry will contain its string representation. - public static let errorMessage = "error.message" - /// If an `Error` is passed to ``Logger/log(level:_:error:metadata:source:file:function:line:)``, this metadata entry will contain its fully qualified type name. - public static let errorType = "error.type" - - private init() { - // Private init to prevent initialization - } - } -} -``` - -This also makes it easier to promote that these keys are part of the `swift-log` API. However, it should be noted that users of `Logger` are still allowed to use these keys manually. That is, the following is still valid. - -```swift -logger.warning("Valid log", metadata: ["error.message": ["msg1", "msg2"]]) -``` - -This suggests that a `LogHandler` that wants to extract error information from the metadata must ensure that the expected types are passed. For example, it could opt to re-map any error metadata that contain only strings, and leave any other metadata using those keys untouched. +We choose the keys `"error.message"` and `"error.type"` since they correspond to what [ECS](https://www.elastic.co/docs/reference/ecs/ecs-error) and [OpenTelemetry](https://opentelemetry.io/docs/specs/semconv/registry/attributes/error/#error-type) use. However, we propose that the metadata keys used should **not** be considered stable or part of the `swift-log` API. Instead, if a `LogHandler` wants to use separate keys, it should implement the new protocol method, rather than re-map the metadata keys. ### API stability -The proposed additions are fully backwards compatible, meaning that all existing code will continue to function as is. Additionally, a user of `Logger` can start using the new convenience methods, without any modifications of the `LogHandler`, since a `LogHandler` is already expected to handle `Metadata`. +The proposed additions are fully backwards compatible, meaning that all existing code will continue to function as is. Additionally, a user of `Logger` can start using the new convenience methods, without any modifications of the `LogHandler`, thanks to the default implementation and since a `LogHandler` is already expected to handle `Metadata`. -A potential metadata collision exists when an `Error` is passed via the new methods while the same keys (`"error.message"`, `"error.type"`) are present in metadata: +However, when using the default implementation, a potential metadata collision exists when an `Error` is passed via the new methods while the same keys (`"error.message"`, `"error.type"`) are present in metadata: ```swift logger.warning("Something went wrong", error: error, metadata: ["error.message": "some other info"]) @@ -369,39 +387,30 @@ logger.warning("Something went wrong", error: error, metadata: ["error.message": We recommend that the `error` parameter takes precedence in such cases, with conflicting metadata values discarded. This aligns with the principle that explicit `error:` parameters represent primary data, while the same keys in metadata are likely incidental. In practice, we don't expect callers to deliberately pass conflicting error information. +Conversely, a `LogHandler` can implement the new protocol method, and still function with existing users of `Logger` - the `error` parameter will then always be `nil`. + ### Future directions -A future extension of this could be to pass raw `Error` objects to `LogHandler`s. This would allow them to extract more (or less) information from the `Error`, and serialize it however they want. One could imagine that such an extension would come with a default implementation similar to that in this proposal, so that existing `LogHandler`s would be unaffected. +#### recordError -This would however affect the abstraction layer between `Logger` and `LogHandler`, and so would need a strong justification. +If `swift-log` develops better support for scoped loggers, it might be possible to add a `recordError` method on `Logger`, that would attach the `Error` to all logs in that scope. ### Alternatives considered -#### WellKnownMetadataKey as enum +#### Standardized Error metadata via Logger convenience -It was considered to make `WellKnownMetadataKey` an enum, but seeing as more keys might be added in the future, this enum would have had to be marked `@nonexhaustive` to not make such addition a breaking change. However, using this attribute would limit which Swift versions are supported by `swift-log`, and so was not a good option. +The first proposed solution was to treat the new `Logger` methods as "convenience methods", that simply serialized the `Error` as metadata and did not pass the raw `Error` to `LogHandler`. The end result was similar to the currently proposed default implementation in `LogHandler`. In this solution, the metadata keys (`"error.message"` and `"error.type"`) were considered stable and part of the API, since that allowed for `LogHandler` implementations to re-map the keys (e.g. to `"err.*"`). -#### Pass raw Error objects to LogHandler +Ultimately, this was declined in favor of the current proposal. While the metadata based solution was simple, it lacked the flexibility that passing the raw `Error` allows for. -An alternative would be to pass the `Error` objects directly to the `LogHandler` (as discussed in **"Future directions"**). This was the solution initially proposed in [apple/swift-log#384](https://github.com/apple/swift-log/pull/384). +#### recordError convenience method -The API in `Logger` would be the same, adding new extensions methods that take an `Error` as a parameter, but would also allow a `LogHandler` to directly access the `Error` instance. +In the first iteration, we considered adding a new convenience method `recordError` on `Logger`, that would take an `Error`, serialize it, and add to the metadata on the `Logger`. This would primarily have been useful for when a `Logger` instance were passed down a call hierarchy and the `Error` metadata were relevant further down. However, it doesn't work well with the current proposal, since the serialization happens at a later stage. -```swift -struct CustomLogHandler: LogHandler { - public func log( - level: Logger.Level, - message: Logger.Message, - error: any Error?, // New parameter - metadata: Logger.Metadata?, - source: String, - file: String, - function: String, - line: UInt - ) { - // process log post and serialize error however you like - } -} -``` +#### Using .stringConvertible to pass Error to LogHandler -This was rejected due to breaking the existing abstraction layer between `Logger` and `LogHandler`, while also being questionable how much value it would add. \ No newline at end of file +An alternative way to let the `LogHandler` get access to the raw `Error` would be to use the existing `.stringConvertible` enum case of `MetadataValue`. By putting the `Error` under a well-known metadata key (such as `"error"`), a `LogHandler` could get access to it, without any changes to the `LogHandler` protocol. However, this would only work for `Error`s that conform to `CustomStringConvertible`. + +#### some Error vs any Error + +The error argument in `Logger` was considered to be `some Error` rather than `any Error`. Ultimately, `any Error` was preferred. This is because in most typical use cases (e.g. general catch blocks), the error is an existential, so by using `some Error` we would get a slight performance penalty. \ No newline at end of file