mirror of
https://github.com/apple/swift-log
synced 2026-11-28 04:14:20 +00:00
Proposal discussion thread: https://forums.swift.org/t/proposal-slg-0004-metadata-value-attributes-revision-2/86488 Add an extensible per-value attribute mechanism for metadata. ### Motivation: Metadata values in `swift-log` are opaque strings by the time the `LogHandler` receives them. The call site often knows things about a value that the handler cannot infer — for example, whether the value should be redacted in different environments. ### Modifications: - SLG-0004 proposal is updated based on the feedback. - Added `AttributedStringCarrier: CustomStringConvertible`-based mechanism to `Logging`. - Added benchmarks and benchmark thresholds for the new attributed metadata. ### Result: `swift-log` provides an optional extensible mechanism for attaching attributes to metadata values. --------- Co-authored-by: Franz Busch <privat@franz-busch.de>
237 lines
7.2 KiB
Markdown
237 lines
7.2 KiB
Markdown
# Implementing a log handler
|
|
|
|
Create a custom logging backend that provides logging services for your apps and libraries.
|
|
|
|
## Overview
|
|
|
|
To become a compatible logging backend that any SwiftLog consumer can use,
|
|
you need to fulfill a few requirements, primarily conforming to the
|
|
``LogHandler`` protocol.
|
|
|
|
### Implement with value type semantics
|
|
|
|
Your log handler **must be a `struct`** and exhibit value semantics. This
|
|
ensures that changes to one logger don't affect others.
|
|
|
|
To verify that your handler reflects value semantics ensure that it passes this
|
|
test:
|
|
|
|
```swift
|
|
@Test
|
|
func logHandlerValueSemantics() {
|
|
LoggingSystem.bootstrap(MyLogHandler.init)
|
|
var logger1 = Logger(label: "first logger")
|
|
logger1.logLevel = .debug
|
|
logger1[metadataKey: "only-on"] = "first"
|
|
|
|
var logger2 = logger1
|
|
logger2.logLevel = .error // Must not affect logger1
|
|
logger2[metadataKey: "only-on"] = "second" // Must not affect logger1
|
|
|
|
// These expectations must pass
|
|
#expect(logger1.logLevel == .debug)
|
|
#expect(logger2.logLevel == .error)
|
|
#expect(logger1[metadataKey: "only-on"] == "first")
|
|
#expect(logger2[metadataKey: "only-on"] == "second")
|
|
}
|
|
```
|
|
|
|
> Note: In special cases, it is acceptable for a log handler to provide
|
|
> global log level overrides that may affect all log handlers created.
|
|
|
|
### Example implementation
|
|
|
|
Here's a complete example of a simple print-based log handler:
|
|
|
|
```swift
|
|
import Foundation
|
|
import Logging
|
|
|
|
public struct PrintLogHandler: LogHandler {
|
|
private let label: String
|
|
public var logLevel: Logger.Level = .info
|
|
public var metadata: Logger.Metadata = [:]
|
|
|
|
public init(label: String) {
|
|
self.label = label
|
|
}
|
|
|
|
public func log(event: LogEvent) {
|
|
let timestamp = ISO8601DateFormatter().string(from: Date())
|
|
let levelString = event.level.rawValue.uppercased()
|
|
|
|
// Merge handler metadata with message metadata
|
|
let combinedMetadata = Self.prepareMetadata(
|
|
base: self.metadata,
|
|
explicit: event.metadata
|
|
)
|
|
|
|
// Format metadata
|
|
let metadataString = combinedMetadata.map { "\($0.key)=\($0.value)" }.joined(separator: ",")
|
|
|
|
// Create log line and print to console
|
|
let logLine = "\(label) \(timestamp) \(levelString) [\(metadataString)]: \(event.message)"
|
|
print(logLine)
|
|
}
|
|
|
|
public subscript(metadataKey key: String) -> Logger.Metadata.Value? {
|
|
get {
|
|
return self.metadata[key]
|
|
}
|
|
set {
|
|
self.metadata[key] = newValue
|
|
}
|
|
}
|
|
|
|
static func prepareMetadata(
|
|
base: Logger.Metadata,
|
|
explicit: Logger.Metadata?
|
|
) -> Logger.Metadata? {
|
|
var metadata = base
|
|
|
|
guard let explicit else {
|
|
// all per-log-statement values are empty
|
|
return metadata
|
|
}
|
|
|
|
metadata.merge(explicit, uniquingKeysWith: { _, explicit in explicit })
|
|
|
|
return metadata
|
|
}
|
|
}
|
|
|
|
```
|
|
|
|
### Advanced features
|
|
|
|
#### Metadata providers
|
|
|
|
Metadata providers allow you to dynamically add contextual information to all
|
|
log messages without explicitly passing it each time. Common use cases include
|
|
request IDs, user sessions, or trace contexts that should be included in logs
|
|
throughout a request's lifecycle.
|
|
|
|
```swift
|
|
import Foundation
|
|
import Logging
|
|
|
|
public struct PrintLogHandler: LogHandler {
|
|
private let label: String
|
|
public var logLevel: Logger.Level = .info
|
|
public var metadata: Logger.Metadata = [:]
|
|
public var metadataProvider: Logger.MetadataProvider?
|
|
|
|
public init(label: String) {
|
|
self.label = label
|
|
}
|
|
|
|
public func log(event: LogEvent) {
|
|
let timestamp = ISO8601DateFormatter().string(from: Date())
|
|
let levelString = event.level.rawValue.uppercased()
|
|
|
|
// Merge handler metadata with message metadata
|
|
let combinedMetadata = Self.prepareMetadata(
|
|
base: self.metadata,
|
|
provider: self.metadataProvider,
|
|
explicit: event.metadata
|
|
)
|
|
|
|
// Format metadata
|
|
let metadataString = combinedMetadata.map { "\($0.key)=\($0.value)" }.joined(separator: ",")
|
|
|
|
// Create log line and print to console
|
|
let logLine = "\(label) \(timestamp) \(levelString) [\(metadataString)]: \(event.message)"
|
|
print(logLine)
|
|
}
|
|
|
|
public subscript(metadataKey key: String) -> Logger.Metadata.Value? {
|
|
get {
|
|
return self.metadata[key]
|
|
}
|
|
set {
|
|
self.metadata[key] = newValue
|
|
}
|
|
}
|
|
|
|
static func prepareMetadata(
|
|
base: Logger.Metadata,
|
|
provider: Logger.MetadataProvider?,
|
|
explicit: Logger.Metadata?
|
|
) -> Logger.Metadata? {
|
|
var metadata = base
|
|
|
|
let provided = provider?.get() ?? [:]
|
|
|
|
guard !provided.isEmpty || !((explicit ?? [:]).isEmpty) else {
|
|
// all per-log-statement values are empty
|
|
return metadata
|
|
}
|
|
|
|
if !provided.isEmpty {
|
|
metadata.merge(provided, uniquingKeysWith: { _, provided in provided })
|
|
}
|
|
|
|
if let explicit = explicit, !explicit.isEmpty {
|
|
metadata.merge(explicit, uniquingKeysWith: { _, explicit in explicit })
|
|
}
|
|
|
|
return metadata
|
|
}
|
|
}
|
|
```
|
|
|
|
#### Reading metadata attributes in LogHandlers
|
|
|
|
Metadata values can carry attributes alongside their string representation. Attributes are embedded inside
|
|
`MetadataValue` via the `.stringConvertible` case and are accessible through the `value.attributes` property. This
|
|
enables features like sensitivity annotations without any changes to your handler's protocol conformance.
|
|
|
|
To read attributes in your log handler:
|
|
|
|
```swift
|
|
public func log(event: LogEvent) {
|
|
// Merge handler metadata, provider metadata, and event metadata as usual
|
|
var merged = self.metadata
|
|
|
|
if let provider = self.metadataProvider {
|
|
merged.merge(provider.get(), uniquingKeysWith: { _, rhs in rhs })
|
|
}
|
|
|
|
if let eventMetadata = event.metadata {
|
|
merged.merge(eventMetadata, uniquingKeysWith: { _, rhs in rhs })
|
|
}
|
|
|
|
// Read attributes from individual values:
|
|
for (key, value) in merged {
|
|
let attributes = value.attributes // Empty if the value carries no attributes
|
|
|
|
// Process based on your handler's needs
|
|
// For example, check for a custom attribute:
|
|
// if attributes[MyAttribute.self] == .flagged { ... }
|
|
}
|
|
}
|
|
```
|
|
|
|
**Key considerations:**
|
|
|
|
- **Opt-in inspection**: Attributes are invisible unless you call `value.attributes`. Handlers that do not care about
|
|
attributes work without any changes.
|
|
|
|
- **No new protocol requirements**: Reading attributes does not require implementing any new `LogHandler` properties
|
|
or subscripts. The `metadata` property and `metadataKey` subscript work exactly as before.
|
|
|
|
- **Attributes flow through metadata**: Attributed values flow naturally through metadata merging, `MetadataProvider`,
|
|
and `MultiplexLogHandler` — no special handling needed.
|
|
|
|
### Performance considerations
|
|
|
|
1. **Avoid blocking**: Don't block the calling thread for I/O operations.
|
|
2. **Lazy evaluation**: Remember that messages and metadata are autoclosures.
|
|
3. **Memory efficiency**: Don't hold onto large amounts of messages.
|
|
|
|
## See Also
|
|
|
|
- ``LogHandler``
|
|
- ``StreamLogHandler``
|
|
- ``MultiplexLogHandler``
|