mirror of
https://github.com/apple/swift-log
synced 2026-11-22 03:40:39 +00:00
Give `Logger.handler` a `_modify` accessor and replace its `get` with `_read`, so metadata writes update the stored handler instead of a copy. ### Motivation: `Logger.handler` only has `get` and `set`. A write such as `logger[metadataKey: "k"] = "v"` gets a copy of the handler, writes to it while the stored handler still shares the metadata dictionary, and sets it back. So every write copies the whole dictionary, and `withLogger(mergingMetadata:)` does that once per key. ### Modifications: - Give `Logger.handler` `_read`, `set` and `_modify` accessors. `_read` yields the stored handler. `_modify` keeps the existing uniqueness check on the storage and then yields the stored handler, so metadata and log level writes change it in place. `set` keeps the same check for plain `logger.handler = newHandler` assignments, which are cheaper through a setter than through `_modify`. - Add a test handler that counts copies of its metadata, with tests for direct writes and for `withLogger(mergingMetadata:)`. Without the change they report 10 copies instead of 0, and 5 instead of 1. ### Result: A metadata write on a logger that owns its storage no longer copies the dictionary. A copied logger still copies once on its first write, so value semantics are unchanged. 1,000 metadata writes with a handler that keeps metadata in a plain dictionary, debug build, three runs each: | Keys on the logger | Before | After | |---|---|---| | 10 | 7.2 to 8.1 ms | 0.46 to 0.50 ms | | 1,000 | 20.2 to 20.6 ms | 0.46 to 0.55 ms | | 10,000 | 134.0 to 134.4 ms | 0.47 to 0.50 ms | | 100,000 | 1.29 to 1.30 s | 0.32 to 0.35 ms | `withLogger(mergingMetadata:)` with 10,000 keys went from 0.64 to 0.65 s down to 2.9 to 3.1 ms. `StreamLogHandler` still rebuilds its pretty metadata string on every write; this change does not touch that. All 176 tests pass on macOS with Swift 6.4, and `swift format lint --strict` and `swift package diagnose-api-breaking-changes` are clean. Once yielding accessors land, `_read` and `_modify` can become `yielding borrow` and `yielding mutate`. Fixes #526.
449 lines
16 KiB
Swift
449 lines
16 KiB
Swift
//===----------------------------------------------------------------------===//
|
|
//
|
|
// This source file is part of the Swift Logging API open source project
|
|
//
|
|
// Copyright (c) 2025 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 Testing
|
|
|
|
@testable import Logging
|
|
|
|
struct TaskLocalLoggerTest {
|
|
// MARK: - Binding a logger
|
|
|
|
@Test func bindLogger() {
|
|
let logging = TestLogging()
|
|
let logger = Logger(label: "test", factory: { logging.make(label: $0) })
|
|
|
|
withLogger(logger) { logger in
|
|
logger.info("bound")
|
|
}
|
|
|
|
logging.history.assertExist(level: .info, message: "bound")
|
|
}
|
|
|
|
@Test func bindLoggerAsyncReturning() async {
|
|
let logging = TestLogging()
|
|
let logger = Logger(label: "test", factory: { logging.make(label: $0) })
|
|
|
|
let result = await withLogger(logger) { logger -> Int in
|
|
await Task.yield()
|
|
logger.info("computing")
|
|
return 42
|
|
}
|
|
|
|
#expect(result == 42)
|
|
logging.history.assertExist(level: .info, message: "computing")
|
|
}
|
|
|
|
/// The bind overload replaces the task-local logger; accumulated metadata from an
|
|
/// enclosing `withLogger(mergingMetadata:)` scope is intentionally not carried over.
|
|
@Test func bindReplacesAccumulatedMetadata() {
|
|
let logging1 = TestLogging()
|
|
let logging2 = TestLogging()
|
|
let root = Logger(label: "root", factory: { logging1.make(label: $0) })
|
|
let other = Logger(label: "other", factory: { logging2.make(label: $0) })
|
|
|
|
withLogger(root) { _ in
|
|
withLogger(mergingMetadata: ["request.id": "r1"]) { _ in
|
|
withLogger(other) { inner in
|
|
inner.info("no request.id")
|
|
}
|
|
}
|
|
}
|
|
|
|
let entry = logging2.history.entries.first { $0.message == "no request.id" }
|
|
#expect(entry?.metadata?["request.id"] == nil)
|
|
}
|
|
|
|
// MARK: - Modifying the current logger
|
|
|
|
@Test func mergeMetadata() {
|
|
let logging = TestLogging()
|
|
let logger = Logger(label: "test", factory: { logging.make(label: $0) })
|
|
|
|
withLogger(logger) { _ in
|
|
withLogger(mergingMetadata: ["key": "value"]) { logger in
|
|
logger.info("merged")
|
|
}
|
|
}
|
|
|
|
logging.history.assertExist(level: .info, message: "merged", metadata: ["key": "value"])
|
|
}
|
|
|
|
@Test func mergeMetadataCopiesHandlerOnce() {
|
|
let logger = Logger(label: "test", factory: { _ in CopyCountingLogHandler() })
|
|
let metadata: Logger.Metadata = ["a": "1", "b": "2", "c": "3", "d": "4", "e": "5"]
|
|
|
|
withLogger(logger) { _ in
|
|
withLogger(mergingMetadata: metadata) { inner in
|
|
#expect(inner.handler.metadata == metadata)
|
|
#expect(inner.handlerCopies == 1)
|
|
}
|
|
#expect(Logger.current.handler.metadata.isEmpty)
|
|
#expect(Logger.current.handlerCopies == 0)
|
|
}
|
|
}
|
|
|
|
@Test func overrideLogLevel() {
|
|
let logging = TestLogging()
|
|
let logger = Logger(label: "test", factory: { logging.make(label: $0) })
|
|
|
|
withLogger(logger) { _ in
|
|
withLogger(logLevel: .warning) { logger in
|
|
logger.debug("suppressed")
|
|
logger.warning("emitted")
|
|
}
|
|
}
|
|
|
|
logging.history.assertNotExist(level: .debug, message: "suppressed")
|
|
logging.history.assertExist(level: .warning, message: "emitted")
|
|
}
|
|
|
|
@Test func nestedMetadataAccumulates() {
|
|
let logging = TestLogging()
|
|
let logger = Logger(label: "test", factory: { logging.make(label: $0) })
|
|
|
|
withLogger(logger) { _ in
|
|
withLogger(mergingMetadata: ["level1": "first"]) { _ in
|
|
withLogger(mergingMetadata: ["level2": "second"]) { logger in
|
|
logger.info("inner")
|
|
}
|
|
}
|
|
}
|
|
|
|
logging.history.assertExist(
|
|
level: .info,
|
|
message: "inner",
|
|
metadata: ["level1": "first", "level2": "second"]
|
|
)
|
|
}
|
|
|
|
@Test func innerMetadataOverridesOuter() {
|
|
let logging = TestLogging()
|
|
let logger = Logger(label: "test", factory: { logging.make(label: $0) })
|
|
|
|
withLogger(logger) { _ in
|
|
withLogger(mergingMetadata: ["key": "outer"]) { _ in
|
|
withLogger(mergingMetadata: ["key": "inner"]) { logger in
|
|
logger.info("test")
|
|
}
|
|
}
|
|
}
|
|
|
|
logging.history.assertExist(level: .info, message: "test", metadata: ["key": "inner"])
|
|
}
|
|
|
|
/// The modifying `withLogger(metadata:)` overload replaces the inherited metadata
|
|
/// rather than layering — passing `[:]` wipes; passing a fresh dict starts the scope
|
|
/// from a known state.
|
|
@Test func metadataReplacesInherited() {
|
|
let logging = TestLogging()
|
|
let logger = Logger(label: "test", factory: { logging.make(label: $0) })
|
|
|
|
withLogger(logger) { _ in
|
|
withLogger(mergingMetadata: ["request.id": "r1", "user.id": "u1"]) { _ in
|
|
withLogger(metadata: ["job.id": "j1"]) { scoped in
|
|
scoped.info("background")
|
|
}
|
|
}
|
|
}
|
|
|
|
let entry = logging.history.entries.first { $0.message == "background" }
|
|
#expect(entry?.metadata?["job.id"] == "j1")
|
|
#expect(entry?.metadata?["request.id"] == nil)
|
|
#expect(entry?.metadata?["user.id"] == nil)
|
|
}
|
|
|
|
@Test func metadataEmptyDictWipesInherited() {
|
|
let logging = TestLogging()
|
|
let logger = Logger(label: "test", factory: { logging.make(label: $0) })
|
|
|
|
withLogger(logger) { _ in
|
|
withLogger(mergingMetadata: ["request.id": "r1"]) { _ in
|
|
withLogger(metadata: [:]) { scoped in
|
|
scoped.info("wiped")
|
|
}
|
|
}
|
|
}
|
|
|
|
let entry = logging.history.entries.first { $0.message == "wiped" }
|
|
#expect(entry?.metadata?.isEmpty ?? true)
|
|
}
|
|
|
|
/// `withLogger(handler:)` routes logs to a different handler for the scope — the
|
|
/// canonical use is swapping in an in-memory handler to capture logs for assertions
|
|
/// in a test.
|
|
@Test func handlerSwapsForScope() {
|
|
let outer = TestLogging()
|
|
let inner = TestLogging()
|
|
let appLogger = Logger(label: "app", factory: { outer.make(label: $0) })
|
|
|
|
withLogger(appLogger) { _ in
|
|
for _ in outer.history.entries {} // touch outer so we can see the drift
|
|
withLogger(handler: inner.make(label: "captured"), metadata: ["case": "test"]) { scoped in
|
|
scoped.info("emitted under inner handler")
|
|
}
|
|
appLogger.info("back under outer")
|
|
}
|
|
|
|
inner.history.assertExist(
|
|
level: .info,
|
|
message: "emitted under inner handler",
|
|
metadata: ["case": "test"]
|
|
)
|
|
inner.history.assertNotExist(level: .info, message: "back under outer")
|
|
outer.history.assertExist(level: .info, message: "back under outer")
|
|
outer.history.assertNotExist(level: .info, message: "emitted under inner handler")
|
|
}
|
|
|
|
@Test(arguments: [Logger.Level.debug, .warning])
|
|
func handlerSwapRespectsExplicitLogLevel(level: Logger.Level) {
|
|
let outer = TestLogging()
|
|
let inner = TestLogging()
|
|
var appLogger = Logger(label: "app", factory: { outer.make(label: $0) })
|
|
appLogger.logLevel = .critical
|
|
var replacement = inner.make(label: "captured")
|
|
replacement.logLevel = .info
|
|
let suppressedLevel: Logger.Level = level == .debug ? .trace : .info
|
|
|
|
withLogger(appLogger) { _ in
|
|
withLogger(logLevel: level, handler: replacement) { scoped in
|
|
#expect(scoped.logLevel == level)
|
|
#expect(Logger.current.logLevel == level)
|
|
scoped.log(level: level, "emitted")
|
|
Logger.current.log(level: suppressedLevel, "suppressed")
|
|
}
|
|
#expect(Logger.current.logLevel == .critical)
|
|
}
|
|
|
|
#expect(replacement.logLevel == .info)
|
|
inner.history.assertExist(level: level, message: "emitted")
|
|
inner.history.assertNotExist(level: suppressedLevel, message: "suppressed")
|
|
outer.history.assertNotExist(level: level, message: "emitted")
|
|
}
|
|
|
|
@Test(arguments: [Logger.Level.debug, .warning])
|
|
func asyncHandlerSwapRespectsExplicitLogLevel(level: Logger.Level) async {
|
|
let outer = TestLogging()
|
|
let inner = TestLogging()
|
|
var appLogger = Logger(label: "app", factory: { outer.make(label: $0) })
|
|
appLogger.logLevel = .critical
|
|
var replacement = inner.make(label: "captured")
|
|
replacement.logLevel = .info
|
|
let suppressedLevel: Logger.Level = level == .debug ? .trace : .info
|
|
|
|
await withLogger(appLogger) { _ in
|
|
await withLogger(logLevel: level, handler: replacement) { scoped in
|
|
await Task.yield()
|
|
#expect(scoped.logLevel == level)
|
|
#expect(Logger.current.logLevel == level)
|
|
scoped.log(level: level, "emitted")
|
|
Logger.current.log(level: suppressedLevel, "suppressed")
|
|
}
|
|
#expect(Logger.current.logLevel == .critical)
|
|
}
|
|
|
|
#expect(replacement.logLevel == .info)
|
|
inner.history.assertExist(level: level, message: "emitted")
|
|
inner.history.assertNotExist(level: suppressedLevel, message: "suppressed")
|
|
outer.history.assertNotExist(level: level, message: "emitted")
|
|
}
|
|
|
|
@Test func siblingScopesAreIsolated() {
|
|
let logging = TestLogging()
|
|
let logger = Logger(label: "test", factory: { logging.make(label: $0) })
|
|
|
|
withLogger(logger) { _ in
|
|
withLogger(mergingMetadata: ["a": "1"]) { logger in
|
|
logger.info("first")
|
|
}
|
|
withLogger(mergingMetadata: ["b": "2"]) { logger in
|
|
logger.info("second")
|
|
}
|
|
}
|
|
|
|
let second = logging.history.entries.first { $0.message == "second" }
|
|
#expect(second?.metadata?["a"] == nil)
|
|
#expect(second?.metadata?["b"] == "2")
|
|
}
|
|
|
|
// MARK: - Async propagation and task isolation
|
|
|
|
@Test func contextPreservedAcrossAwait() async throws {
|
|
let logging = TestLogging()
|
|
let logger = Logger(label: "test", factory: { logging.make(label: $0) })
|
|
|
|
await withLogger(logger) { _ in
|
|
await withLogger(mergingMetadata: ["request": "123"]) { logger in
|
|
logger.info("before await")
|
|
await Task.yield()
|
|
logger.info("after await")
|
|
}
|
|
}
|
|
|
|
logging.history.assertExist(level: .info, message: "before await", metadata: ["request": "123"])
|
|
logging.history.assertExist(level: .info, message: "after await", metadata: ["request": "123"])
|
|
}
|
|
|
|
@Test func childTaskInheritsContextDetachedDoesNot() async {
|
|
let logging = TestLogging()
|
|
let logger = Logger(label: "test", factory: { logging.make(label: $0) })
|
|
|
|
await withLogger(logger) { _ in
|
|
await withLogger(mergingMetadata: ["parent": "value"]) { _ in
|
|
await Task {
|
|
Logger.current.info("child")
|
|
}.value
|
|
await Task.detached {
|
|
Logger.current.info("detached")
|
|
}.value
|
|
}
|
|
}
|
|
|
|
logging.history.assertExist(level: .info, message: "child", metadata: ["parent": "value"])
|
|
// Detached task starts without a task-local logger and falls back to a freshly
|
|
// constructed `Logger(label: "")`, which doesn't reach our per-test TestLogging.
|
|
logging.history.assertNotExist(level: .info, message: "detached")
|
|
}
|
|
|
|
@Test func concurrentTasksHaveIndependentContext() async {
|
|
let logging = TestLogging()
|
|
let logger = Logger(label: "test", factory: { logging.make(label: $0) })
|
|
|
|
await withLogger(logger) { _ in
|
|
await withLogger(mergingMetadata: ["context": "parent"]) { _ in
|
|
await withTaskGroup(of: Void.self) { group in
|
|
group.addTask {
|
|
withLogger(mergingMetadata: ["task": "1"]) { logger in
|
|
logger.info("task 1")
|
|
}
|
|
}
|
|
group.addTask {
|
|
withLogger(mergingMetadata: ["task": "2"]) { logger in
|
|
logger.info("task 2")
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
logging.history.assertExist(
|
|
level: .info,
|
|
message: "task 1",
|
|
metadata: ["task": "1", "context": "parent"]
|
|
)
|
|
logging.history.assertExist(
|
|
level: .info,
|
|
message: "task 2",
|
|
metadata: ["task": "2", "context": "parent"]
|
|
)
|
|
}
|
|
|
|
@Test func asyncLetInheritsContext() async {
|
|
let logging = TestLogging()
|
|
let logger = Logger(label: "test", factory: { logging.make(label: $0) })
|
|
|
|
func observedScope() async -> String? {
|
|
Logger.current.handler.metadata["scope"]?.description
|
|
}
|
|
|
|
await withLogger(logger) { _ in
|
|
await withLogger(mergingMetadata: ["scope": "parent"]) { _ in
|
|
async let inherited = observedScope()
|
|
let observed = await inherited
|
|
#expect(observed == "parent")
|
|
}
|
|
}
|
|
}
|
|
|
|
// MARK: - Error propagation
|
|
|
|
@Test func bindPropagatesThrow() {
|
|
struct TestError: Error {}
|
|
#expect(throws: TestError.self) {
|
|
try withLogger(Logger(label: "t")) { _ in
|
|
throw TestError()
|
|
}
|
|
}
|
|
}
|
|
|
|
@Test func modifyAsyncPropagatesThrow() async {
|
|
struct TestError: Error {}
|
|
#expect(throws: TestError.self) {
|
|
try withLogger(mergingMetadata: ["k": "v"]) { _ in
|
|
throw TestError()
|
|
}
|
|
}
|
|
}
|
|
|
|
// MARK: - Fallback behavior
|
|
|
|
@Test func fallbackUsesEmptyLabel() {
|
|
// Without an active `withLogger` scope, `Logger.current` returns the process-wide
|
|
// unbound default — a `Logger(label: "")` cached from the first time the
|
|
// task-local is touched. The empty label is the diagnostic signal that no
|
|
// `withLogger` scope was set up before the read.
|
|
withLogger(mergingMetadata: ["key": "value"]) { logger in
|
|
#expect(logger.label == "")
|
|
}
|
|
}
|
|
|
|
// MARK: - Real-world patterns
|
|
|
|
@Test func libraryReadsCurrentWithoutLoggerParameter() {
|
|
let logging = TestLogging()
|
|
let logger = Logger(label: "test", factory: { logging.make(label: $0) })
|
|
|
|
struct DatabaseClient {
|
|
func query(_ sql: String) {
|
|
Logger.current.debug("query", metadata: ["sql": "\(sql)"])
|
|
}
|
|
}
|
|
|
|
withLogger(logger) { _ in
|
|
withLogger(mergingMetadata: ["request.id": "123"]) { _ in
|
|
DatabaseClient().query("SELECT 1")
|
|
}
|
|
}
|
|
|
|
logging.history.assertExist(
|
|
level: .debug,
|
|
message: "query",
|
|
metadata: ["request.id": "123", "sql": "SELECT 1"]
|
|
)
|
|
}
|
|
|
|
// MARK: - Stress
|
|
|
|
@Test func deeplyNestedScopes() {
|
|
let logging = TestLogging()
|
|
let logger = Logger(label: "test", factory: { logging.make(label: $0) })
|
|
|
|
func nest(depth: Int) {
|
|
if depth == 0 {
|
|
Logger.current.info("bottom")
|
|
return
|
|
}
|
|
withLogger(mergingMetadata: ["d-\(depth)": "\(depth)"]) { _ in
|
|
nest(depth: depth - 1)
|
|
}
|
|
}
|
|
|
|
withLogger(logger) { _ in
|
|
nest(depth: 20)
|
|
}
|
|
|
|
let entry = logging.history.entries.first { $0.message == "bottom" }
|
|
#expect(entry?.metadata?.count == 20)
|
|
}
|
|
}
|