mirror of
https://github.com/apple/swift-log
synced 2026-11-22 03:40:39 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5073617dac | ||
|
|
6f3fbace66 | ||
|
|
41f6c72707 | ||
|
|
bffceaf778 | ||
|
|
6558438e46 | ||
|
|
7c04f86fba | ||
|
|
8c0f217f01 | ||
|
|
f4f84c9f26 | ||
|
|
1f38a59922 | ||
|
|
39e14910f6 | ||
|
|
63ee499927 | ||
|
|
c9ceb519e7 | ||
|
|
154acdf7d4 | ||
|
|
b93451412b | ||
|
|
c5f42781c4 | ||
|
|
4f1022c5cd | ||
|
|
f22537f94d | ||
|
|
185a56a488 | ||
|
|
bbd81b6725 | ||
|
|
8fb4e7147d | ||
|
|
d5dbc04d53 | ||
|
|
47ef0ec6a4 | ||
|
|
7d6d55f9ed | ||
|
|
8f634e4e68 | ||
|
|
2778fd4e5a | ||
|
|
0d9c9ae808 | ||
|
|
a92ccc626c | ||
|
|
7ee16e4656 | ||
|
|
1ccd2c5a27 | ||
|
|
477fab4170 | ||
|
|
bc386b95f2 | ||
|
|
6856e42a3f | ||
|
|
cdaa5ac879 |
No files matched your search
@@ -0,0 +1,6 @@
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
@@ -0,0 +1,12 @@
|
||||
name: Auto Release
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: read
|
||||
|
||||
jobs:
|
||||
auto-release:
|
||||
uses: apple/swift-temporal-sdk/.github/workflows/auto-release.yml@main
|
||||
@@ -14,30 +14,38 @@ jobs:
|
||||
name: Unit tests
|
||||
uses: apple/swift-nio/.github/workflows/unit_tests.yml@main
|
||||
with:
|
||||
linux_6_0_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
|
||||
linux_6_1_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
|
||||
linux_6_2_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
|
||||
linux_6_3_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
|
||||
linux_nightly_next_arguments_override: "--explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
|
||||
linux_nightly_main_arguments_override: "--explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
|
||||
windows_6_0_enabled: true
|
||||
windows_6_1_enabled: true
|
||||
windows_6_2_enabled: true
|
||||
windows_6_3_enabled: true
|
||||
windows_nightly_next_enabled: true
|
||||
windows_nightly_main_enabled: true
|
||||
windows_6_0_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
|
||||
windows_6_1_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
|
||||
windows_6_2_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
|
||||
windows_6_3_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
|
||||
windows_nightly_next_arguments_override: "--explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
|
||||
windows_nightly_main_arguments_override: "--explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
|
||||
|
||||
benchmarks:
|
||||
name: Benchmarks
|
||||
uses: apple/swift-nio/.github/workflows/benchmarks.yml@main
|
||||
macos-benchmarks:
|
||||
name: macOS benchmarks (NoTraits)
|
||||
uses: apple/swift-nio/.github/workflows/macos_benchmarks.yml@main
|
||||
with:
|
||||
benchmark_package_path: "Benchmarks"
|
||||
benchmark_package_path: "Benchmarks/NoTraits"
|
||||
macos_xcode_16_4_enabled: true
|
||||
macos_xcode_26_1_enabled: true
|
||||
|
||||
macos-benchmarks-MaxLogLevelWarningBenchmarks-trait:
|
||||
name: macOS benchmarks (MaxLogLevelWarning)
|
||||
needs: macos-benchmarks
|
||||
uses: apple/swift-nio/.github/workflows/macos_benchmarks.yml@main
|
||||
with:
|
||||
benchmark_package_path: "Benchmarks/MaxLogLevelWarning"
|
||||
macos_xcode_26_1_enabled: true
|
||||
|
||||
cxx-interop:
|
||||
name: Cxx interop
|
||||
uses: apple/swift-nio/.github/workflows/cxx_interop.yml@main
|
||||
@@ -53,7 +61,20 @@ jobs:
|
||||
with:
|
||||
runner_pool: nightly
|
||||
build_scheme: swift-log-Package
|
||||
swift_test_enabled: true
|
||||
debug_output_enabled: true
|
||||
xcode_16_3_enabled: false
|
||||
xcode_16_4_enabled: false
|
||||
xcode_26_0_enabled: false
|
||||
xcode_26_1_enabled: false
|
||||
xcode_26_2_enabled: false
|
||||
swift_6_1_enabled: true
|
||||
swift_6_2_enabled: true
|
||||
swift_6_3_enabled: true
|
||||
macos_xcode_test_enabled: false
|
||||
ios_xcode_test_enabled: false
|
||||
watchos_xcode_test_enabled: false
|
||||
tvos_xcode_test_enabled: false
|
||||
visionos_xcode_test_enabled: false
|
||||
|
||||
wasm:
|
||||
name: Wasm Swift SDK
|
||||
@@ -68,8 +89,8 @@ jobs:
|
||||
name: Release builds
|
||||
uses: apple/swift-nio/.github/workflows/release_builds.yml@main
|
||||
with:
|
||||
windows_6_0_enabled: true
|
||||
windows_6_1_enabled: true
|
||||
windows_6_2_enabled: true
|
||||
windows_6_3_enabled: true
|
||||
windows_nightly_next_enabled: true
|
||||
windows_nightly_main_enabled: true
|
||||
@@ -10,7 +10,7 @@ on:
|
||||
jobs:
|
||||
soundness:
|
||||
name: Soundness
|
||||
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@main
|
||||
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@0.0.9
|
||||
with:
|
||||
license_header_check_project_name: "Swift Logging API"
|
||||
|
||||
@@ -18,31 +18,41 @@ jobs:
|
||||
name: Unit tests
|
||||
uses: apple/swift-nio/.github/workflows/unit_tests.yml@main
|
||||
with:
|
||||
linux_6_0_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
|
||||
linux_6_1_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
|
||||
linux_6_2_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
|
||||
linux_6_3_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
|
||||
linux_nightly_next_arguments_override: "--explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
|
||||
linux_nightly_main_arguments_override: "--explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
|
||||
windows_6_0_enabled: true
|
||||
windows_6_1_enabled: true
|
||||
windows_6_2_enabled: true
|
||||
windows_6_3_enabled: true
|
||||
windows_nightly_next_enabled: true
|
||||
windows_nightly_main_enabled: true
|
||||
windows_6_0_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
|
||||
windows_6_1_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
|
||||
windows_6_2_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
|
||||
windows_6_3_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
|
||||
windows_nightly_next_arguments_override: "--explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
|
||||
windows_nightly_main_arguments_override: "--explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
|
||||
|
||||
benchmarks:
|
||||
name: Benchmarks
|
||||
uses: apple/swift-nio/.github/workflows/benchmarks.yml@main
|
||||
macos-benchmarks:
|
||||
name: macOS benchmarks (NoTraits)
|
||||
uses: apple/swift-nio/.github/workflows/macos_benchmarks.yml@main
|
||||
with:
|
||||
benchmark_package_path: "Benchmarks"
|
||||
benchmark_package_path: "Benchmarks/NoTraits"
|
||||
macos_runner_pool: general
|
||||
macos_xcode_16_4_enabled: true
|
||||
macos_xcode_26_1_enabled: true
|
||||
|
||||
macos-benchmarks-MaxLogLevelWarningBenchmarks-trait:
|
||||
name: macOS benchmarks (MaxLogLevelWarning)
|
||||
# Workaround for reusing the same benchmarks.yml workflow
|
||||
needs: macos-benchmarks
|
||||
uses: apple/swift-nio/.github/workflows/macos_benchmarks.yml@main
|
||||
with:
|
||||
benchmark_package_path: "Benchmarks/MaxLogLevelWarning"
|
||||
macos_runner_pool: general
|
||||
macos_xcode_26_1_enabled: true
|
||||
|
||||
cxx-interop:
|
||||
name: Cxx interop
|
||||
uses: apple/swift-nio/.github/workflows/cxx_interop.yml@main
|
||||
@@ -69,9 +79,9 @@ jobs:
|
||||
name: Release builds
|
||||
uses: apple/swift-nio/.github/workflows/release_builds.yml@main
|
||||
with:
|
||||
windows_6_0_enabled: true
|
||||
windows_6_1_enabled: true
|
||||
windows_6_2_enabled: true
|
||||
windows_6_3_enabled: true
|
||||
windows_nightly_next_enabled: true
|
||||
windows_nightly_main_enabled: true
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ jobs:
|
||||
timeout-minutes: 1
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Check for Semantic Version label
|
||||
|
||||
@@ -19,6 +19,8 @@ Package.swift
|
||||
**/Package.swift
|
||||
Package@-*.swift
|
||||
**/Package@-*.swift
|
||||
Package@swift-*.swift
|
||||
**/Package@swift-*.swift
|
||||
Package.resolved
|
||||
**/Package.resolved
|
||||
Makefile
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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 Benchmark
|
||||
import Foundation
|
||||
import Logging
|
||||
|
||||
let benchmarks: @Sendable () -> Void = {
|
||||
let iterations = 1_000_000
|
||||
let metrics: [BenchmarkMetric] = [.instructions, .objectAllocCount]
|
||||
|
||||
// Take a pair of levels to cover all condition ranges between the active level and logged level.
|
||||
let logLevelParameterization: [Logger.Level] = [.debug, .error]
|
||||
for logLevel in logLevelParameterization {
|
||||
for logLevelUsed in logLevelParameterization {
|
||||
var logger = Logger(label: "BenchmarkRunner_\(logLevel)_\(logLevelUsed)")
|
||||
|
||||
// Use a NoOpLogHandler to avoid polluting the logs
|
||||
logger.handler = NoOpLogHandler(label: "NoOpLogHandler")
|
||||
logger.logLevel = logLevel
|
||||
|
||||
Benchmark(
|
||||
"\(logLevelUsed)_log_with_\(logLevel)_log_level",
|
||||
configuration: .init(
|
||||
metrics: metrics,
|
||||
maxIterations: iterations,
|
||||
thresholds: [
|
||||
.instructions: BenchmarkThresholds(
|
||||
relative: [
|
||||
.p90: 1.0 // we only record p90
|
||||
]
|
||||
),
|
||||
.objectAllocCount: BenchmarkThresholds(
|
||||
absolute: [
|
||||
.p90: 0 // we only record p90
|
||||
]
|
||||
),
|
||||
]
|
||||
)
|
||||
) { benchmark in
|
||||
// This is what we actually benchmark
|
||||
logger.log(level: logLevelUsed, "hello, benchmarking world")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
.DS_Store
|
||||
/.build
|
||||
/Packages
|
||||
xcuserdata/
|
||||
DerivedData/
|
||||
.swiftpm/configuration/registries.json
|
||||
.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
|
||||
.netrc
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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 Benchmark
|
||||
import BenchmarksFactory
|
||||
import Foundation
|
||||
import Logging
|
||||
|
||||
public let benchmarks: @Sendable () -> Void = {
|
||||
makeBenchmark(loggerLevel: .notice, logLevel: .notice) { logger in
|
||||
logger.notice("hello, benchmarking world")
|
||||
}
|
||||
makeBenchmark(loggerLevel: .notice, logLevel: .notice, "_generic") { logger in
|
||||
logger.log(level: .notice, "hello, benchmarking world")
|
||||
}
|
||||
makeBenchmark(loggerLevel: .warning, logLevel: .warning) { logger in
|
||||
logger.warning("hello, benchmarking world")
|
||||
}
|
||||
makeBenchmark(loggerLevel: .warning, logLevel: .warning, "_generic") { logger in
|
||||
logger.log(level: .warning, "hello, benchmarking world")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
// swift-tools-version: 6.1
|
||||
// The swift-tools-version declares the minimum version of Swift required to build this package.
|
||||
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "MaxLogLevelWarning",
|
||||
platforms: [
|
||||
.macOS(.v13)
|
||||
],
|
||||
products: [
|
||||
.executable(name: "MaxLogLevelWarning", targets: ["MaxLogLevelWarning"])
|
||||
],
|
||||
dependencies: [
|
||||
// swift-log
|
||||
.package(
|
||||
path: "../../",
|
||||
traits: ["MaxLogLevelWarning"]
|
||||
),
|
||||
// Parent Benchmarks
|
||||
.package(name: "Benchmarks", path: "../"),
|
||||
.package(url: "https://github.com/ordo-one/package-benchmark.git", from: "1.29.6"),
|
||||
],
|
||||
targets: [
|
||||
.executableTarget(
|
||||
name: "MaxLogLevelWarning",
|
||||
dependencies: [
|
||||
.product(name: "BenchmarksFactory", package: "Benchmarks"),
|
||||
.product(name: "Benchmark", package: "package-benchmark"),
|
||||
.product(name: "Logging", package: "swift-log"),
|
||||
],
|
||||
path: "Benchmarks/MaxLogLevelWarningBenchmarks",
|
||||
plugins: [
|
||||
.plugin(name: "BenchmarkPlugin", package: "package-benchmark")
|
||||
]
|
||||
)
|
||||
]
|
||||
)
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
{
|
||||
"instructions" : 1045,
|
||||
"instructions" : 619,
|
||||
"objectAllocCount" : 0
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
{
|
||||
"instructions" : 1126,
|
||||
"instructions" : 619,
|
||||
"objectAllocCount" : 0
|
||||
}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"instructions" : 1651,
|
||||
"objectAllocCount" : 0
|
||||
}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"instructions" : 1651,
|
||||
"objectAllocCount" : 0
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
.DS_Store
|
||||
/.build
|
||||
/Packages
|
||||
xcuserdata/
|
||||
DerivedData/
|
||||
.swiftpm/configuration/registries.json
|
||||
.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
|
||||
.netrc
|
||||
@@ -0,0 +1,27 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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 Benchmark
|
||||
import BenchmarksFactory
|
||||
import Foundation
|
||||
import Logging
|
||||
|
||||
public let benchmarks: @Sendable () -> Void = {
|
||||
makeBenchmark(loggerLevel: .error, logLevel: .error, "_generic") { logger in
|
||||
logger.log(level: .error, "hello, benchmarking world")
|
||||
}
|
||||
makeBenchmark(loggerLevel: .error, logLevel: .debug, "_generic") { logger in
|
||||
logger.log(level: .debug, "hello, benchmarking world")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
// swift-tools-version:6.1
|
||||
// The swift-tools-version declares the minimum version of Swift required to build this package.
|
||||
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "NoTraits",
|
||||
platforms: [
|
||||
.macOS(.v13)
|
||||
],
|
||||
products: [
|
||||
.executable(name: "NoTraits", targets: ["NoTraits"])
|
||||
],
|
||||
dependencies: [
|
||||
// swift-log
|
||||
.package(
|
||||
path: "../../"
|
||||
),
|
||||
// Parent Benchmarks
|
||||
.package(name: "Benchmarks", path: "../"),
|
||||
.package(url: "https://github.com/ordo-one/package-benchmark.git", from: "1.29.6"),
|
||||
],
|
||||
targets: [
|
||||
.executableTarget(
|
||||
name: "NoTraits",
|
||||
dependencies: [
|
||||
.product(name: "BenchmarksFactory", package: "Benchmarks"),
|
||||
.product(name: "Benchmark", package: "package-benchmark"),
|
||||
.product(name: "Logging", package: "swift-log"),
|
||||
],
|
||||
path: "Benchmarks/NoTraitsBenchmarks",
|
||||
plugins: [
|
||||
.plugin(name: "BenchmarkPlugin", package: "package-benchmark")
|
||||
]
|
||||
)
|
||||
]
|
||||
)
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"instructions" : 984,
|
||||
"objectAllocCount" : 0
|
||||
}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"instructions" : 1368,
|
||||
"objectAllocCount" : 0
|
||||
}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"instructions" : 893,
|
||||
"objectAllocCount" : 0
|
||||
}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"instructions" : 1649,
|
||||
"objectAllocCount" : 0
|
||||
}
|
||||
+15
-18
@@ -1,30 +1,27 @@
|
||||
// swift-tools-version: 6.0
|
||||
// swift-tools-version:6.1
|
||||
// The swift-tools-version declares the minimum version of Swift required to build this package.
|
||||
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "Benchmarks",
|
||||
name: "BenchmarksFactory",
|
||||
platforms: [
|
||||
.macOS(.v13)
|
||||
],
|
||||
products: [
|
||||
.library(name: "BenchmarksFactory", targets: ["BenchmarksFactory"])
|
||||
],
|
||||
dependencies: [
|
||||
.package(path: "../"),
|
||||
.package(url: "https://github.com/ordo-one/package-benchmark.git", from: "1.29.6"),
|
||||
.package(path: "../"), // swift-log
|
||||
],
|
||||
targets: [
|
||||
.target(
|
||||
name: "BenchmarksFactory",
|
||||
dependencies: [
|
||||
.product(name: "Benchmark", package: "package-benchmark"),
|
||||
.product(name: "Logging", package: "swift-log"),
|
||||
]
|
||||
)
|
||||
]
|
||||
)
|
||||
|
||||
// Benchmark of SwiftLogBenchmarks
|
||||
package.targets += [
|
||||
.executableTarget(
|
||||
name: "SwiftLogBenchmarks",
|
||||
dependencies: [
|
||||
.product(name: "Benchmark", package: "package-benchmark"),
|
||||
.product(name: "Logging", package: "swift-log"),
|
||||
],
|
||||
path: "Benchmarks/SwiftLogBenchmarks",
|
||||
plugins: [
|
||||
.plugin(name: "BenchmarkPlugin", package: "package-benchmark")
|
||||
]
|
||||
)
|
||||
]
|
||||
@@ -0,0 +1,55 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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 Benchmark
|
||||
import Foundation
|
||||
import Logging
|
||||
|
||||
public func makeBenchmark(
|
||||
loggerLevel: Logger.Level,
|
||||
logLevel: Logger.Level,
|
||||
_ suffix: String = "",
|
||||
_ body: @escaping (Logger) -> Void
|
||||
) {
|
||||
let iterations = 1_000_000
|
||||
let metrics: [BenchmarkMetric] = [.instructions, .objectAllocCount]
|
||||
|
||||
var logger = Logger(label: "BenchmarkRunner_\(loggerLevel)_\(logLevel)")
|
||||
|
||||
// Use a NoOpLogHandler to avoid polluting the logs
|
||||
logger.handler = NoOpLogHandler(label: "NoOpLogHandler")
|
||||
logger.logLevel = loggerLevel
|
||||
|
||||
Benchmark(
|
||||
"\(logLevel)_log_with_\(loggerLevel)_log_level\(suffix)",
|
||||
configuration: .init(
|
||||
metrics: metrics,
|
||||
maxIterations: iterations,
|
||||
thresholds: [
|
||||
.instructions: BenchmarkThresholds(
|
||||
relative: [
|
||||
.p90: 1.0 // we only record p90
|
||||
]
|
||||
),
|
||||
.objectAllocCount: BenchmarkThresholds(
|
||||
absolute: [
|
||||
.p90: 0 // we only record p90
|
||||
]
|
||||
),
|
||||
]
|
||||
)
|
||||
) { _ in
|
||||
body(logger)
|
||||
}
|
||||
}
|
||||
+6
@@ -28,6 +28,12 @@ struct NoOpLogHandler: LogHandler {
|
||||
self.metadataProvider = LoggingSystem.metadataProvider
|
||||
}
|
||||
|
||||
func log(
|
||||
event: LogEvent
|
||||
) {
|
||||
// Do nothing
|
||||
}
|
||||
|
||||
func log(
|
||||
level: Logger.Level,
|
||||
message: Logger.Message,
|
||||
-4
@@ -1,4 +0,0 @@
|
||||
{
|
||||
"instructions" : 3279,
|
||||
"objectAllocCount" : 1
|
||||
}
|
||||
-4
@@ -1,4 +0,0 @@
|
||||
{
|
||||
"instructions" : 3279,
|
||||
"objectAllocCount" : 1
|
||||
}
|
||||
-4
@@ -1,4 +0,0 @@
|
||||
{
|
||||
"instructions" : 3279,
|
||||
"objectAllocCount" : 1
|
||||
}
|
||||
-4
@@ -1,4 +0,0 @@
|
||||
{
|
||||
"instructions" : 3197,
|
||||
"objectAllocCount" : 1
|
||||
}
|
||||
-4
@@ -1,4 +0,0 @@
|
||||
{
|
||||
"instructions" : 3197,
|
||||
"objectAllocCount" : 1
|
||||
}
|
||||
-4
@@ -1,4 +0,0 @@
|
||||
{
|
||||
"instructions" : 3197,
|
||||
"objectAllocCount" : 1
|
||||
}
|
||||
@@ -118,3 +118,8 @@ For more information please refer to `swift package benchmark --help` or the [do
|
||||
## How to contribute your work
|
||||
|
||||
Please open a pull request at https://github.com/apple/swift-log. Make sure the CI passes, and then wait for code review.
|
||||
|
||||
|
||||
## Automated release process
|
||||
|
||||
This repository uses automated releases based on semantic versioning labels. See the [Auto Release Workflow documentation](https://github.com/apple/swift-temporal-sdk/blob/main/.github/workflows/README.md) for details.
|
||||
+40
-19
@@ -1,4 +1,4 @@
|
||||
// swift-tools-version:6.0
|
||||
// swift-tools-version:6.2
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Logging API open source project
|
||||
@@ -21,6 +21,24 @@ let package = Package(
|
||||
.library(name: "Logging", targets: ["Logging"]),
|
||||
.library(name: "InMemoryLogging", targets: ["InMemoryLogging"]),
|
||||
],
|
||||
traits: [
|
||||
.trait(name: "MaxLogLevelDebug", description: "Debug and above available (compiles out trace)"),
|
||||
.trait(name: "MaxLogLevelInfo", description: "Info and above available (compiles out trace, debug)"),
|
||||
.trait(name: "MaxLogLevelNotice", description: "Notice and above available (compiles out trace, debug, info)"),
|
||||
.trait(
|
||||
name: "MaxLogLevelWarning",
|
||||
description: "Warning and above available (compiles out trace, debug, info, notice)"
|
||||
),
|
||||
.trait(
|
||||
name: "MaxLogLevelError",
|
||||
description: "Error and above available (compiles out trace, debug, info, notice, warning)"
|
||||
),
|
||||
.trait(name: "MaxLogLevelCritical", description: "Only critical available (compiles out all except critical)"),
|
||||
.trait(name: "MaxLogLevelNone", description: "All logging compiled out (no log levels available)"),
|
||||
|
||||
// By default, no traits are enabled (all log levels available)
|
||||
.default(enabledTraits: []),
|
||||
],
|
||||
targets: [
|
||||
.target(
|
||||
name: "Logging",
|
||||
@@ -41,24 +59,27 @@ let package = Package(
|
||||
]
|
||||
)
|
||||
|
||||
for target in package.targets {
|
||||
for target in package.targets
|
||||
where [.executable, .test, .regular].contains(
|
||||
target.type
|
||||
) {
|
||||
var settings = target.swiftSettings ?? []
|
||||
settings.append(.enableExperimentalFeature("StrictConcurrency=complete"))
|
||||
|
||||
// https://github.com/apple/swift-evolution/blob/main/proposals/0335-existential-any.md
|
||||
// Require `any` for existential types.
|
||||
settings.append(.enableUpcomingFeature("ExistentialAny"))
|
||||
|
||||
// https://github.com/swiftlang/swift-evolution/blob/main/proposals/0444-member-import-visibility.md
|
||||
settings.append(.enableUpcomingFeature("MemberImportVisibility"))
|
||||
|
||||
// https://github.com/swiftlang/swift-evolution/blob/main/proposals/0409-access-level-on-imports.md
|
||||
settings.append(.enableUpcomingFeature("InternalImportsByDefault"))
|
||||
|
||||
// https://docs.swift.org/compiler/documentation/diagnostics/nonisolated-nonsending-by-default/
|
||||
settings.append(.enableUpcomingFeature("NonisolatedNonsendingByDefault"))
|
||||
|
||||
// Ensure all public types are explicitly annotated as Sendable or not Sendable.
|
||||
settings.append(.unsafeFlags(["-Xfrontend", "-require-explicit-sendable"]))
|
||||
|
||||
target.swiftSettings = settings
|
||||
}
|
||||
|
||||
// --- STANDARD CROSS-REPO SETTINGS DO NOT EDIT --- //
|
||||
for target in package.targets {
|
||||
switch target.type {
|
||||
case .regular, .test, .executable:
|
||||
var settings = target.swiftSettings ?? []
|
||||
// https://github.com/swiftlang/swift-evolution/blob/main/proposals/0444-member-import-visibility.md
|
||||
settings.append(.enableUpcomingFeature("MemberImportVisibility"))
|
||||
target.swiftSettings = settings
|
||||
case .macro, .plugin, .system, .binary:
|
||||
() // not applicable
|
||||
@unknown default:
|
||||
() // we don't know what to do here, do nothing
|
||||
}
|
||||
}
|
||||
// --- END: STANDARD CROSS-REPO SETTINGS DO NOT EDIT --- //
|
||||
@@ -0,0 +1,79 @@
|
||||
// swift-tools-version:6.1
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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"]),
|
||||
.library(name: "InMemoryLogging", targets: ["InMemoryLogging"]),
|
||||
],
|
||||
traits: [
|
||||
.trait(name: "MaxLogLevelDebug", description: "Debug and above available (compiles out trace)"),
|
||||
.trait(name: "MaxLogLevelInfo", description: "Info and above available (compiles out trace, debug)"),
|
||||
.trait(name: "MaxLogLevelNotice", description: "Notice and above available (compiles out trace, debug, info)"),
|
||||
.trait(
|
||||
name: "MaxLogLevelWarning",
|
||||
description: "Warning and above available (compiles out trace, debug, info, notice)"
|
||||
),
|
||||
.trait(
|
||||
name: "MaxLogLevelError",
|
||||
description: "Error and above available (compiles out trace, debug, info, notice, warning)"
|
||||
),
|
||||
.trait(name: "MaxLogLevelCritical", description: "Only critical available (compiles out all except critical)"),
|
||||
.trait(name: "MaxLogLevelNone", description: "All logging compiled out (no log levels available)"),
|
||||
|
||||
// By default, no traits are enabled (all log levels available)
|
||||
.default(enabledTraits: []),
|
||||
],
|
||||
targets: [
|
||||
.target(
|
||||
name: "Logging",
|
||||
dependencies: []
|
||||
),
|
||||
.target(
|
||||
name: "InMemoryLogging",
|
||||
dependencies: ["Logging"]
|
||||
),
|
||||
.testTarget(
|
||||
name: "LoggingTests",
|
||||
dependencies: ["Logging"]
|
||||
),
|
||||
.testTarget(
|
||||
name: "InMemoryLoggingTests",
|
||||
dependencies: ["InMemoryLogging", "Logging"]
|
||||
),
|
||||
]
|
||||
)
|
||||
|
||||
for target in package.targets
|
||||
where [.executable, .test, .regular].contains(
|
||||
target.type
|
||||
) {
|
||||
var settings = target.swiftSettings ?? []
|
||||
|
||||
// https://github.com/apple/swift-evolution/blob/main/proposals/0335-existential-any.md
|
||||
// Require `any` for existential types.
|
||||
settings.append(.enableUpcomingFeature("ExistentialAny"))
|
||||
|
||||
// https://github.com/swiftlang/swift-evolution/blob/main/proposals/0444-member-import-visibility.md
|
||||
settings.append(.enableUpcomingFeature("MemberImportVisibility"))
|
||||
|
||||
// https://github.com/swiftlang/swift-evolution/blob/main/proposals/0409-access-level-on-imports.md
|
||||
settings.append(.enableUpcomingFeature("InternalImportsByDefault"))
|
||||
|
||||
target.swiftSettings = settings
|
||||
}
|
||||
-43
@@ -1,43 +0,0 @@
|
||||
# Security
|
||||
|
||||
This document specifies the security process for the SwiftLog project.
|
||||
|
||||
## Disclosures
|
||||
|
||||
### Private Disclosure Process
|
||||
|
||||
The SwiftLog maintainers ask that known and suspected vulnerabilities be
|
||||
privately and responsibly disclosed by emailing
|
||||
[sswg-security-reports@forums.swift.org](mailto:sswg-security-reports@forums.swift.org)
|
||||
with the all the required detail.
|
||||
**Do not file a public issue.**
|
||||
|
||||
#### When to report a vulnerability
|
||||
|
||||
* You think you have discovered a potential security vulnerability in SwiftLog.
|
||||
* You are unsure how a vulnerability affects SwiftLog.
|
||||
|
||||
#### What happens next?
|
||||
|
||||
* A member of the team will acknowledge receipt of the report within 3
|
||||
working days (United States). This may include a request for additional
|
||||
information about reproducing the vulnerability.
|
||||
* We will privately inform the Swift Server Work Group ([SSWG][sswg]) of the
|
||||
vulnerability within 10 days of the report as per their [security
|
||||
guidelines][sswg-security].
|
||||
* Once we have identified a fix we may ask you to validate it. We aim to do this
|
||||
within 30 days. In some cases this may not be possible, for example when the
|
||||
vulnerability exists at the protocol level and the industry must coordinate on
|
||||
the disclosure process.
|
||||
* If a CVE number is required, one will be requested from [MITRE][mitre]
|
||||
providing you with full credit for the discovery.
|
||||
* We will decide on a planned release date and let you know when it is.
|
||||
* Prior to release, we will inform major dependents that a security-related
|
||||
patch is impending.
|
||||
* Once the fix has been released we will publish a security advisory on GitHub
|
||||
and in the Server → Security Updates category on the [Swift forums][swift-forums-sec].
|
||||
|
||||
[sswg]: https://github.com/swift-server/sswg
|
||||
[sswg-security]: https://www.swift.org/sswg/security/
|
||||
[swift-forums-sec]: https://forums.swift.org/c/server/security-updates/
|
||||
[mitre]: https://cveform.mitre.org/
|
||||
@@ -12,7 +12,7 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Logging
|
||||
public import Logging
|
||||
|
||||
/// A custom log handler which just collects logs into memory.
|
||||
/// You can then retrieve an array of those log entries.
|
||||
@@ -46,6 +46,8 @@ public struct InMemoryLogHandler: LogHandler {
|
||||
public var level: Logger.Level
|
||||
/// The message which was logged.
|
||||
public var message: Logger.Message
|
||||
/// The error which was logged.
|
||||
public var error: (any Error)?
|
||||
/// The metadata which was logged.
|
||||
public var metadata: Logger.Metadata
|
||||
|
||||
@@ -54,18 +56,49 @@ public struct InMemoryLogHandler: LogHandler {
|
||||
self.message = message
|
||||
self.metadata = metadata
|
||||
}
|
||||
|
||||
public init(level: Logger.Level, message: Logger.Message, error: (any Error)?, metadata: Logger.Metadata) {
|
||||
self.level = level
|
||||
self.message = message
|
||||
self.error = error
|
||||
self.metadata = metadata
|
||||
}
|
||||
|
||||
public static func == (lhs: InMemoryLogHandler.Entry, rhs: InMemoryLogHandler.Entry) -> Bool {
|
||||
lhs.level == rhs.level
|
||||
&& lhs.message == rhs.message
|
||||
&& errorsEqual(lhs.error, rhs.error)
|
||||
&& lhs.metadata == rhs.metadata
|
||||
}
|
||||
|
||||
private static func errorsEqual(_ lhs: (any Error)?, _ rhs: (any Error)?) -> Bool {
|
||||
switch (lhs, rhs) {
|
||||
case (nil, nil):
|
||||
return true
|
||||
case let (l?, r?):
|
||||
return "\(l)" == "\(r)" && String(reflecting: type(of: l)) == String(reflecting: type(of: r))
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private final class LogStore: @unchecked Sendable {
|
||||
private var _entries: [Entry] = []
|
||||
private let lock = Lock()
|
||||
|
||||
fileprivate func append(level: Logger.Level, message: Logger.Message, metadata: Logger.Metadata) {
|
||||
fileprivate func append(
|
||||
level: Logger.Level,
|
||||
message: Logger.Message,
|
||||
error: (any Error)?,
|
||||
metadata: Logger.Metadata
|
||||
) {
|
||||
self.lock.withLockVoid {
|
||||
self._entries.append(
|
||||
Entry(
|
||||
level: level,
|
||||
message: message,
|
||||
error: error,
|
||||
metadata: metadata
|
||||
)
|
||||
)
|
||||
@@ -92,6 +125,18 @@ public struct InMemoryLogHandler: LogHandler {
|
||||
self.init(logStore: .init())
|
||||
}
|
||||
|
||||
public func log(event: LogEvent) {
|
||||
// Start with the metadata provider..
|
||||
var mergedMetadata: Logger.Metadata = self.metadataProvider?.get() ?? [:]
|
||||
// ..merge in self.metadata, overwriting existing keys
|
||||
mergedMetadata = mergedMetadata.merging(self.metadata) { $1 }
|
||||
// ..merge in metadata from this log call, overwriting existing keys
|
||||
mergedMetadata = mergedMetadata.merging(event.metadata ?? [:]) { $1 }
|
||||
|
||||
self.logStore.append(level: event.level, message: event.message, error: event.error, metadata: mergedMetadata)
|
||||
}
|
||||
|
||||
@available(*, deprecated, renamed: "log(event:)")
|
||||
public func log(
|
||||
level: Logger.Level,
|
||||
message: Logger.Message,
|
||||
@@ -101,14 +146,17 @@ public struct InMemoryLogHandler: LogHandler {
|
||||
function: String,
|
||||
line: UInt
|
||||
) {
|
||||
// Start with the metadata provider..
|
||||
var mergedMetadata: Logger.Metadata = self.metadataProvider?.get() ?? [:]
|
||||
// ..merge in self.metadata, overwriting existing keys
|
||||
mergedMetadata = mergedMetadata.merging(self.metadata) { $1 }
|
||||
// ..merge in metadata from this log call, overwriting existing keys
|
||||
mergedMetadata = mergedMetadata.merging(metadata ?? [:]) { $1 }
|
||||
|
||||
self.logStore.append(level: level, message: message, metadata: mergedMetadata)
|
||||
self.log(
|
||||
event: LogEvent(
|
||||
level: level,
|
||||
message: message,
|
||||
metadata: metadata,
|
||||
source: source,
|
||||
file: file,
|
||||
function: function,
|
||||
line: line
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
public subscript(metadataKey key: String) -> Logger.Metadata.Value? {
|
||||
|
||||
@@ -9,7 +9,7 @@ creating well-behaved libraries that don't overwhelm logging systems or misuse
|
||||
severity levels. This practice provides clear guidance on when to use each
|
||||
level.
|
||||
|
||||
### Motivation
|
||||
### Motivation
|
||||
|
||||
Libraries must be well-behaved across various use cases and cannot assume
|
||||
specific logging backend configurations. Using inappropriate log levels can
|
||||
@@ -51,7 +51,7 @@ Each level serves different purposes:
|
||||
- **Performance**: May impact performance; assume it won't be used in production.
|
||||
- **Content**: Internal state, detailed operation flows, diagnostic information.
|
||||
|
||||
##### Debug Level
|
||||
##### Debug Level
|
||||
- **Usage**: May be enabled in some production deployments.
|
||||
- **Performance**: Should not significantly undermine production performance.
|
||||
- **Content**: High-level operation overview, connection events, major decisions.
|
||||
@@ -128,7 +128,7 @@ logger.info("Request failed")
|
||||
```swift
|
||||
// ❌ Bad: Normal operations at info level flood production logs
|
||||
logger.info("HTTP request received")
|
||||
logger.info("Database query executed")
|
||||
logger.info("Database query executed")
|
||||
logger.info("Response sent")
|
||||
|
||||
// ✅ Good: Use appropriate levels instead
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
# Disable log levels during compilation
|
||||
|
||||
SwiftLog provides compile-time traits to eliminate less severe log levels from
|
||||
your binary reducing the runtime overhead.
|
||||
|
||||
## Motivation
|
||||
|
||||
When deploying applications to production, you often know in advance which log
|
||||
levels will never be needed. For example, a production service might only need
|
||||
warning and above, while trace and debug levels are only useful during
|
||||
development. By using traits, you can completely remove these unnecessary log
|
||||
levels at compile time, achieving zero runtime overhead.
|
||||
|
||||
## Available traits
|
||||
|
||||
SwiftLog defines seven maximum log level traits, ordered from most permissive
|
||||
to most restrictive:
|
||||
|
||||
- `MaxLogLevelDebug`: Debug and above available (compiles out trace)
|
||||
- `MaxLogLevelInfo`: Info and above available (compiles out trace, debug)
|
||||
- `MaxLogLevelNotice`: Notice and above available (compiles out trace, debug,
|
||||
info)
|
||||
- `MaxLogLevelWarning`: Warning and above available (compiles out trace, debug,
|
||||
info, notice)
|
||||
- `MaxLogLevelError`: Error and above available (compiles out trace, debug,
|
||||
info, notice, warning)
|
||||
- `MaxLogLevelCritical`: Only critical available (compiles out all except
|
||||
critical)
|
||||
- `MaxLogLevelNone`: All logging compiled out (no log levels available)
|
||||
|
||||
By default (when no traits are specified), all log levels are available.
|
||||
|
||||
When you specify a maximum log level trait, all less severe levels are
|
||||
completely removed from your binary at compile time. This applies to both
|
||||
level-specific methods (e.g., `logger.debug()`) and calls to the generic
|
||||
`logger.log(level:)` method. Traits are additive. If multiple max level traits
|
||||
are specified, the most restrictive one takes effect.
|
||||
|
||||
> Note: Traits should only be set by the applications and not libraries as
|
||||
> any traits defined in a transitive dependency will affect the whole resolution tree.
|
||||
|
||||
## Example
|
||||
|
||||
To enable a trait, specify it when declaring your package dependency:
|
||||
|
||||
```swift
|
||||
// In your Package.swift:
|
||||
dependencies: [
|
||||
.package(
|
||||
url: "https://github.com/apple/swift-log.git",
|
||||
from: "1.0.0",
|
||||
traits: ["MaxLogLevelWarning"]
|
||||
)
|
||||
]
|
||||
```
|
||||
|
||||
With `MaxLogLevelWarning` enabled, all trace, debug, info, and notice log
|
||||
statements are compiled out:
|
||||
|
||||
```swift
|
||||
// These become no-ops (compiled out completely):
|
||||
logger.trace("This will not be in the binary")
|
||||
logger.debug("This will not be in the binary")
|
||||
logger.info("This will not be in the binary")
|
||||
logger.notice("This will not be in the binary")
|
||||
logger.log(level: .debug, "This will not log anything")
|
||||
|
||||
// These work normally:
|
||||
logger.warning("This still works")
|
||||
logger.error("This still works")
|
||||
logger.critical("This still works")
|
||||
logger.log(level: .error, "This still works")
|
||||
```
|
||||
@@ -1,4 +1,4 @@
|
||||
# Metadata Providers
|
||||
# SLG-0001: Metadata Providers
|
||||
|
||||
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.
|
||||
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
# SLG-0002: Compile-time log level elimination using traits
|
||||
|
||||
Enable compile-time elimination of log levels to achieve zero runtime overhead for logs that will never be needed in production.
|
||||
|
||||
## Overview
|
||||
|
||||
- Proposal: SLG-0002
|
||||
- Author(s): [Vladimir Kukushkin](https://github.com/kukushechkin)
|
||||
- Status: **Approved**
|
||||
- Issue: [apple/swift-log#378](https://github.com/apple/swift-log/issues/378)
|
||||
- Implementation:
|
||||
- [apple/swift-log#389](https://github.com/apple/swift-log/pull/389)
|
||||
- Related links:
|
||||
- [Lightweight proposals process description](https://github.com/apple/swift-log/blob/main/Sources/Logging/Docs.docc/Proposals/Proposals.md)
|
||||
|
||||
### Introduction
|
||||
|
||||
Add Swift package traits to allow applications to compile out less severe log levels, completely eliminating their runtime overhead from the final binary.
|
||||
|
||||
### Motivation
|
||||
|
||||
In production deployments, applications often know in advance which log levels will never be needed. For example, a production service typically only needs warning and above, while trace and debug levels are exclusively useful during development. Currently, even with the log level set to `.warning` at runtime, the code for trace and debug statements still exists in the binary and incurs overhead.
|
||||
|
||||
For performance-critical applications or resource-constrained environments, this overhead is unacceptable. Applications need a way to completely remove unnecessary log levels at compile time, achieving zero runtime cost.
|
||||
|
||||
Before this proposal, the only workarounds were:
|
||||
- Manually wrapping log statements in `#if DEBUG` checks (error-prone and verbose)
|
||||
- Accepting the runtime overhead (unacceptable for many use cases)
|
||||
|
||||
### Proposed solution
|
||||
|
||||
This proposal introduces seven package traits that correspond to maximum log level thresholds. Applications specify a trait when declaring their dependency on SwiftLog, and all less severe log levels are completely compiled out.
|
||||
|
||||
In your `Package.swift`:
|
||||
|
||||
```swift
|
||||
dependencies: [
|
||||
.package(
|
||||
url: "https://github.com/apple/swift-log.git",
|
||||
from: "1.0.0",
|
||||
traits: ["MaxLogLevelWarning"]
|
||||
)
|
||||
]
|
||||
```
|
||||
|
||||
With `MaxLogLevelWarning` enabled:
|
||||
|
||||
```swift
|
||||
// These become no-ops (compiled out completely):
|
||||
logger.trace("This will not be in the binary")
|
||||
logger.debug("This will not be in the binary")
|
||||
logger.info("This will not be in the binary")
|
||||
logger.notice("This will not be in the binary")
|
||||
logger.log(level: .debug, "This will not log anything")
|
||||
|
||||
// These work normally:
|
||||
logger.warning("This still works")
|
||||
logger.error("This still works")
|
||||
logger.critical("This still works")
|
||||
logger.log(level: .error, "This still works")
|
||||
```
|
||||
|
||||
### Detailed design
|
||||
|
||||
The seven available traits, ordered from most permissive to most restrictive, are:
|
||||
|
||||
```swift
|
||||
traits: [
|
||||
.trait(name: "MaxLogLevelDebug", description: "Debug and above available (compiles out trace)"),
|
||||
.trait(name: "MaxLogLevelInfo", description: "Info and above available (compiles out trace, debug)"),
|
||||
.trait(name: "MaxLogLevelNotice", description: "Notice and above available (compiles out trace, debug, info)"),
|
||||
.trait(
|
||||
name: "MaxLogLevelWarning",
|
||||
description: "Warning and above available (compiles out trace, debug, info, notice)"
|
||||
),
|
||||
.trait(
|
||||
name: "MaxLogLevelError",
|
||||
description: "Error and above available (compiles out trace, debug, info, notice, warning)"
|
||||
),
|
||||
.trait(name: "MaxLogLevelCritical", description: "Only critical available (compiles out all except critical)"),
|
||||
.trait(name: "MaxLogLevelNone", description: "All logging compiled out (no log levels available)"),
|
||||
|
||||
.default(enabledTraits: []),
|
||||
]
|
||||
```
|
||||
|
||||
By default (when no traits are specified), all log levels remain available.
|
||||
|
||||
Traits are additive: if multiple max level traits are specified in the dependency graph, the most restrictive one takes effect. This ensures that if any dependency requests stricter elimination, the entire build respects it.
|
||||
|
||||
> Important: Traits should only be set by applications, not libraries, as any trait defined in a transitive dependency will affect the entire dependency resolution tree.
|
||||
|
||||
For the generic `log(level:)` method, the implementation switches behavior based on whether any trait is enabled:
|
||||
|
||||
```swift
|
||||
public 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
|
||||
) {
|
||||
#if MaxLogLevelDebug || MaxLogLevelInfo || MaxLogLevelNotice || MaxLogLevelWarning || MaxLogLevelError || MaxLogLevelCritical || MaxLogLevelNone
|
||||
// When traits are enabled, dispatch to level-specific methods
|
||||
// to leverage their compile-time elimination
|
||||
switch level {
|
||||
case .trace:
|
||||
self.trace(message(), metadata: metadata(), source: source(), file: file, function: function, line: line)
|
||||
case .debug:
|
||||
self.debug(message(), metadata: metadata(), source: source(), file: file, function: function, line: line)
|
||||
// ... (all levels)
|
||||
}
|
||||
#else
|
||||
// When no traits are enabled, avoid the switch overhead
|
||||
self._log(
|
||||
level: level,
|
||||
message(),
|
||||
metadata: metadata(),
|
||||
source: source(),
|
||||
file: file,
|
||||
function: function,
|
||||
line: line
|
||||
)
|
||||
#endif
|
||||
}
|
||||
```
|
||||
|
||||
This approach adds a minimal switch statement overhead when traits are enabled, but allows the level-specific methods' compile-time elimination to work even when called through `log(level:)`. When no traits are enabled, the original zero-overhead path is preserved. Level-specific methods has no additional overhead.
|
||||
|
||||
### API stability
|
||||
|
||||
**For existing `Logger` users:**
|
||||
- When no traits are enabled (the default), behavior is identical to before
|
||||
- Users can opt in to traits at the application level without modifying any source code
|
||||
|
||||
**For existing `LogHandler` implementations:**
|
||||
- No changes are required to any `LogHandler` implementation
|
||||
|
||||
### Future directions
|
||||
|
||||
No future directions identified.
|
||||
|
||||
### Alternatives considered
|
||||
|
||||
#### Per-log-level traits
|
||||
|
||||
An alternative approach would be to define one trait per log level that could be individually disabled:
|
||||
|
||||
```swift
|
||||
traits: [
|
||||
.trait(name: "DisableTraceLogs"),
|
||||
.trait(name: "DisableDebugLogs"),
|
||||
.trait(name: "DisableInfoLogs"),
|
||||
.trait(name: "DisableNoticeLogs"),
|
||||
.trait(name: "DisableWarningLogs"),
|
||||
.trait(name: "DisableErrorLogs"),
|
||||
.trait(name: "DisableCriticalLogs"),
|
||||
]
|
||||
```
|
||||
|
||||
Users would specify multiple traits to eliminate multiple levels:
|
||||
|
||||
```swift
|
||||
.package(
|
||||
url: "https://github.com/apple/swift-log.git",
|
||||
from: "1.0.0",
|
||||
traits: ["DisableTraceLogs", "DisableDebugLogs", "DisableInfoLogs", "DisableNoticeLogs"]
|
||||
)
|
||||
```
|
||||
|
||||
This approach was rejected in favor of a `MaxLogLevel` semantics to make it less verbose to use the functionality and to be aligned with the similar functionality in logging packages in other languages users might already be familiar with.
|
||||
@@ -0,0 +1,416 @@
|
||||
# SLG-0003: Support for Attaching Errors to Log Entries
|
||||
|
||||
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: **Approved**
|
||||
- Issue: [apple/swift-log#291](https://github.com/apple/swift-log/issues/291)
|
||||
- Implementation:
|
||||
- [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 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
|
||||
|
||||
SwiftLog advocates for the use of _structured logging_, which in its implementation is achieved by using the `metadata` attribute in the log methods. This is important since it allows for automated tools to parse the logs and extract metadata values for filtering and/or visualization. When logging in a catch-block, it often makes sense to attach some information from the thrown `Error` in the log post, so as to capture the root cause.
|
||||
|
||||
```swift
|
||||
do {
|
||||
try someThrowingFunc()
|
||||
} catch {
|
||||
logger.warning("Something went wrong") // Want to somehow attach information about the error
|
||||
}
|
||||
```
|
||||
|
||||
Currently, there is no standardized way of doing this. The simplest way to do it would be to simply attach the stringified error to the message.
|
||||
|
||||
```swift
|
||||
logger.warning("Something went wrong: \(error)")
|
||||
```
|
||||
|
||||
This of course is not _structured_, so a better way would be:
|
||||
|
||||
```swift
|
||||
logger.warning("Something went wrong", metadata: ["error": "\(error)"])
|
||||
```
|
||||
|
||||
However, since there is no clear preference for what metadata key to use, it is likely that different code bases use variations of the above. This makes it hard for automated tools to extract error information, since there is no single key to look for.
|
||||
|
||||
Additionally, there is more information that we could extract from the error, such as the type name.
|
||||
|
||||
```swift
|
||||
logger.warning("Something went wrong", metadata: ["error.message": "\(error)", "error.type": "\(String(reflecting: type(of: 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 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
|
||||
|
||||
The solution we propose is to add convenience methods in `Logger` that allows the caller to do the following:
|
||||
|
||||
```swift
|
||||
do {
|
||||
try someThrowingFunc()
|
||||
} catch {
|
||||
logger.warning("Something went wrong", error: error)
|
||||
}
|
||||
```
|
||||
|
||||
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).
|
||||
* `LogHandler`s are free to serialize the `Error` in an way appropriate to that handler.
|
||||
|
||||
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
|
||||
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 }
|
||||
}
|
||||
// ...
|
||||
}
|
||||
|
||||
/* ... */
|
||||
}
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
```swift
|
||||
extension Logger {
|
||||
/// Log a message at the 'trace' log level with the source that you provide.
|
||||
///
|
||||
/// If ``Level/trace`` is at least as severe as this logger's ``logLevel`` the system logs the message;
|
||||
/// otherwise nothing will happen.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - message: The message to be logged. The `message` parameter supports any string interpolation literal.
|
||||
/// - 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.
|
||||
/// - file: The file this log message originates from. There's usually no need to pass it explicitly, as it
|
||||
/// defaults to `#fileID`.
|
||||
/// - function: The function this log message originates from. There's usually no need to pass it explicitly, as
|
||||
/// it defaults to `#function`.
|
||||
/// - line: The line this log message originates from. There's usually no need to pass it explicitly, as it
|
||||
/// defaults to `#line`.
|
||||
@inlinable
|
||||
public func trace(
|
||||
_ message: @autoclosure () -> Logger.Message,
|
||||
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;
|
||||
/// otherwise nothing will happen.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - message: The message to be logged. The `message` parameter supports any string interpolation literal.
|
||||
/// - 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.
|
||||
/// - file: The file this log message originates from. There's usually no need to pass it explicitly, as it
|
||||
/// defaults to `#fileID`.
|
||||
/// - function: The function this log message originates from. There's usually no need to pass it explicitly, as
|
||||
/// it defaults to `#function`.
|
||||
/// - line: The line this log message originates from. There's usually no need to pass it explicitly, as it
|
||||
/// defaults to `#line`.
|
||||
@inlinable
|
||||
public func debug(
|
||||
_ message: @autoclosure () -> Logger.Message,
|
||||
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 'info' log level with the source that you provide.
|
||||
///
|
||||
/// If ``Level/info`` is at least as severe as this logger's ``logLevel`` the system logs the message;
|
||||
/// otherwise nothing will happen.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - message: The message to be logged. The `message` parameter supports any string interpolation literal.
|
||||
/// - 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.
|
||||
/// - file: The file this log message originates from. There's usually no need to pass it explicitly, as it
|
||||
/// defaults to `#fileID`.
|
||||
/// - function: The function this log message originates from. There's usually no need to pass it explicitly, as
|
||||
/// it defaults to `#function`.
|
||||
/// - line: The line this log message originates from. There's usually no need to pass it explicitly, as it
|
||||
/// defaults to `#line`.
|
||||
@inlinable
|
||||
public func info(
|
||||
_ message: @autoclosure () -> Logger.Message,
|
||||
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 'notice' log level with the source that you provide.
|
||||
///
|
||||
/// If ``Level/notice`` is at least as severe as this logger's ``logLevel`` the system logs the message;
|
||||
/// otherwise nothing will happen.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - message: The message to be logged. The `message` parameter supports any string interpolation literal.
|
||||
/// - 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.
|
||||
/// - file: The file this log message originates from. There's usually no need to pass it explicitly, as it
|
||||
/// defaults to `#fileID`.
|
||||
/// - function: The function this log message originates from. There's usually no need to pass it explicitly, as
|
||||
/// it defaults to `#function`.
|
||||
/// - line: The line this log message originates from. There's usually no need to pass it explicitly, as it
|
||||
/// defaults to `#line`.
|
||||
@inlinable
|
||||
public func notice(
|
||||
_ message: @autoclosure () -> Logger.Message,
|
||||
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 'warning' log level with the source that you provide.
|
||||
///
|
||||
/// If ``Level/warning`` is at least as severe as this logger's ``logLevel`` the system logs the message;
|
||||
/// otherwise nothing will happen.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - message: The message to be logged. The `message` parameter supports any string interpolation literal.
|
||||
/// - 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.
|
||||
/// - file: The file this log message originates from. There's usually no need to pass it explicitly, as it
|
||||
/// defaults to `#fileID`.
|
||||
/// - function: The function this log message originates from. There's usually no need to pass it explicitly, as
|
||||
/// it defaults to `#function`.
|
||||
/// - line: The line this log message originates from. There's usually no need to pass it explicitly, as it
|
||||
/// defaults to `#line`.
|
||||
@inlinable
|
||||
public func warning(
|
||||
_ message: @autoclosure () -> Logger.Message,
|
||||
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 'error' log level with the source that you provide.
|
||||
///
|
||||
/// If ``Level/error`` is at least as severe as this logger's ``logLevel`` the system logs the message;
|
||||
/// otherwise nothing will happen.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - message: The message to be logged. The `message` parameter supports any string interpolation literal.
|
||||
/// - 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.
|
||||
/// - file: The file this log message originates from. There's usually no need to pass it explicitly, as it
|
||||
/// defaults to `#fileID`.
|
||||
/// - function: The function this log message originates from. There's usually no need to pass it explicitly, as
|
||||
/// it defaults to `#function`.
|
||||
/// - line: The line this log message originates from. There's usually no need to pass it explicitly, as it
|
||||
/// defaults to `#line`.
|
||||
@inlinable
|
||||
public func error(
|
||||
_ message: @autoclosure () -> Logger.Message,
|
||||
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 'critical' log level with the source that you provide.
|
||||
///
|
||||
/// If ``Level/critical`` is at least as severe as this logger's ``logLevel`` the system logs the message;
|
||||
/// otherwise nothing will happen.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - message: The message to be logged. The `message` parameter supports any string interpolation literal.
|
||||
/// - 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.
|
||||
/// - file: The file this log message originates from. There's usually no need to pass it explicitly, as it
|
||||
/// defaults to `#fileID`.
|
||||
/// - function: The function this log message originates from. There's usually no need to pass it explicitly, as
|
||||
/// it defaults to `#function`.
|
||||
/// - line: The line this log message originates from. There's usually no need to pass it explicitly, as it
|
||||
/// defaults to `#line`.
|
||||
@inlinable
|
||||
public func critical(
|
||||
_ message: @autoclosure () -> Logger.Message,
|
||||
error: (any Error)?,
|
||||
metadata: @autoclosure () -> Logger.Metadata? = nil,
|
||||
source: @autoclosure () -> String? = nil,
|
||||
file: String = #fileID,
|
||||
function: String = #function,
|
||||
line: UInt = #line
|
||||
)
|
||||
|
||||
/// Log a message using the log level and source that you provide.
|
||||
///
|
||||
/// If the `logLevel` passed to this method is more severe than the `Logger`'s ``logLevel``, the library
|
||||
/// logs the message, otherwise nothing will happen.
|
||||
///
|
||||
/// - 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` 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.
|
||||
/// - file: The file this log message originates from. There's usually no need to pass it explicitly, as it
|
||||
/// defaults to `#fileID`.
|
||||
/// - function: The function this log message originates from. There's usually no need to pass it explicitly, as
|
||||
/// it defaults to `#function`.
|
||||
/// - line: The line this log message originates from. There's usually no need to pass it explicitly, as it
|
||||
/// defaults to `#line`.
|
||||
@inlinable
|
||||
public func log(
|
||||
level: Logger.Level,
|
||||
_ message: @autoclosure () -> Logger.Message,
|
||||
error: (any Error)?,
|
||||
metadata: @autoclosure () -> Logger.Metadata? = nil,
|
||||
source: @autoclosure () -> String? = nil,
|
||||
file: String = #fileID,
|
||||
function: String = #function,
|
||||
line: UInt = #line
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
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.
|
||||
///
|
||||
/// 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
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
A draft implementation can be found in [apple/swift-log#425](https://github.com/apple/swift-log/pull/425).
|
||||
|
||||
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`, thanks to the default implementation and since a `LogHandler` is already expected to handle `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"])
|
||||
```
|
||||
|
||||
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
|
||||
|
||||
#### recordError
|
||||
|
||||
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
|
||||
|
||||
#### Standardized Error metadata via Logger convenience
|
||||
|
||||
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.*"`).
|
||||
|
||||
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.
|
||||
|
||||
#### recordError convenience method
|
||||
|
||||
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.
|
||||
|
||||
#### Using .stringConvertible to pass Error to LogHandler
|
||||
|
||||
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.
|
||||
@@ -0,0 +1,467 @@
|
||||
# SLG-0004: Metadata values privacy attribute
|
||||
|
||||
Introduce an attributed metadata system that allows attaching attributes to metadata values, with privacy level as the first attribute enabling developers to mark metadata as `.private` or `.public`.
|
||||
|
||||
## Overview
|
||||
|
||||
- Proposal: SLG-0004
|
||||
- Author(s): [Vladimir Kukushkin](https://github.com/kukushechkin)
|
||||
- Status: **Deferred**
|
||||
- Issue: https://github.com/apple/swift-log/issues/204
|
||||
- Implementation:
|
||||
- [apple/swift-log#418](https://github.com/apple/swift-log/pull/418)
|
||||
- Related links:
|
||||
- [Lightweight proposals process description](https://github.com/apple/swift-log/blob/main/Sources/Logging/Docs.docc/Proposals/Proposals.md)
|
||||
- [Review discussion](https://forums.swift.org/t/proposal-slg-0004-metadata-values-privacy-attribute/85249/16)
|
||||
|
||||
### Introduction
|
||||
|
||||
This proposal introduces an **attributed metadata system** that allows attaching attributes to metadata values. Privacy level is the first concrete attribute, enabling developers to mark metadata values as `.private` or `.public` so `LogHandler` implementations can redact sensitive values before logging.
|
||||
|
||||
### Motivation
|
||||
|
||||
SwiftLog lacks a mechanism to attach attributes to metadata values. This prevents marking metadata as sensitive and limits future extensibility for other metadata attributes.
|
||||
|
||||
Applications need privacy controls for:
|
||||
- Compliance with privacy regulations.
|
||||
- Backend integration with privacy-aware logging systems.
|
||||
- Systematic control over what data appears in logs.
|
||||
|
||||
Beyond privacy, an attributed metadata system provides a foundation for future extensions such as retention policies, data classification, or other metadata attributes.
|
||||
|
||||
### Proposed solution
|
||||
|
||||
Introduce new `AttributedMetadata` data type, enabling users to mark metadata values with `.private` and `.public` privacy label:
|
||||
|
||||
```swift
|
||||
// Add privacy level to metadata values obtained through a metadata provider
|
||||
let serviceIp = "127.0.0.1"
|
||||
var logger = Logger(label: "my-app", metadataProvider: .init {[
|
||||
"service.ip": "\(serviceIp, privacy: .private)",
|
||||
]})
|
||||
|
||||
// Add privacy level to metadata values attached to a `Loghandler` instance
|
||||
let requestId = UUID()
|
||||
logger[attributedMetadataKey: "request.id"] = "\(requestId, privacy: .private)"
|
||||
|
||||
// Mark sensitive values as private and non-sensitive as public at logging call site
|
||||
let userId = UUID()
|
||||
let action = "login"
|
||||
logger.info("User action", attributedMetadata: [
|
||||
"user.id": "\(userId, privacy: .private)",
|
||||
"action": "\(action)" // default is .public for ease of adoption
|
||||
])
|
||||
```
|
||||
|
||||
This allows `Logger` users to mark certain metadata values as "I only trust LogHandlers, who know how to handle sensitive data, to see this value".
|
||||
|
||||
### Detailed design
|
||||
|
||||
#### Attributed Metadata
|
||||
|
||||
To support privacy labels and enable future extensibility, we introduce a generalized **attributed metadata** system. This provides a foundation for attaching arbitrary attributes to metadata values, with privacy labels being the first concrete use case:
|
||||
|
||||
```swift
|
||||
// Plain metadata (existing)
|
||||
let metadataValue: MetadataValue = .string("value")
|
||||
logger.info("Message", metadata: ["key": metadataValue])
|
||||
|
||||
// Attributed metadata (new) — a value with attributes
|
||||
logger.info("Message", attributedMetadata: [
|
||||
"key": AttributedMetadataValue(value: metadataValue, attributes: ...)
|
||||
])
|
||||
```
|
||||
|
||||
The attributed metadata system instroduces new public API:
|
||||
|
||||
1. **`AttributedMetadataValue`**: Wraps a standard `MetadataValue` with associated attributes.
|
||||
2. **`MetadataValueAttributes`**: Container for attributes.
|
||||
3. **`AttributedMetadata`**: Dictionary type mapping `String` keys to attributed values.
|
||||
4. **Parallel logging API**: New log methods accepting `attributedMetadata` parameter.
|
||||
|
||||
This design separates the transport mechanism (attributed metadata) from specific attribute semantics (privacy labels), allowing future extensions without breaking existing attributed metadata code.
|
||||
|
||||
#### Privacy levels
|
||||
|
||||
With attributed metadata as the foundation, privacy labels are implemented as the first concrete attribute:
|
||||
|
||||
```swift
|
||||
extension Logger {
|
||||
/// A metadata value with associated privacy attributes.
|
||||
///
|
||||
/// `AttributedMetadataValue` wraps a standard `MetadataValue` with privacy attributes,
|
||||
/// allowing you to mark metadata as private or public for privacy-aware logging.
|
||||
///
|
||||
/// ## Creating Attributed Metadata
|
||||
///
|
||||
/// Use string interpolation with privacy parameter:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Preferred: String interpolation with privacy level specified
|
||||
/// let userId = "12345"
|
||||
/// let action = "login"
|
||||
/// logger.info("User action", attributedMetadata: [
|
||||
/// "user.id": "\(userId, privacy: .private)",
|
||||
/// "action": "\(action, privacy: .public)" // explicit .public for non-sensitive data
|
||||
/// ])
|
||||
///
|
||||
/// // Direct creation
|
||||
/// let attributed = Logger.AttributedMetadataValue(
|
||||
/// .string("12345"),
|
||||
/// privacy: .private
|
||||
/// )
|
||||
/// ```
|
||||
///
|
||||
/// ## Important Limitations
|
||||
///
|
||||
/// - **No nested privacy**: When marking a dictionary or array as private, all contained
|
||||
/// values are treated with the same privacy level. Fine-grained privacy within nested
|
||||
/// structures is not currently supported.
|
||||
///
|
||||
/// - **Metadata only**: Privacy levels apply only to metadata values, not to log messages.
|
||||
/// Avoid including sensitive data in log message string interpolation.
|
||||
public struct AttributedMetadataValue: CustomStringConvertible, Sendable {
|
||||
/// The redaction marker used for private values.
|
||||
internal static let redactionMarker = "<private>"
|
||||
|
||||
public let value: MetadataValue
|
||||
public let attributes: MetadataValueAttributes
|
||||
|
||||
/// String representation redacts private values to the redaction marker.
|
||||
public var description: String {
|
||||
attributes.privacy == .public ? value.description : Self.redactionMarker
|
||||
}
|
||||
|
||||
public init(_ value: MetadataValue, attributes: MetadataValueAttributes)
|
||||
public init(_ value: MetadataValue, privacy: PrivacyLevel)
|
||||
}
|
||||
|
||||
extension AttributedMetadataValue {
|
||||
/// Attributes that can be associated with metadata values.
|
||||
public struct MetadataValueAttributes: CustomStringConvertible, Hashable, Sendable {
|
||||
/// Privacy level for metadata values.
|
||||
///
|
||||
/// Privacy levels allow you to mark metadata values as either private (sensitive data that should be
|
||||
/// protected) or public (safe to log in any context).
|
||||
///
|
||||
/// ## Usage
|
||||
///
|
||||
/// Use string interpolation with the privacy parameter to create attributed metadata values:
|
||||
///
|
||||
/// ```swift
|
||||
/// let userId = "12345"
|
||||
/// let action = "login"
|
||||
/// logger.info("User action", attributedMetadata: [
|
||||
/// "user.id": "\(userId, privacy: .private)",
|
||||
/// "action": "\(action, privacy: .public)",
|
||||
/// "ip": "\(ipAddress, privacy: .private)"
|
||||
/// ])
|
||||
/// ```
|
||||
@frozen
|
||||
public enum PrivacyLevel: Sendable, CaseIterable, Equatable, Hashable, CustomStringConvertible {
|
||||
/// Private data that should be redacted in non-secure contexts.
|
||||
case `private`
|
||||
|
||||
/// Public data safe for general logging.
|
||||
case `public`
|
||||
}
|
||||
|
||||
/// The privacy level of this metadata value.
|
||||
public var privacy: PrivacyLevel
|
||||
|
||||
/// Create metadata value attributes with the specified privacy level.
|
||||
///
|
||||
/// - Parameter privacy: The privacy level for this metadata. Defaults to `.public`.
|
||||
public init(privacy: PrivacyLevel = .public)
|
||||
}
|
||||
|
||||
/// The underlying metadata value without privacy attributes.
|
||||
public var value: MetadataValue
|
||||
|
||||
/// The privacy attributes associated with this metadata value.
|
||||
public var attributes: MetadataValueAttributes
|
||||
|
||||
/// Create an attributed metadata value with the specified attributes.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - value: The metadata value to wrap.
|
||||
/// - attributes: The attributes for this value.
|
||||
public init(_ value: MetadataValue, attributes: MetadataValueAttributes)
|
||||
|
||||
/// Convenience initializer for creating attributed metadata with a privacy level.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - value: The metadata value to wrap.
|
||||
/// - privacy: The privacy level for this value.
|
||||
public init(_ value: MetadataValue, privacy: PrivacyLevel)
|
||||
}
|
||||
|
||||
/// Metadata dictionary with privacy attributes.
|
||||
///
|
||||
/// A dictionary mapping string keys to ``AttributedMetadataValue`` instances, used with
|
||||
/// the `attributedMetadata` parameter of logging methods.
|
||||
///
|
||||
/// ## Example
|
||||
///
|
||||
/// ```swift
|
||||
/// let userId = "12345"
|
||||
/// let requestId = "req-789"
|
||||
/// let metadata: Logger.AttributedMetadata = [
|
||||
/// "user.id": "\(userId, privacy: .private)",
|
||||
/// "request.id": "\(requestId, privacy: .public)",
|
||||
/// "action": "purchase" // String literal defaults to .public
|
||||
/// ]
|
||||
/// logger.info("User action", attributedMetadata: metadata)
|
||||
/// ```
|
||||
public typealias AttributedMetadata = [String: AttributedMetadataValue]
|
||||
}
|
||||
```
|
||||
|
||||
#### String interpolation for attributed metadata
|
||||
|
||||
```swift
|
||||
extension Logger.AttributedMetadataValue: ExpressibleByStringLiteral, ExpressibleByStringInterpolation {
|
||||
/// Custom string interpolation that captures privacy levels from interpolated values.
|
||||
///
|
||||
/// This enables syntax like:
|
||||
/// ```swift
|
||||
/// logger.info("User action", attributedMetadata: [
|
||||
/// "user.id": "\(userId, privacy: .private)",
|
||||
/// "action": "\(action, privacy: .public)"
|
||||
/// ])
|
||||
/// ```
|
||||
public struct StringInterpolation: StringInterpolationProtocol {
|
||||
public init(literalCapacity: Int, interpolationCount: Int)
|
||||
public mutating func appendLiteral(_ literal: String)
|
||||
|
||||
/// Interpolation with explicit privacy parameter.
|
||||
public mutating func appendInterpolation<T>(_ value: T, privacy: Logger.PrivacyLevel = .public)
|
||||
where T: CustomStringConvertible
|
||||
}
|
||||
|
||||
/// Creates an attributed metadata value from a string literal (defaults to .public).
|
||||
public init(stringLiteral value: String)
|
||||
|
||||
/// Creates an attributed metadata value from string interpolation.
|
||||
public init(stringInterpolation: StringInterpolation)
|
||||
}
|
||||
```
|
||||
|
||||
#### New Logger methods
|
||||
|
||||
```swift
|
||||
extension Logger {
|
||||
// Attributed metadata storage
|
||||
var attributedMetadata: Logger.AttributedMetadata { get set }
|
||||
subscript(attributedMetadataKey: String) -> Logger.AttributedMetadataValue? { get set }
|
||||
|
||||
// Log family of methods
|
||||
public func log(level: Level, _ message: @autoclosure () -> Message,
|
||||
attributedMetadata: @autoclosure () -> AttributedMetadata?,
|
||||
source: @autoclosure () -> String? = nil,
|
||||
file: String = #fileID, function: String = #function, line: UInt = #line)
|
||||
public func trace(_ message: @autoclosure () -> Message,
|
||||
attributedMetadata: @autoclosure () -> AttributedMetadata?,
|
||||
source: @autoclosure () -> String? = nil,
|
||||
file: String = #fileID, function: String = #function, line: UInt = #line)
|
||||
public func debug(_ message: @autoclosure () -> Message,
|
||||
attributedMetadata: @autoclosure () -> AttributedMetadata?,
|
||||
source: @autoclosure () -> String? = nil,
|
||||
file: String = #fileID, function: String = #function, line: UInt = #line)
|
||||
public func info(_ message: @autoclosure () -> Message,
|
||||
attributedMetadata: @autoclosure () -> AttributedMetadata?,
|
||||
source: @autoclosure () -> String? = nil,
|
||||
file: String = #fileID, function: String = #function, line: UInt = #line)
|
||||
public func notice(_ message: @autoclosure () -> Message,
|
||||
attributedMetadata: @autoclosure () -> AttributedMetadata?,
|
||||
source: @autoclosure () -> String? = nil,
|
||||
file: String = #fileID, function: String = #function, line: UInt = #line)
|
||||
public func warning(_ message: @autoclosure () -> Message,
|
||||
attributedMetadata: @autoclosure () -> AttributedMetadata?,
|
||||
source: @autoclosure () -> String? = nil,
|
||||
file: String = #fileID, function: String = #function, line: UInt = #line)
|
||||
public func error(_ message: @autoclosure () -> Message,
|
||||
attributedMetadata: @autoclosure () -> AttributedMetadata?,
|
||||
source: @autoclosure () -> String? = nil,
|
||||
file: String = #fileID, function: String = #function, line: UInt = #line)
|
||||
public func critical(_ message: @autoclosure () -> Message,
|
||||
attributedMetadata: @autoclosure () -> AttributedMetadata?,
|
||||
source: @autoclosure () -> String? = nil,
|
||||
file: String = #fileID, function: String = #function, line: UInt = #line)
|
||||
}
|
||||
```
|
||||
|
||||
#### AttributedMetadata support in LogHandler protocol
|
||||
|
||||
```swift
|
||||
protocol LogHandler {
|
||||
func log(level: Logger.Level, message: Logger.Message,
|
||||
attributedMetadata: Logger.AttributedMetadata?, source: String,
|
||||
file: String, function: String, line: UInt)
|
||||
|
||||
var attributedMetadata: Logger.AttributedMetadata { get set }
|
||||
subscript(attributedMetadataKey: String) -> Logger.AttributedMetadataValue? { get set }
|
||||
}
|
||||
|
||||
// Default implementations provided for backward compatibility
|
||||
extension LogHandler {
|
||||
// Default attributed metadata log method - redacts private values using helper
|
||||
public func log(level: Logger.Level, message: Logger.Message,
|
||||
attributedMetadata: Logger.AttributedMetadata?,
|
||||
source: String, file: String, function: String, line: UInt) {
|
||||
let processedMetadata = attributedMetadata.flatMap(Self.attributedToPlain)
|
||||
self.log(level: level, message: message, metadata: processedMetadata,
|
||||
source: source, file: file, function: function, line: line)
|
||||
}
|
||||
|
||||
// Default attributed metadata storage - uses helpers for conversion
|
||||
public var attributedMetadata: Logger.AttributedMetadata {
|
||||
get { self.metadata.mapValues(Self.plainToAttributed) }
|
||||
set { self.metadata = newValue.mapValues(Self.attributedToPlain) }
|
||||
}
|
||||
|
||||
public subscript(attributedMetadataKey key: String) -> Logger.AttributedMetadataValue? {
|
||||
get {
|
||||
guard let plainValue = self[metadataKey: key] else { return nil }
|
||||
return Self.plainToAttributed(plainValue)
|
||||
}
|
||||
set {
|
||||
if let attributedValue = newValue {
|
||||
self[metadataKey: key] = Self.attributedToPlain(attributedValue)
|
||||
} else {
|
||||
self[metadataKey: key] = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### AttributedMetadata support in MetadataProvider
|
||||
|
||||
```swift
|
||||
extension Logger.MetadataProvider {
|
||||
/// Creates a new metadata provider that returns attributed metadata.
|
||||
///
|
||||
/// Attributed metadata providers allow you to specify privacy levels and other
|
||||
/// attributes for each metadata value. When accessed through the plain ``get()``
|
||||
/// method (for backward compatibility), private values are redacted to `"<private>"`.
|
||||
///
|
||||
/// ### Example
|
||||
///
|
||||
/// ```swift
|
||||
/// let provider = Logger.MetadataProvider {
|
||||
/// [
|
||||
/// "request-id": "\(RequestContext.current.id, privacy: .public)",
|
||||
/// "user-id": "\(RequestContext.current.userId, privacy: .private)"
|
||||
/// ]
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - Parameter provideAttributed: A closure that extracts attributed metadata from the current execution context.
|
||||
/// - Returns: A metadata provider that returns attributed metadata.
|
||||
@_disfavoredOverload
|
||||
public static func init(_ provideAttributed: @escaping @Sendable () -> AttributedMetadata) -> MetadataProvider
|
||||
|
||||
/// Returns attributed metadata if this is an attributed provider.
|
||||
///
|
||||
/// Handlers supporting attributed metadata should call this first,
|
||||
/// falling back to `get()` if it returns nil.
|
||||
public func getAttributed() -> AttributedMetadata?
|
||||
}
|
||||
```
|
||||
|
||||
### API stability
|
||||
|
||||
- All existing APIs unchanged.
|
||||
- Plain and attributed metadata APIs coexist.
|
||||
- No deprecation planned.
|
||||
- Adoption is optional and incremental on both application and Log Handler sides.
|
||||
- Default implementation ensures existing handlers work; logging private metadata is an application concern requiring a compatible `LogHandler`.
|
||||
|
||||
### Future directions
|
||||
|
||||
- Add more attributes (e.g., value data type, etc) and potential future unification of plain and attributed metadata APIs.
|
||||
- Introduce "custom attributes", allowing applications to define application-specific attributes to work with application-specific log handlers.
|
||||
|
||||
### Alternatives considered
|
||||
|
||||
1. **Key-based redaction:** Configure which keys should be treated as private rather than marking each value:
|
||||
|
||||
```swift
|
||||
logger.privateKeys = ["user.id", "password", "email"]
|
||||
logger.info("User action", metadata: [
|
||||
"user.id": "12345", // Automatically private
|
||||
"action": "login" // Automatically public
|
||||
])
|
||||
```
|
||||
|
||||
Advantages:
|
||||
- Simpler API (no new types).
|
||||
- Centralized configuration.
|
||||
- Safer at scale (new sensitive fields update all logs automatically).
|
||||
- Easier migration.
|
||||
|
||||
**Not chosen because:**
|
||||
|
||||
- **Privacy belongs to data, not identifiers:** The same private data might be logged under different keys ("email", "user.email", "contact"), and the same key might contain different data with different privacy requirements in different contexts. Key-based redaction creates a synchronization problem—developers must maintain a separate list of "private keys" that stays in sync with actual logging code across the codebase, with no compile-time or review-time verification.
|
||||
|
||||
- **Code review visibility:** With value-based privacy, reviewers see privacy decisions at the call site: `"email": user.email.private()` makes it immediately clear that data is sensitive. With key-based redaction, reviewers must cross-reference a separate configuration file, making security review significantly harder.
|
||||
|
||||
- **No synchronization needed:** Value-based privacy is self-contained—privacy travels with the data at the point of use. No separate configuration to maintain, no risk of configuration drift, no runtime surprises when a key is missing from the private keys list.
|
||||
|
||||
- **Pattern complexity:** Supporting patterns/regex adds complexity and potential performance concerns.
|
||||
|
||||
The current design prioritizes **explicitness and data-centric privacy** over **configuration-based simplicity**. Privacy decisions are made where data is logged, making them visible during code review and keeping privacy attributes coupled to the data they protect.
|
||||
|
||||
2. **Convenience methods (`.private()` and `.public()`):** Add extension methods to `String` and `MetadataValue` for creating attributed metadata:
|
||||
|
||||
```swift
|
||||
extension String {
|
||||
public func `private`() -> Logger.AttributedMetadataValue
|
||||
public func `public`() -> Logger.AttributedMetadataValue
|
||||
}
|
||||
|
||||
logger.info("User action", attributedMetadata: [
|
||||
"user.id": "12345".private(),
|
||||
"action": "login".public()
|
||||
])
|
||||
```
|
||||
|
||||
**Not chosen because:**
|
||||
|
||||
- **Consistency with existing patterns:** `Logger.Message` and `Logger.MetadataValue` already use string interpolation extensively.
|
||||
- **Natural syntax:** `"\(value, privacy: .private)"` reads clearly and fits Swift's interpolation conventions.
|
||||
- **Less API surface:** No need for multiple extension methods across different types.
|
||||
|
||||
Metadata values already support string interpolation in SwiftLog. Rather than inventing additional API surface area with new methods, we leverage the existing string interpolation infrastructure with a custom `StringInterpolation` type. This provides:
|
||||
|
||||
3. **Default privacy level to `.private`:** Make attributed metadata values default to `.private` privacy level when no explicit privacy parameter is provided:
|
||||
|
||||
```swift
|
||||
logger.info("User action", attributedMetadata: [
|
||||
"user.id": "\(userId, privacy: .private)", // Explicit private (redundant with default)
|
||||
"action": "\(action, privacy: .public)" // Must explicitly mark as public
|
||||
])
|
||||
```
|
||||
|
||||
Advantages:
|
||||
- Security-by-default: requires explicit opt-out for logging non-sensitive data.
|
||||
- Safer for accidental inclusion of sensitive data.
|
||||
|
||||
**Not chosen because:**
|
||||
|
||||
Privacy should be an explicit opt-in action from the user. The current design (defaulting to `.public`) prioritizes **ease of adoption** over **security-by-default**:
|
||||
- Easier adoption - less boilerplate for common non-sensitive metadata.
|
||||
- Matches the mental model that "most data is safe to log".
|
||||
- Lower friction for migration from plain metadata.
|
||||
- Forces developers to think about privacy only for sensitive data, rather than requiring `.public` annotations everywhere.
|
||||
|
||||
4. **Pass all metadata to non-privacy-aware handlers:** Security risk; current design filters private data by default.
|
||||
|
||||
5. **Message-level privacy:** Less granular than metadata-level privacy and requires message handling changes.
|
||||
|
||||
6. **Privacy level handling configuration** to be an attribute of the `Logger` instead of LogHandler configuration. This would centralize the configuration across various `LogHandler` implementations. However, existing `LogHandler` already have configurations and they might want to customize the behavior even further.
|
||||
|
||||
7. **Handler metadata merging:** LogHandlers are responsible for merging their own `metadata` property, `metadataProvider` output, and the explicit `attributedMetadata` parameter. This is consistent with how plain metadata works - handlers control merging. Plain handler metadata and provider values should be treated as public (`.public` privacy level). Attributed metadata from the log call takes precedence.
|
||||
|
||||
8. **Add a third `.auto`/`.default` privacy attribute value:** Libraries and applications can mark a metadata value as `privacy: .default` and rely on the `LogHandler` to configure what the default is. While this might've been a solution to overcome default `.public` values for all the attributed metadata, in reality it is confusing from the semantic point of view. If someone wants to mark something as `.default`, because this _might_ be sensitive, then it should be marked as `.private` or not logged at all. If something does not need to be marked as `.private`, then it is `.public`. A custom `LogHandler` with an allow list of metadata keys/messages/modules can be used as an escape hatch in case the application does not trust its dependencies.
|
||||
@@ -0,0 +1,180 @@
|
||||
# SLG-0005: `LogEvent`-based `LogHandler` API
|
||||
|
||||
Replace the flat-parameter `log(level:message:metadata:source:file:function:line:)` method on `LogHandler` with
|
||||
`log(event: LogEvent)`, enabling forward-compatible evolution of the `LogHandler` interface without breaking existing
|
||||
handler implementations.
|
||||
|
||||
## Overview
|
||||
|
||||
- Proposal: SLG-0005
|
||||
- Author(s): [Vladimir Kukushkin](https://github.com/kukushechkin)
|
||||
- Status: **Approved**
|
||||
- Issue: [apple/swift-log#421](https://github.com/apple/swift-log/issues/421)
|
||||
- Implementation:
|
||||
- [apple/swift-log#423](https://github.com/apple/swift-log/pull/423)
|
||||
- Related links:
|
||||
- [Lightweight proposals process description](https://github.com/apple/swift-log/blob/main/Sources/Logging/Docs.docc/Proposals/Proposals.md)
|
||||
- [SLG-0003: Standardized Error Metadata via Logger Convenience](https://github.com/apple/swift-log/blob/main/Sources/Logging/Docs.docc/Proposals/SLG-0003.md)
|
||||
|
||||
### Introduction
|
||||
|
||||
Introduce `LogEvent` that bundles all log-statement data, and replace the flat-parameter
|
||||
`log(level:message:metadata:source:file:function:line:)` method on `LogHandler` with `log(event: LogEvent)`.
|
||||
|
||||
### Motivation
|
||||
|
||||
The `LogHandler` protocol currently requires implementing a single method with seven parameters:
|
||||
|
||||
```swift
|
||||
func log(
|
||||
level: Logger.Level,
|
||||
message: Logger.Message,
|
||||
metadata: Logger.Metadata?,
|
||||
source: String,
|
||||
file: String,
|
||||
function: String,
|
||||
line: UInt
|
||||
)
|
||||
```
|
||||
|
||||
Every time a new piece of data needs to be forwarded from a log call site to the handler — an error, or a richer metadata type — the only options are:
|
||||
|
||||
- **Add a new parameter to the existing method.** This is a source-breaking change: every existing `LogHandler`
|
||||
implementation across the entire Swift ecosystem must be updated simultaneously.
|
||||
- **Add a new `Logger` overload.** This requires 2 parallel APIs to coexist until the old one can be safely deprecated.
|
||||
|
||||
### Proposed solution
|
||||
|
||||
Introduce `LogEvent`, a `struct` that carries all the data associated with a single log statement. `LogEvent` is
|
||||
a handler-side type: it is constructed by `Logger._log` and passed to `LogHandler`. The public `Logger` call-site
|
||||
API — `logger.info(...)`, `logger.log(level:...)` and so on — is unchanged.
|
||||
|
||||
The `LogHandler` protocol gains a new required method `log(event: LogEvent)`, while the old flat-parameter method
|
||||
is deprecated.
|
||||
|
||||
For existing handlers, a default implementation of `log(event:)` forwards to the old method, so no code changes
|
||||
are required to keep existing implementations working. Handlers that want to take advantage of new fields added to
|
||||
`LogEvent` in future proposals implement `log(event:)`.
|
||||
|
||||
### Detailed design
|
||||
|
||||
#### New `LogEvent` type
|
||||
|
||||
A new top-level `struct` in the `Logging` module:
|
||||
|
||||
```swift
|
||||
public struct LogEvent: Sendable {
|
||||
public var level: Logger.Level
|
||||
public var message: Logger.Message
|
||||
private var _metadata: Logger.Metadata?
|
||||
public var metadata: Logger.Metadata? {
|
||||
get { self._metadata }
|
||||
set { self._metadata = newValue }
|
||||
}
|
||||
public var source: String
|
||||
public var file: String
|
||||
public var function: String
|
||||
public var line: UInt
|
||||
|
||||
public init(
|
||||
level: Logger.Level,
|
||||
message: Logger.Message,
|
||||
metadata: Logger.Metadata?,
|
||||
source: String,
|
||||
file: String,
|
||||
function: String,
|
||||
line: UInt
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
#### Updated `LogHandler` protocol
|
||||
|
||||
```swift
|
||||
public protocol LogHandler: _SwiftLogSendableLogHandler {
|
||||
|
||||
/// The library calls this method when a log handler 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.
|
||||
///
|
||||
/// - Parameter event: The log event containing the level, message, metadata, and source location.
|
||||
func log(event: LogEvent)
|
||||
|
||||
/// Please do _not_ implement this method when you create a `LogHandler` implementation.
|
||||
/// Implement ``log(event:)`` instead.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - level: The log level of the message.
|
||||
/// - message: The message to log. To obtain a `String` representation call `message.description`.
|
||||
/// - 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.
|
||||
@available(*, deprecated, renamed: "log(event:)")
|
||||
func log(
|
||||
level: Logger.Level,
|
||||
message: Logger.Message,
|
||||
metadata: Logger.Metadata?,
|
||||
source: String,
|
||||
file: String,
|
||||
function: String,
|
||||
line: UInt
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
#### Default implementation
|
||||
|
||||
The default for `log(event:)` forwards all event fields to the old flat-parameter method,
|
||||
preserving the behavior of existing handlers with no source changes required.
|
||||
|
||||
The default implementation is marked as deprecated to encourage handler authors to migrate to `log(event:)`.
|
||||
Handlers that still rely on the forwarding bridge will see a deprecation warning at compile time, signaling that
|
||||
they should adopt the new method directly.
|
||||
|
||||
```swift
|
||||
extension LogHandler {
|
||||
@available(*, deprecated, message: "You should implement this method instead of using the default implementation")
|
||||
public func log(event: LogEvent) {
|
||||
self.log(
|
||||
level: event.level,
|
||||
message: event.message,
|
||||
metadata: event.metadata,
|
||||
source: event.source,
|
||||
file: event.file,
|
||||
function: event.function,
|
||||
line: event.line
|
||||
)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### API stability
|
||||
|
||||
**For existing `Logger` users:** No changes. All existing call sites continue to compile and behave identically.
|
||||
|
||||
**For existing `LogHandler` implementations:** Implementations of
|
||||
`log(level:message:metadata:source:file:function:line:)` continue to work without any source changes. The
|
||||
default implementation of `log(event:)` forwards to the old method.
|
||||
|
||||
### Future directions
|
||||
|
||||
Future proposals can add new fields to `LogEvent` with sensible defaults — a richer metadata
|
||||
type, or an attached `Error` (as a follow-up for [SLG-0003 proposal](https://forums.swift.org/t/proposal-slg-0003-standardized-error-metadata-via-logger-convenience/84518/39)) —
|
||||
without touching the `LogHandler` protocol and without requiring any changes to
|
||||
existing handler implementations. This is the primary motivation for this proposal.
|
||||
|
||||
The [SLG-0004 proposal](https://github.com/apple/swift-log/pull/416) introduces an `AttributedMetadata` type that wraps
|
||||
`Logger.Metadata` with additional context. Adding it to `LogEvent` as a new optional field would be
|
||||
source-compatible, and the existing `metadata` field could become a computed property that projects from
|
||||
`attributedMetadata` when present, keeping old handlers fully functional without modification.
|
||||
|
||||
### Alternatives considered
|
||||
|
||||
#### Adding parameters with default values to the existing method
|
||||
|
||||
Adding new parameters with default values avoids introducing a new method, but still constitutes a
|
||||
source-breaking change: every existing `LogHandler` implementation that implements the method explicitly
|
||||
must add the new parameter. The whole point of this proposal is to avoid that pattern indefinitely.
|
||||
@@ -92,6 +92,7 @@ backend.
|
||||
|
||||
- <doc:LoggingBestPractices>
|
||||
- <doc:ImplementingALogHandler>
|
||||
- <doc:DisableLogLevelsDuringCompilation>
|
||||
|
||||
### Contributing
|
||||
|
||||
|
||||
+80
-58
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// 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
|
||||
// Copyright (c) 2018-2026 Apple Inc. and the Swift Logging API project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
@@ -16,7 +16,7 @@
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
|
||||
// Copyright (c) 2017-2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
@@ -26,20 +26,26 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
#if canImport(WASILibc)
|
||||
// No locking on WASILibc
|
||||
#elseif canImport(Darwin)
|
||||
#if canImport(Darwin)
|
||||
import Darwin
|
||||
#elseif os(Windows)
|
||||
import ucrt
|
||||
import WinSDK
|
||||
#elseif canImport(Glibc)
|
||||
import Glibc
|
||||
@preconcurrency import Glibc
|
||||
#elseif canImport(Android)
|
||||
import Android
|
||||
@preconcurrency import Android
|
||||
#elseif canImport(Musl)
|
||||
import Musl
|
||||
@preconcurrency import Musl
|
||||
#elseif canImport(Bionic)
|
||||
@preconcurrency import Bionic
|
||||
#elseif canImport(WASILibc)
|
||||
@preconcurrency import WASILibc
|
||||
#if canImport(wasi_pthread)
|
||||
import wasi_pthread
|
||||
#endif
|
||||
#else
|
||||
#error("Unsupported runtime")
|
||||
#error("The concurrency lock module was unable to identify your C library.")
|
||||
#endif
|
||||
|
||||
/// A threading lock based on `libpthread` instead of `libdispatch`.
|
||||
@@ -48,43 +54,56 @@ import Musl
|
||||
/// of lock is safe to use with `libpthread`-based threading models, such as the
|
||||
/// one used by NIO. On Windows, the lock is based on the substantially similar
|
||||
/// `SRWLOCK` type.
|
||||
package final class Lock: @unchecked Sendable {
|
||||
#if canImport(WASILibc)
|
||||
// WASILibc is single threaded, provides no locks
|
||||
#elseif os(Windows)
|
||||
package final class Lock {
|
||||
#if os(Windows)
|
||||
fileprivate let mutex: UnsafeMutablePointer<SRWLOCK> =
|
||||
UnsafeMutablePointer.allocate(capacity: 1)
|
||||
#else
|
||||
#elseif os(FreeBSD) || os(OpenBSD)
|
||||
fileprivate let mutex: UnsafeMutablePointer<pthread_mutex_t?> =
|
||||
UnsafeMutablePointer.allocate(capacity: 1)
|
||||
#elseif (compiler(<6.1) && !os(WASI)) || (compiler(>=6.1) && _runtime(_multithreaded))
|
||||
fileprivate let mutex: UnsafeMutablePointer<pthread_mutex_t> =
|
||||
UnsafeMutablePointer.allocate(capacity: 1)
|
||||
#endif
|
||||
|
||||
/// Create a new lock.
|
||||
package init() {
|
||||
#if canImport(WASILibc)
|
||||
// WASILibc is single threaded, provides no locks
|
||||
#elseif os(Windows)
|
||||
#if os(Windows)
|
||||
InitializeSRWLock(self.mutex)
|
||||
#elseif (compiler(<6.1) && !os(WASI)) || (compiler(>=6.1) && _runtime(_multithreaded))
|
||||
#if os(FreeBSD) || os(OpenBSD)
|
||||
var attr = pthread_mutexattr_t(bitPattern: 0)
|
||||
#else
|
||||
var attr = pthread_mutexattr_t()
|
||||
pthread_mutexattr_init(&attr)
|
||||
pthread_mutexattr_settype(&attr, .init(PTHREAD_MUTEX_ERRORCHECK))
|
||||
#endif
|
||||
var err = pthread_mutexattr_init(&attr)
|
||||
precondition(err == 0, "\(#function) failed in pthread_mutexattr_init with error \(err)")
|
||||
debugOnly {
|
||||
#if os(FreeBSD) || os(OpenBSD)
|
||||
pthread_mutexattr_settype(&attr, .init(PTHREAD_MUTEX_ERRORCHECK.rawValue))
|
||||
#else
|
||||
pthread_mutexattr_settype(&attr, .init(PTHREAD_MUTEX_ERRORCHECK))
|
||||
#endif
|
||||
}
|
||||
|
||||
let err = pthread_mutex_init(self.mutex, &attr)
|
||||
err = pthread_mutex_init(self.mutex, &attr)
|
||||
precondition(err == 0, "\(#function) failed in pthread_mutex with error \(err)")
|
||||
// `pthread_mutexattr_t` only lives during init; destroy here instead of deinit.
|
||||
let attrDestroyErr = pthread_mutexattr_destroy(&attr)
|
||||
precondition(
|
||||
attrDestroyErr == 0,
|
||||
"\(#function) failed in pthread_mutexattr_destroy with error \(attrDestroyErr)"
|
||||
)
|
||||
#endif
|
||||
}
|
||||
|
||||
deinit {
|
||||
#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
|
||||
#if os(Windows)
|
||||
mutex.deallocate()
|
||||
#elseif (compiler(<6.1) && !os(WASI)) || (compiler(>=6.1) && _runtime(_multithreaded))
|
||||
let err = pthread_mutex_destroy(self.mutex)
|
||||
precondition(err == 0, "\(#function) failed in pthread_mutex with error \(err)")
|
||||
self.mutex.deallocate()
|
||||
mutex.deallocate()
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -93,11 +112,9 @@ package final class Lock: @unchecked Sendable {
|
||||
/// Whenever possible, consider using `withLock` instead of this method and
|
||||
/// `unlock`, to simplify lock handling.
|
||||
package func lock() {
|
||||
#if canImport(WASILibc)
|
||||
// WASILibc is single threaded, provides no locks
|
||||
#elseif os(Windows)
|
||||
#if os(Windows)
|
||||
AcquireSRWLockExclusive(self.mutex)
|
||||
#else
|
||||
#elseif (compiler(<6.1) && !os(WASI)) || (compiler(>=6.1) && _runtime(_multithreaded))
|
||||
let err = pthread_mutex_lock(self.mutex)
|
||||
precondition(err == 0, "\(#function) failed in pthread_mutex with error \(err)")
|
||||
#endif
|
||||
@@ -108,18 +125,14 @@ package final class Lock: @unchecked Sendable {
|
||||
/// Whenever possible, consider using `withLock` instead of this method and
|
||||
/// `lock`, to simplify lock handling.
|
||||
package func unlock() {
|
||||
#if canImport(WASILibc)
|
||||
// WASILibc is single threaded, provides no locks
|
||||
#elseif os(Windows)
|
||||
#if os(Windows)
|
||||
ReleaseSRWLockExclusive(self.mutex)
|
||||
#else
|
||||
#elseif (compiler(<6.1) && !os(WASI)) || (compiler(>=6.1) && _runtime(_multithreaded))
|
||||
let err = pthread_mutex_unlock(self.mutex)
|
||||
precondition(err == 0, "\(#function) failed in pthread_mutex with error \(err)")
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
extension Lock {
|
||||
/// Acquire the lock for the duration of the given block.
|
||||
///
|
||||
/// This convenience method should be preferred to `lock` and `unlock` in
|
||||
@@ -144,6 +157,23 @@ extension Lock {
|
||||
}
|
||||
}
|
||||
|
||||
/// A utility function that runs the body code only in debug builds, without
|
||||
/// emitting compiler warnings.
|
||||
///
|
||||
/// This is currently the only way to do this in Swift: see
|
||||
/// https://forums.swift.org/t/support-debug-only-code/11037 for a discussion.
|
||||
@inlinable
|
||||
internal func debugOnly(_ body: () -> Void) {
|
||||
assert(
|
||||
{
|
||||
body()
|
||||
return true
|
||||
}()
|
||||
)
|
||||
}
|
||||
|
||||
extension Lock: @unchecked Sendable {}
|
||||
|
||||
/// A reader/writer threading lock based on `libpthread` instead of `libdispatch`.
|
||||
///
|
||||
/// This object provides a lock on top of a single `pthread_rwlock_t`. This kind
|
||||
@@ -157,6 +187,9 @@ internal final class ReadWriteLock: @unchecked Sendable {
|
||||
fileprivate let rwlock: UnsafeMutablePointer<SRWLOCK> =
|
||||
UnsafeMutablePointer.allocate(capacity: 1)
|
||||
fileprivate var shared: Bool = true
|
||||
#elseif os(FreeBSD) || os(OpenBSD)
|
||||
fileprivate let rwlock: UnsafeMutablePointer<pthread_rwlock_t?> =
|
||||
UnsafeMutablePointer.allocate(capacity: 1)
|
||||
#else
|
||||
fileprivate let rwlock: UnsafeMutablePointer<pthread_rwlock_t> =
|
||||
UnsafeMutablePointer.allocate(capacity: 1)
|
||||
@@ -164,23 +197,18 @@ internal final class ReadWriteLock: @unchecked Sendable {
|
||||
|
||||
/// Create a new lock.
|
||||
public init() {
|
||||
#if canImport(WASILibc)
|
||||
// WASILibc is single threaded, provides no locks
|
||||
#elseif os(Windows)
|
||||
#if os(Windows)
|
||||
InitializeSRWLock(self.rwlock)
|
||||
#else
|
||||
#elseif (compiler(<6.1) && !os(WASI)) || (compiler(>=6.1) && _runtime(_multithreaded))
|
||||
let err = pthread_rwlock_init(self.rwlock, nil)
|
||||
precondition(err == 0, "\(#function) failed in pthread_rwlock with error \(err)")
|
||||
#endif
|
||||
}
|
||||
|
||||
deinit {
|
||||
#if canImport(WASILibc)
|
||||
// WASILibc is single threaded, provides no locks
|
||||
#elseif os(Windows)
|
||||
// SRWLOCK does not need to be free'd
|
||||
#if os(Windows)
|
||||
self.rwlock.deallocate()
|
||||
#else
|
||||
#elseif (compiler(<6.1) && !os(WASI)) || (compiler(>=6.1) && _runtime(_multithreaded))
|
||||
let err = pthread_rwlock_destroy(self.rwlock)
|
||||
precondition(err == 0, "\(#function) failed in pthread_rwlock with error \(err)")
|
||||
self.rwlock.deallocate()
|
||||
@@ -192,12 +220,10 @@ internal final class ReadWriteLock: @unchecked Sendable {
|
||||
/// Whenever possible, consider using `withReaderLock` instead of this
|
||||
/// method and `unlock`, to simplify lock handling.
|
||||
fileprivate func lockRead() {
|
||||
#if canImport(WASILibc)
|
||||
// WASILibc is single threaded, provides no locks
|
||||
#elseif os(Windows)
|
||||
#if os(Windows)
|
||||
AcquireSRWLockShared(self.rwlock)
|
||||
self.shared = true
|
||||
#else
|
||||
#elseif (compiler(<6.1) && !os(WASI)) || (compiler(>=6.1) && _runtime(_multithreaded))
|
||||
let err = pthread_rwlock_rdlock(self.rwlock)
|
||||
precondition(err == 0, "\(#function) failed in pthread_rwlock with error \(err)")
|
||||
#endif
|
||||
@@ -208,12 +234,10 @@ internal final class ReadWriteLock: @unchecked Sendable {
|
||||
/// Whenever possible, consider using `withWriterLock` instead of this
|
||||
/// method and `unlock`, to simplify lock handling.
|
||||
fileprivate func lockWrite() {
|
||||
#if canImport(WASILibc)
|
||||
// WASILibc is single threaded, provides no locks
|
||||
#elseif os(Windows)
|
||||
#if os(Windows)
|
||||
AcquireSRWLockExclusive(self.rwlock)
|
||||
self.shared = false
|
||||
#else
|
||||
#elseif (compiler(<6.1) && !os(WASI)) || (compiler(>=6.1) && _runtime(_multithreaded))
|
||||
let err = pthread_rwlock_wrlock(self.rwlock)
|
||||
precondition(err == 0, "\(#function) failed in pthread_rwlock with error \(err)")
|
||||
#endif
|
||||
@@ -225,15 +249,13 @@ internal final class ReadWriteLock: @unchecked Sendable {
|
||||
/// instead of this method and `lockRead` and `lockWrite`, to simplify lock
|
||||
/// handling.
|
||||
fileprivate func unlock() {
|
||||
#if canImport(WASILibc)
|
||||
// WASILibc is single threaded, provides no locks
|
||||
#elseif os(Windows)
|
||||
#if os(Windows)
|
||||
if self.shared {
|
||||
ReleaseSRWLockShared(self.rwlock)
|
||||
} else {
|
||||
ReleaseSRWLockExclusive(self.rwlock)
|
||||
}
|
||||
#else
|
||||
#elseif (compiler(<6.1) && !os(WASI)) || (compiler(>=6.1) && _runtime(_multithreaded))
|
||||
let err = pthread_rwlock_unlock(self.rwlock)
|
||||
precondition(err == 0, "\(#function) failed in pthread_rwlock with error \(err)")
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A log event that contains all the information about a single log statement.
|
||||
///
|
||||
/// `LogEvent` is passed to a ``LogHandler`` via ``LogHandler/log(event:)`` and carries every piece of data emitted
|
||||
/// at the log call site. Handlers may inspect, modify, or forward any of the event's properties.
|
||||
///
|
||||
/// All properties are mutable so that handler wrappers (for example ``MultiplexLogHandler``) can rewrite fields
|
||||
/// such as metadata or source before forwarding to downstream handlers.
|
||||
public struct LogEvent: Sendable {
|
||||
/// The log level of this event.
|
||||
public var level: Logger.Level
|
||||
|
||||
/// The message of this event.
|
||||
public var message: Logger.Message
|
||||
|
||||
/// The error associated with this event, if any.
|
||||
public var error: (any Error)?
|
||||
|
||||
/// The metadata associated with this event, if any.
|
||||
public var metadata: Logger.Metadata? {
|
||||
get { self._metadata }
|
||||
set { self._metadata = newValue }
|
||||
}
|
||||
|
||||
private var _metadata: Logger.Metadata?
|
||||
|
||||
/// The source where this log event originated, for example the logging module.
|
||||
///
|
||||
/// When no explicit source was provided at the call site, this is derived lazily from ``file``
|
||||
/// every time this property is accessed. Handlers that never read this property pay no
|
||||
/// allocation cost for source computation.
|
||||
public var source: String {
|
||||
@inlinable get { self._source ?? Logger.currentModule(fileID: self.file) }
|
||||
@inlinable set { self._source = newValue }
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal var _source: String?
|
||||
|
||||
/// The file this log event originates from.
|
||||
public var file: String
|
||||
|
||||
/// The function this log event originates from.
|
||||
public var function: String
|
||||
|
||||
/// The line this log event originates from.
|
||||
public var line: UInt
|
||||
|
||||
/// Creates a new log event.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - level: The log level of this event.
|
||||
/// - message: The message of this event.
|
||||
/// - metadata: The metadata associated with this event, if any.
|
||||
/// - source: The source where this log event originated. When `nil`, ``source`` is derived lazily
|
||||
/// from ``file`` on first access so handlers that never read it pay no allocation cost.
|
||||
/// - file: The file this log event originates from.
|
||||
/// - function: The function this log event originates from.
|
||||
/// - line: The line this log event originates from.
|
||||
public init(
|
||||
level: Logger.Level,
|
||||
message: Logger.Message,
|
||||
metadata: Logger.Metadata?,
|
||||
source: String?,
|
||||
file: String,
|
||||
function: String,
|
||||
line: UInt
|
||||
) {
|
||||
self.init(
|
||||
level: level,
|
||||
message: message,
|
||||
error: nil,
|
||||
metadata: metadata,
|
||||
source: source,
|
||||
file: file,
|
||||
function: function,
|
||||
line: line
|
||||
)
|
||||
}
|
||||
|
||||
/// Creates a new log event.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - level: The log level of this event.
|
||||
/// - message: The message of this event.
|
||||
/// - error: The error associated with this event, if any.
|
||||
/// - metadata: The metadata associated with this event, if any.
|
||||
/// - source: The source where this log event originated. When `nil`, ``source`` is derived lazily
|
||||
/// from ``file`` on first access so handlers that never read it pay no allocation cost.
|
||||
/// - file: The file this log event originates from.
|
||||
/// - function: The function this log event originates from.
|
||||
/// - line: The line this log event originates from.
|
||||
public init(
|
||||
level: Logger.Level,
|
||||
message: Logger.Message,
|
||||
error: (any Error)?,
|
||||
metadata: Logger.Metadata?,
|
||||
source: String?,
|
||||
file: String,
|
||||
function: String,
|
||||
line: UInt
|
||||
) {
|
||||
self.level = level
|
||||
self.message = message
|
||||
self.error = error
|
||||
self._metadata = metadata
|
||||
self._source = source
|
||||
self.file = file
|
||||
self.function = function
|
||||
self.line = line
|
||||
}
|
||||
}
|
||||
@@ -138,9 +138,14 @@ public protocol LogHandler: _SwiftLogSendableLogHandler {
|
||||
|
||||
/// The library calls this method when a log handler 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.
|
||||
/// 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.
|
||||
///
|
||||
/// - Parameter event: The log event containing the level, message, metadata, and source location.
|
||||
func log(event: LogEvent)
|
||||
|
||||
/// Please do _not_ implement this method when you create a `LogHandler` implementation.
|
||||
/// Implement ``log(event:)`` instead.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - level: The log level of the message.
|
||||
@@ -150,6 +155,7 @@ public protocol LogHandler: _SwiftLogSendableLogHandler {
|
||||
/// - file: The file this log message originates from.
|
||||
/// - function: The function this log message originates from.
|
||||
/// - line: The line this log message originates from.
|
||||
@available(*, deprecated, renamed: "log(event:)")
|
||||
func log(
|
||||
level: Logger.Level,
|
||||
message: Logger.Message,
|
||||
@@ -163,7 +169,7 @@ public protocol LogHandler: _SwiftLogSendableLogHandler {
|
||||
/// SwiftLog 1.0 log compatibility method.
|
||||
///
|
||||
/// Please do _not_ implement this method when you create a LogHandler implementation.
|
||||
/// Implement `log(level:message:metadata:source:file:function:line:)` instead.
|
||||
/// Implement ``log(event:)`` instead.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - level: The log level of the message.
|
||||
@@ -172,7 +178,7 @@ public protocol LogHandler: _SwiftLogSendableLogHandler {
|
||||
/// - file: The file this log message originates from.
|
||||
/// - function: The function this log message originates from.
|
||||
/// - line: The line this log message originates from.
|
||||
@available(*, deprecated, renamed: "log(level:message:metadata:source:file:function:line:)")
|
||||
@available(*, deprecated, renamed: "log(event:)")
|
||||
func log(
|
||||
level: Logging.Logger.Level,
|
||||
message: Logging.Logger.Message,
|
||||
@@ -218,14 +224,16 @@ extension LogHandler {
|
||||
#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
|
||||
event: LogEvent(
|
||||
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
|
||||
@@ -234,16 +242,31 @@ extension LogHandler {
|
||||
}
|
||||
|
||||
extension LogHandler {
|
||||
/// A default implementation for a log message handler that forwards the source location for the message.
|
||||
/// - Parameters:
|
||||
/// - level: The log level of the message.
|
||||
/// - message: The message to log. To obtain a `String` representation call `message.description`.
|
||||
/// - 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.
|
||||
/// Default implementation of ``log(event:)`` for backward compatibility with handlers that implement the
|
||||
/// deprecated flat-parameter method.
|
||||
///
|
||||
/// Handlers that implement ``log(level:message:metadata:source:file:function:line:)`` continue to work
|
||||
/// without any source changes; this default forwards the event's fields to that method.
|
||||
///
|
||||
/// New handlers should implement ``log(event:)`` directly and rely on this default only as a fallback.
|
||||
///
|
||||
/// > Warning: Do not call this default directly. It exists only as a backward-compatibility bridge.
|
||||
/// Implement ``log(event:)`` in your ``LogHandler`` instead.
|
||||
@available(*, deprecated, message: "You should implement this method instead of using the default implementation")
|
||||
public func log(event: LogEvent) {
|
||||
self.log(
|
||||
level: event.level,
|
||||
message: event.message,
|
||||
metadata: event.metadata,
|
||||
source: event.source,
|
||||
file: event.file,
|
||||
function: event.function,
|
||||
line: event.line
|
||||
)
|
||||
}
|
||||
|
||||
/// A default implementation for a log message handler that forwards to the SwiftLog 1.0 compatibility method.
|
||||
@available(*, deprecated, renamed: "log(event:)")
|
||||
public func log(
|
||||
level: Logger.Level,
|
||||
message: Logger.Message,
|
||||
@@ -253,18 +276,18 @@ extension LogHandler {
|
||||
function: String,
|
||||
line: UInt
|
||||
) {
|
||||
self.log(level: level, message: message, metadata: metadata, file: file, function: function, line: line)
|
||||
self.log(
|
||||
level: level,
|
||||
message: message,
|
||||
metadata: metadata,
|
||||
file: file,
|
||||
function: function,
|
||||
line: line
|
||||
)
|
||||
}
|
||||
|
||||
/// A default implementation for a log message handler.
|
||||
/// - Parameters:
|
||||
/// - level: The log level of the message.
|
||||
/// - message: The message to log. To obtain a `String` representation call `message.description`.
|
||||
/// - metadata: The metadata associated to this log message.
|
||||
/// - file: The file this log message originates from.
|
||||
/// - function: The function this log message originates from.
|
||||
/// - line: The line this log message originates from.
|
||||
@available(*, deprecated, renamed: "log(level:message:metadata:source:file:function:line:)")
|
||||
/// A default implementation for the SwiftLog 1.0 log message handler.
|
||||
@available(*, deprecated, renamed: "log(event:)")
|
||||
public func log(
|
||||
level: Logging.Logger.Level,
|
||||
message: Logging.Logger.Message,
|
||||
|
||||
+698
-132
File diff suppressed because it is too large.
Load diff
@@ -69,6 +69,53 @@ struct InMemoryLogHandlerTests {
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
func errorEquality() throws {
|
||||
let (logHandler, logger) = self.makeTestLogger()
|
||||
logger.info("hello", error: TestError.first)
|
||||
let entry = try #require(logHandler.entries.first)
|
||||
|
||||
#expect(
|
||||
entry
|
||||
== InMemoryLogHandler.Entry(
|
||||
level: .info,
|
||||
message: "hello",
|
||||
error: TestError.first,
|
||||
metadata: [:],
|
||||
)
|
||||
)
|
||||
|
||||
#expect(
|
||||
entry
|
||||
!= InMemoryLogHandler.Entry(
|
||||
level: .info,
|
||||
message: "hello",
|
||||
error: nil,
|
||||
metadata: [:],
|
||||
)
|
||||
)
|
||||
|
||||
#expect(
|
||||
entry
|
||||
!= InMemoryLogHandler.Entry(
|
||||
level: .info,
|
||||
message: "hello",
|
||||
error: TestError.second,
|
||||
metadata: [:]
|
||||
)
|
||||
)
|
||||
|
||||
#expect(
|
||||
entry
|
||||
!= InMemoryLogHandler.Entry(
|
||||
level: .info,
|
||||
message: "hello",
|
||||
error: Nested.TestError.first,
|
||||
metadata: [:]
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
func clear() {
|
||||
let (logHandler, logger) = self.makeTestLogger()
|
||||
@@ -95,4 +142,15 @@ struct InMemoryLogHandlerTests {
|
||||
)
|
||||
return (logHandler, logger)
|
||||
}
|
||||
|
||||
enum TestError: Error {
|
||||
case first
|
||||
case second
|
||||
}
|
||||
|
||||
struct Nested {
|
||||
enum TestError: Error {
|
||||
case first
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -41,6 +41,31 @@ struct CompatibilityTest {
|
||||
testLogging.history.assertExist(level: .error, message: "yes: error", source: "no source")
|
||||
testLogging.history.assertExist(level: .critical, message: "yes: critical", source: "no source")
|
||||
}
|
||||
|
||||
@available(*, deprecated, message: "Testing deprecated functionality")
|
||||
@Test func allLogLevelsWorkWithNewerButStillOldLogHandlerWorks() {
|
||||
let testLogging = NewerButStillOldTestLogging()
|
||||
|
||||
var logger = Logger(label: "\(#function)", factory: { testLogging.make(label: $0) })
|
||||
logger.logLevel = .trace
|
||||
|
||||
logger.trace("yes: trace", source: "yes: trace source")
|
||||
logger.debug("yes: debug", source: "yes: debug source")
|
||||
logger.info("yes: info", source: "yes: info source")
|
||||
logger.notice("yes: notice", source: "yes: notice source")
|
||||
logger.warning("yes: warning", source: "yes: warning source")
|
||||
logger.error("yes: error", source: "yes: error source")
|
||||
logger.critical("yes: critical", source: "yes: critical source")
|
||||
|
||||
// Please note that the source is _not_ propagated (because the backend doesn't support it).
|
||||
testLogging.history.assertExist(level: .trace, message: "yes: trace", source: "yes: trace source")
|
||||
testLogging.history.assertExist(level: .debug, message: "yes: debug", source: "yes: debug source")
|
||||
testLogging.history.assertExist(level: .info, message: "yes: info", source: "yes: info source")
|
||||
testLogging.history.assertExist(level: .notice, message: "yes: notice", source: "yes: notice source")
|
||||
testLogging.history.assertExist(level: .warning, message: "yes: warning", source: "yes: warning source")
|
||||
testLogging.history.assertExist(level: .error, message: "yes: error", source: "yes: error source")
|
||||
testLogging.history.assertExist(level: .critical, message: "yes: critical", source: "yes: critical source")
|
||||
}
|
||||
}
|
||||
|
||||
private struct OldSchoolTestLogging {
|
||||
@@ -96,3 +121,58 @@ private struct OldSchoolLogHandler: LogHandler {
|
||||
|
||||
var logLevel: Logger.Level
|
||||
}
|
||||
|
||||
private struct NewerButStillOldTestLogging {
|
||||
private let _config = Config() // shared among loggers
|
||||
private let recorder = Recorder() // shared among loggers
|
||||
|
||||
@available(*, deprecated, message: "Testing deprecated functionality")
|
||||
func make(label: String) -> any LogHandler {
|
||||
NewerButStillOldLogHandler(
|
||||
label: label,
|
||||
config: self.config,
|
||||
recorder: self.recorder,
|
||||
metadata: [:],
|
||||
logLevel: .info
|
||||
)
|
||||
}
|
||||
|
||||
var config: Config { self._config }
|
||||
var history: some History { self.recorder }
|
||||
}
|
||||
|
||||
@available(*, deprecated, message: "Testing deprecated functionality")
|
||||
private struct NewerButStillOldLogHandler: LogHandler {
|
||||
var label: String
|
||||
let config: Config
|
||||
let recorder: Recorder
|
||||
|
||||
func make(label: String) -> some LogHandler {
|
||||
TestLogHandler(label: label, config: self.config, recorder: self.recorder)
|
||||
}
|
||||
|
||||
func log(
|
||||
level: Logger.Level,
|
||||
message: Logger.Message,
|
||||
metadata: Logger.Metadata?,
|
||||
source: String,
|
||||
file: String,
|
||||
function: String,
|
||||
line: UInt
|
||||
) {
|
||||
self.recorder.record(level: level, metadata: metadata, message: message, source: source)
|
||||
}
|
||||
|
||||
subscript(metadataKey metadataKey: String) -> Logger.Metadata.Value? {
|
||||
get {
|
||||
self.metadata[metadataKey]
|
||||
}
|
||||
set {
|
||||
self.metadata[metadataKey] = newValue
|
||||
}
|
||||
}
|
||||
|
||||
var metadata: Logger.Metadata
|
||||
|
||||
var logLevel: Logger.Level
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Logging API open source project
|
||||
//
|
||||
// Copyright (c) 2018-2026 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2017-2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Testing
|
||||
|
||||
@testable import Logging
|
||||
|
||||
#if canImport(Dispatch)
|
||||
import Dispatch
|
||||
private let canImportDispatch = true
|
||||
#else
|
||||
private let canImportDispatch = false
|
||||
#endif
|
||||
|
||||
@Suite("Lock Test Suite")
|
||||
struct LockTestSuite {
|
||||
@Test(.enabled(if: canImportDispatch)) func testLockMutualExclusion() {
|
||||
#if canImport(Dispatch)
|
||||
let l = Lock()
|
||||
|
||||
nonisolated(unsafe) var x = 1
|
||||
let q = DispatchQueue(label: "q")
|
||||
let g = DispatchGroup()
|
||||
let sem1 = DispatchSemaphore(value: 0)
|
||||
let sem2 = DispatchSemaphore(value: 0)
|
||||
|
||||
l.lock()
|
||||
|
||||
q.async(group: g) {
|
||||
sem1.signal()
|
||||
l.lock()
|
||||
x = 2
|
||||
l.unlock()
|
||||
sem2.signal()
|
||||
}
|
||||
|
||||
sem1.wait()
|
||||
#expect(DispatchTimeoutResult.timedOut == g.wait(timeout: .now() + 0.1))
|
||||
#expect(1 == x)
|
||||
|
||||
l.unlock()
|
||||
sem2.wait()
|
||||
|
||||
l.lock()
|
||||
#expect(2 == x)
|
||||
l.unlock()
|
||||
#endif // canImport(Dispatch)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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 LogEventTest {
|
||||
|
||||
// MARK: - Lazy source computation
|
||||
|
||||
@Test func sourceIsDerivedFromFileWhenNotProvided() {
|
||||
let event = LogEvent(
|
||||
level: .info,
|
||||
message: "hello",
|
||||
metadata: nil,
|
||||
source: nil,
|
||||
file: "MyModule/MyFile.swift",
|
||||
function: "f()",
|
||||
line: 1
|
||||
)
|
||||
#expect(event.source == "MyModule")
|
||||
}
|
||||
|
||||
@Test func sourceUsesExplicitValueWhenProvided() {
|
||||
let event = LogEvent(
|
||||
level: .info,
|
||||
message: "hello",
|
||||
metadata: nil,
|
||||
source: "ExplicitSource",
|
||||
file: "MyModule/MyFile.swift",
|
||||
function: "f()",
|
||||
line: 1
|
||||
)
|
||||
#expect(event.source == "ExplicitSource")
|
||||
}
|
||||
|
||||
@Test func sourceSetterOverridesLazyValue() {
|
||||
var event = LogEvent(
|
||||
level: .info,
|
||||
message: "hello",
|
||||
metadata: nil,
|
||||
source: nil,
|
||||
file: "MyModule/MyFile.swift",
|
||||
function: "f()",
|
||||
line: 1
|
||||
)
|
||||
#expect(event.source == "MyModule")
|
||||
|
||||
event.source = "OverriddenSource"
|
||||
#expect(event.source == "OverriddenSource")
|
||||
}
|
||||
|
||||
@Test func sourceLazyDerivationDoesNotStoreComputedValue() {
|
||||
let event = LogEvent(
|
||||
level: .info,
|
||||
message: "hello",
|
||||
metadata: nil,
|
||||
source: nil,
|
||||
file: "MyModule/MyFile.swift",
|
||||
function: "f()",
|
||||
line: 1
|
||||
)
|
||||
// Internal _source should be nil when no explicit source was provided.
|
||||
#expect(event._source == nil)
|
||||
// Accessing source derives it from file but does not mutate _source (it's a computed get).
|
||||
_ = event.source
|
||||
#expect(event._source == nil)
|
||||
}
|
||||
|
||||
@Test func metadataSetterStoresThroughComputedProperty() {
|
||||
var event = LogEvent(
|
||||
level: .info,
|
||||
message: "hello",
|
||||
metadata: nil,
|
||||
source: nil,
|
||||
file: "M/F.swift",
|
||||
function: "f()",
|
||||
line: 1
|
||||
)
|
||||
#expect(event.metadata == nil)
|
||||
|
||||
event.metadata = ["key": "value"]
|
||||
#expect(event.metadata?["key"] == "value")
|
||||
|
||||
event.metadata = nil
|
||||
#expect(event.metadata == nil)
|
||||
}
|
||||
|
||||
@Test func loggerDerivedSourceMatchesModuleName() {
|
||||
let recorder = Recorder()
|
||||
let handler = LogEventHandler(recorder: recorder)
|
||||
var logger = Logger(label: "test", handler)
|
||||
logger.logLevel = .trace
|
||||
|
||||
// Log without explicit source — source should be derived from #fileID.
|
||||
logger.info("derived source test")
|
||||
|
||||
let entries = recorder.entries
|
||||
#expect(entries.count == 1)
|
||||
#expect(entries[0].source == "LoggingTests")
|
||||
}
|
||||
|
||||
// MARK: - Default log(event:) forwarding to deprecated flat-parameter method
|
||||
|
||||
@available(*, deprecated, message: "Testing deprecated functionality")
|
||||
@Test func defaultLogEventForwardsAllFieldsIncludingSourceLocation() {
|
||||
let recorder = Recorder()
|
||||
let handler = FlatParametersHandler(recorder: recorder)
|
||||
var logger = Logger(label: "test", handler)
|
||||
logger.logLevel = .trace
|
||||
|
||||
logger.warning("location test")
|
||||
let line = UInt(#line - 1)
|
||||
|
||||
let entries = recorder.entries
|
||||
#expect(entries.count == 1)
|
||||
#expect(entries[0].level == .warning)
|
||||
#expect(entries[0].message == "location test")
|
||||
#expect(entries[0].file.hasSuffix("LogEventTest.swift"))
|
||||
#expect(entries[0].function.contains("defaultLogEventForwardsAllFieldsIncludingSourceLocation"))
|
||||
#expect(entries[0].line == line)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Test Helpers
|
||||
|
||||
/// A handler that implements `log(event:)` directly and records entries.
|
||||
private struct LogEventHandler: LogHandler {
|
||||
let recorder: Recorder
|
||||
var logLevel: Logger.Level = .trace
|
||||
var metadata: Logger.Metadata = [:]
|
||||
var metadataProvider: Logger.MetadataProvider?
|
||||
|
||||
func log(event: LogEvent) {
|
||||
self.recorder.record(level: event.level, metadata: event.metadata, message: event.message, source: event.source)
|
||||
}
|
||||
|
||||
subscript(metadataKey key: String) -> Logger.Metadata.Value? {
|
||||
get { self.metadata[key] }
|
||||
set { self.metadata[key] = newValue }
|
||||
}
|
||||
}
|
||||
|
||||
/// A handler that only implements the deprecated flat-parameter method, relying on the
|
||||
/// default `log(event:)` forwarding bridge.
|
||||
@available(*, deprecated, message: "Testing deprecated functionality")
|
||||
private struct FlatParametersHandler: LogHandler {
|
||||
let recorder: Recorder
|
||||
var logLevel: Logger.Level = .trace
|
||||
var metadata: Logger.Metadata = [:]
|
||||
var metadataProvider: Logger.MetadataProvider?
|
||||
|
||||
func log(
|
||||
level: Logger.Level,
|
||||
message: Logger.Message,
|
||||
metadata: Logger.Metadata?,
|
||||
source: String,
|
||||
file: String,
|
||||
function: String,
|
||||
line: UInt
|
||||
) {
|
||||
self.recorder.record(
|
||||
level: level,
|
||||
metadata: metadata,
|
||||
message: message,
|
||||
source: source,
|
||||
file: file,
|
||||
function: function,
|
||||
line: line
|
||||
)
|
||||
}
|
||||
|
||||
subscript(metadataKey key: String) -> Logger.Metadata.Value? {
|
||||
get { self.metadata[key] }
|
||||
set { self.metadata[key] = newValue }
|
||||
}
|
||||
}
|
||||
@@ -387,6 +387,7 @@ struct LoggingTest {
|
||||
|
||||
enum TestError: Error {
|
||||
case boom
|
||||
case withMessage(String)
|
||||
}
|
||||
|
||||
@Test func dictionaryMetadata() {
|
||||
@@ -443,13 +444,13 @@ struct LoggingTest {
|
||||
private var makeValue: (() -> String)?
|
||||
private var _value: String?
|
||||
|
||||
public init(_ makeValue: @escaping () -> String) {
|
||||
init(_ makeValue: @escaping () -> String) {
|
||||
self.makeValue = makeValue
|
||||
}
|
||||
|
||||
/// This allows caching a value in case it is accessed via an by name subscript,
|
||||
// rather than as part of rendering all metadata that a LoggingContext was carrying
|
||||
public var value: String {
|
||||
var value: String {
|
||||
if let f = self.makeValue {
|
||||
self._value = f()
|
||||
self.makeValue = nil
|
||||
@@ -459,7 +460,7 @@ struct LoggingTest {
|
||||
return self._value!
|
||||
}
|
||||
|
||||
public var description: String {
|
||||
var description: String {
|
||||
"\(self.value)"
|
||||
}
|
||||
}
|
||||
@@ -515,6 +516,7 @@ struct LoggingTest {
|
||||
logger.debug(self.dontEvaluateThisString())
|
||||
logger.info(self.dontEvaluateThisString())
|
||||
logger.warning(self.dontEvaluateThisString())
|
||||
logger.warning(self.dontEvaluateThisString(), error: TestError.withMessage("\(self.dontEvaluateThisString())"))
|
||||
logger.log(level: .warning, self.dontEvaluateThisString())
|
||||
}
|
||||
|
||||
@@ -543,15 +545,7 @@ struct LoggingTest {
|
||||
|
||||
@Test func customFactory() {
|
||||
struct CustomHandler: LogHandler {
|
||||
func log(
|
||||
level: Logger.Level,
|
||||
message: Logger.Message,
|
||||
metadata: Logger.Metadata?,
|
||||
source: String,
|
||||
file: String,
|
||||
function: String,
|
||||
line: UInt
|
||||
) {}
|
||||
func log(event: LogEvent) {}
|
||||
|
||||
subscript(metadataKey _: String) -> Logger.Metadata.Value? {
|
||||
get { nil }
|
||||
@@ -575,6 +569,19 @@ struct LoggingTest {
|
||||
#expect(logger2.handler is CustomHandler, "expected custom log handler")
|
||||
}
|
||||
|
||||
@Test func errorParameter() {
|
||||
let testLogging = TestLogging()
|
||||
|
||||
let logger = Logger(
|
||||
label: "\(#function)",
|
||||
factory: {
|
||||
testLogging.make(label: $0)
|
||||
}
|
||||
)
|
||||
logger.log(level: .info, "hello world!", error: TestError.boom)
|
||||
testLogging.history.assertExist(level: .info, message: "hello world!", error: TestError.boom)
|
||||
}
|
||||
|
||||
@Test func allLogLevelsExceptCriticalCanBeBlocked() {
|
||||
let testLogging = TestLogging()
|
||||
|
||||
@@ -631,7 +638,48 @@ struct LoggingTest {
|
||||
testLogging.history.assertExist(level: .critical, message: "yes: critical")
|
||||
}
|
||||
|
||||
@Test func allLogLevelByFunctionRefWithSource() {
|
||||
@Test func allLogLevelByFunctionRefWithSourceAndError() {
|
||||
let testLogging = TestLogging()
|
||||
|
||||
var logger = Logger(
|
||||
label: "\(#function)",
|
||||
factory: {
|
||||
testLogging.make(label: $0)
|
||||
}
|
||||
)
|
||||
logger.logLevel = .trace
|
||||
|
||||
let trace = logger.trace(_:error:metadata:source:file:function:line:)
|
||||
let debug = logger.debug(_:error:metadata:source:file:function:line:)
|
||||
let info = logger.info(_:error:metadata:source:file:function:line:)
|
||||
let notice = logger.notice(_:error:metadata:source:file:function:line:)
|
||||
let warning = logger.warning(_:error:metadata:source:file:function:line:)
|
||||
let error = logger.error(_:error:metadata:source:file:function:line:)
|
||||
let critical = logger.critical(_:error:metadata:source:file:function:line:)
|
||||
|
||||
trace("yes: trace", TestError.boom, [:], "foo", #file, #function, #line)
|
||||
debug("yes: debug", TestError.boom, [:], "foo", #file, #function, #line)
|
||||
info("yes: info", TestError.boom, [:], "foo", #file, #function, #line)
|
||||
notice("yes: notice", TestError.boom, [:], "foo", #file, #function, #line)
|
||||
warning("yes: warning", TestError.boom, [:], "foo", #file, #function, #line)
|
||||
error("yes: error", TestError.boom, [:], "foo", #file, #function, #line)
|
||||
critical("yes: critical", TestError.boom, [:], "foo", #file, #function, #line)
|
||||
|
||||
testLogging.history.assertExist(level: .trace, message: "yes: trace", error: TestError.boom, source: "foo")
|
||||
testLogging.history.assertExist(level: .debug, message: "yes: debug", error: TestError.boom, source: "foo")
|
||||
testLogging.history.assertExist(level: .info, message: "yes: info", error: TestError.boom, source: "foo")
|
||||
testLogging.history.assertExist(level: .notice, message: "yes: notice", error: TestError.boom, source: "foo")
|
||||
testLogging.history.assertExist(level: .warning, message: "yes: warning", error: TestError.boom, source: "foo")
|
||||
testLogging.history.assertExist(level: .error, message: "yes: error", error: TestError.boom, source: "foo")
|
||||
testLogging.history.assertExist(
|
||||
level: .critical,
|
||||
message: "yes: critical",
|
||||
error: TestError.boom,
|
||||
source: "foo"
|
||||
)
|
||||
}
|
||||
|
||||
@Test func allLogLevelByFunctionRefWithSourceWithoutError() {
|
||||
let testLogging = TestLogging()
|
||||
|
||||
var logger = Logger(
|
||||
@@ -667,7 +715,7 @@ struct LoggingTest {
|
||||
testLogging.history.assertExist(level: .critical, message: "yes: critical", source: "foo")
|
||||
}
|
||||
|
||||
@Test func allLogLevelByFunctionRefWithoutSource() {
|
||||
@Test func allLogLevelByFunctionRefWithoutSourceOrError() {
|
||||
let testLogging = TestLogging()
|
||||
|
||||
var logger = Logger(
|
||||
@@ -869,16 +917,13 @@ struct LoggingTest {
|
||||
}
|
||||
}
|
||||
|
||||
func log(
|
||||
level: Logger.Level,
|
||||
message: Logger.Message,
|
||||
metadata: Logger.Metadata?,
|
||||
source: String,
|
||||
file: String,
|
||||
function: String,
|
||||
line: UInt
|
||||
) {
|
||||
self.recorder.record(level: level, metadata: metadata, message: message, source: source)
|
||||
func log(event: LogEvent) {
|
||||
self.recorder.record(
|
||||
level: event.level,
|
||||
metadata: event.metadata,
|
||||
message: event.message,
|
||||
source: event.source
|
||||
)
|
||||
}
|
||||
|
||||
subscript(metadataKey metadataKey: String) -> Logger.Metadata.Value? {
|
||||
@@ -957,6 +1002,11 @@ struct LoggingTest {
|
||||
#expect(Logger.Level.error < Logger.Level.critical)
|
||||
}
|
||||
|
||||
@Test(arguments: Logger.Level.allCases) func logLevelDescription(level: Logger.Level) {
|
||||
#expect(level.description == level.rawValue)
|
||||
#expect(Logger.Level(level.rawValue.uppercased()) == level)
|
||||
}
|
||||
|
||||
final class InterceptStream: TextOutputStream {
|
||||
var interceptedText: String?
|
||||
var strings = [String]()
|
||||
@@ -1112,8 +1162,7 @@ struct LoggingTest {
|
||||
}
|
||||
|
||||
@Test func stdioOutputStreamWrite() {
|
||||
self.withWriteReadFDsAndReadBuffer { writeFD, readFD, readBuffer in
|
||||
let logStream = StdioOutputStream(file: writeFD, flushMode: .always)
|
||||
self.withWriteReadFDsAndReadBuffer(flushMode: .always) { logStream, readFD, readBuffer in
|
||||
let log = Logger(
|
||||
label: "test",
|
||||
factory: {
|
||||
@@ -1140,8 +1189,7 @@ struct LoggingTest {
|
||||
|
||||
@Test func stdioOutputStreamFlush() {
|
||||
// flush on every statement
|
||||
self.withWriteReadFDsAndReadBuffer { writeFD, readFD, readBuffer in
|
||||
let logStream = StdioOutputStream(file: writeFD, flushMode: .always)
|
||||
self.withWriteReadFDsAndReadBuffer(flushMode: .always) { logStream, readFD, readBuffer in
|
||||
Logger(
|
||||
label: "test",
|
||||
factory: {
|
||||
@@ -1166,8 +1214,7 @@ struct LoggingTest {
|
||||
#expect(size2 == -1, "expected no flush")
|
||||
}
|
||||
// default flushing
|
||||
self.withWriteReadFDsAndReadBuffer { writeFD, readFD, readBuffer in
|
||||
let logStream = StdioOutputStream(file: writeFD, flushMode: .undefined)
|
||||
self.withWriteReadFDsAndReadBuffer(flushMode: .undefined) { logStream, readFD, readBuffer in
|
||||
Logger(
|
||||
label: "test",
|
||||
factory: {
|
||||
@@ -1193,7 +1240,10 @@ struct LoggingTest {
|
||||
}
|
||||
}
|
||||
|
||||
func withWriteReadFDsAndReadBuffer(_ body: (CFilePointer, CInt, UnsafeMutablePointer<Int8>) -> Void) {
|
||||
func withWriteReadFDsAndReadBuffer(
|
||||
flushMode: StdioOutputStream.FlushMode,
|
||||
_ body: (StdioOutputStream, CInt, UnsafeMutablePointer<Int8>) -> Void
|
||||
) {
|
||||
var fds: [Int32] = [-1, -1]
|
||||
#if os(Windows)
|
||||
fds.withUnsafeMutableBufferPointer {
|
||||
@@ -1224,6 +1274,29 @@ struct LoggingTest {
|
||||
var err = setvbuf(writeFD, writeBuffer, _IOFBF, 256)
|
||||
#expect(err == 0, "setvbuf failed \(err)")
|
||||
|
||||
// Create the stream here while writeFD's concrete type is in scope.
|
||||
// Type inference in the generic StdioOutputStream init picks the right
|
||||
// C functions for whatever FILE representation this platform/API level uses.
|
||||
#if os(Windows)
|
||||
let stream = StdioOutputStream(
|
||||
file: writeFD,
|
||||
flushMode: flushMode,
|
||||
lock: _lock_file,
|
||||
unlock: _unlock_file,
|
||||
write: fwrite,
|
||||
flush: fflush
|
||||
)
|
||||
#else
|
||||
let stream = StdioOutputStream(
|
||||
file: writeFD,
|
||||
flushMode: flushMode,
|
||||
lock: flockfile,
|
||||
unlock: funlockfile,
|
||||
write: fwrite,
|
||||
flush: fflush
|
||||
)
|
||||
#endif
|
||||
|
||||
let readFD = fds[0]
|
||||
#if os(Windows)
|
||||
let hPipe: HANDLE = HANDLE(bitPattern: _get_osfhandle(readFD))!
|
||||
@@ -1244,7 +1317,7 @@ struct LoggingTest {
|
||||
}
|
||||
|
||||
// the actual test
|
||||
body(writeFD, readFD, readBuffer)
|
||||
body(stream, readFD, readBuffer)
|
||||
|
||||
for fd in fds {
|
||||
#if os(Windows)
|
||||
@@ -1287,7 +1360,7 @@ struct LoggingTest {
|
||||
LoggingSystem.bootstrap { (label: String) in StreamLogHandler.standardOutput(label: label) }
|
||||
LoggingSystem.bootstrap { (label: String) in StreamLogHandler.standardError(label: label) }
|
||||
|
||||
// with metadata handler, explicitly, public api
|
||||
// with metadata handler, explicitly, api
|
||||
LoggingSystem.bootstrap(
|
||||
{ label, metadataProvider in
|
||||
StreamLogHandler.standardOutput(label: label, metadataProvider: metadataProvider)
|
||||
@@ -1332,7 +1405,7 @@ struct LoggingTest {
|
||||
}
|
||||
|
||||
extension Logger {
|
||||
public func error(
|
||||
func error(
|
||||
error: any Error,
|
||||
metadata: @autoclosure () -> Logger.Metadata? = nil,
|
||||
file: String = #fileID,
|
||||
|
||||
@@ -74,13 +74,13 @@ extension Logger.MetadataProvider {
|
||||
}
|
||||
}
|
||||
|
||||
public struct LogHandlerThatDidNotImplementMetadataProviders: LogHandler {
|
||||
struct LogHandlerThatDidNotImplementMetadataProviders: LogHandler {
|
||||
let testLogging: TestLogging
|
||||
init(testLogging: TestLogging) {
|
||||
self.testLogging = testLogging
|
||||
}
|
||||
|
||||
public subscript(metadataKey _: String) -> Logging.Logger.Metadata.Value? {
|
||||
subscript(metadataKey _: String) -> Logging.Logger.Metadata.Value? {
|
||||
get {
|
||||
nil
|
||||
}
|
||||
@@ -89,38 +89,22 @@ public struct LogHandlerThatDidNotImplementMetadataProviders: LogHandler {
|
||||
}
|
||||
}
|
||||
|
||||
public var metadata: Logging.Logger.Metadata = [:]
|
||||
var metadata: Logging.Logger.Metadata = [:]
|
||||
|
||||
public var logLevel: Logging.Logger.Level = .trace
|
||||
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
|
||||
)
|
||||
func log(event: LogEvent) {
|
||||
self.testLogging.make(label: "fake").log(event: event)
|
||||
}
|
||||
}
|
||||
|
||||
public struct LogHandlerThatDidImplementMetadataProviders: LogHandler {
|
||||
struct LogHandlerThatDidImplementMetadataProviders: LogHandler {
|
||||
let testLogging: TestLogging
|
||||
init(testLogging: TestLogging) {
|
||||
self.testLogging = testLogging
|
||||
}
|
||||
|
||||
public subscript(metadataKey _: String) -> Logging.Logger.Metadata.Value? {
|
||||
subscript(metadataKey _: String) -> Logging.Logger.Metadata.Value? {
|
||||
get {
|
||||
nil
|
||||
}
|
||||
@@ -129,29 +113,13 @@ public struct LogHandlerThatDidImplementMetadataProviders: LogHandler {
|
||||
}
|
||||
}
|
||||
|
||||
public var metadata: Logging.Logger.Metadata = [:]
|
||||
var metadata: Logging.Logger.Metadata = [:]
|
||||
|
||||
public var logLevel: Logging.Logger.Level = .trace
|
||||
var logLevel: Logging.Logger.Level = .trace
|
||||
|
||||
public var metadataProvider: Logger.MetadataProvider?
|
||||
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
|
||||
)
|
||||
func log(event: LogEvent) {
|
||||
self.testLogging.make(label: "fake").log(event: event)
|
||||
}
|
||||
}
|
||||
@@ -54,7 +54,7 @@ internal struct TestLogHandler: LogHandler {
|
||||
private var logger: Logger // the actual logger
|
||||
|
||||
let label: String
|
||||
public var metadataProvider: Logger.MetadataProvider?
|
||||
var metadataProvider: Logger.MetadataProvider?
|
||||
|
||||
init(label: String, config: Config, recorder: Recorder, metadataProvider: Logger.MetadataProvider?) {
|
||||
self.label = label
|
||||
@@ -74,15 +74,7 @@ internal struct TestLogHandler: LogHandler {
|
||||
self.metadataProvider = LoggingSystem.metadataProvider
|
||||
}
|
||||
|
||||
func log(
|
||||
level: Logger.Level,
|
||||
message: Logger.Message,
|
||||
metadata explicitMetadata: Logger.Metadata?,
|
||||
source: String,
|
||||
file: String,
|
||||
function: String,
|
||||
line: UInt
|
||||
) {
|
||||
func log(event: LogEvent) {
|
||||
// baseline metadata, that was set on handler:
|
||||
var metadata = self._metadataSet ? self.metadata : MDC.global.metadata
|
||||
// contextual metadata, e.g. from task-locals:
|
||||
@@ -91,20 +83,27 @@ internal struct TestLogHandler: LogHandler {
|
||||
metadata.merge(contextualMetadata, uniquingKeysWith: { _, contextual in contextual })
|
||||
}
|
||||
// override using any explicit metadata passed for this log statement:
|
||||
if let explicitMetadata = explicitMetadata {
|
||||
if let explicitMetadata = event.metadata {
|
||||
metadata.merge(explicitMetadata, uniquingKeysWith: { _, explicit in explicit })
|
||||
}
|
||||
|
||||
self.logger.log(
|
||||
level: level,
|
||||
message,
|
||||
level: event.level,
|
||||
event.message,
|
||||
error: event.error,
|
||||
metadata: metadata,
|
||||
source: source,
|
||||
file: file,
|
||||
function: function,
|
||||
line: line
|
||||
source: event.source,
|
||||
file: event.file,
|
||||
function: event.function,
|
||||
line: event.line
|
||||
)
|
||||
self.recorder.record(
|
||||
level: event.level,
|
||||
metadata: metadata,
|
||||
message: event.message,
|
||||
error: event.error,
|
||||
source: event.source
|
||||
)
|
||||
self.recorder.record(level: level, metadata: metadata, message: message, source: source)
|
||||
}
|
||||
|
||||
private var _logLevel: Logger.Level?
|
||||
@@ -125,7 +124,7 @@ internal struct TestLogHandler: LogHandler {
|
||||
}
|
||||
}
|
||||
|
||||
public var metadata: Logger.Metadata {
|
||||
var metadata: Logger.Metadata {
|
||||
get {
|
||||
self._metadata
|
||||
}
|
||||
@@ -175,10 +174,42 @@ internal class Recorder: History {
|
||||
private let lock = NSLock()
|
||||
private var _entries = [LogEntry]()
|
||||
|
||||
func record(level: Logger.Level, metadata: Logger.Metadata?, message: Logger.Message, source: String) {
|
||||
func record(
|
||||
level: Logger.Level,
|
||||
metadata: Logger.Metadata?,
|
||||
message: Logger.Message,
|
||||
error: (any Error)? = nil,
|
||||
source: String
|
||||
) {
|
||||
self.lock.withLock {
|
||||
self._entries.append(
|
||||
LogEntry(level: level, metadata: metadata, message: message.description, source: source)
|
||||
LogEntry(level: level, metadata: metadata, message: message.description, error: error, source: source)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func record(
|
||||
level: Logger.Level,
|
||||
metadata: Logger.Metadata?,
|
||||
message: Logger.Message,
|
||||
error: (any Error)? = nil,
|
||||
source: String,
|
||||
file: String,
|
||||
function: String,
|
||||
line: UInt
|
||||
) {
|
||||
self.lock.withLock {
|
||||
self._entries.append(
|
||||
LogEntry(
|
||||
level: level,
|
||||
metadata: metadata,
|
||||
message: message.description,
|
||||
error: error,
|
||||
source: source,
|
||||
file: file,
|
||||
function: function,
|
||||
line: line
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -224,13 +255,38 @@ internal struct LogEntry {
|
||||
let level: Logger.Level
|
||||
let metadata: Logger.Metadata?
|
||||
let message: String
|
||||
let error: (any Error)?
|
||||
let source: String
|
||||
let file: String
|
||||
let function: String
|
||||
let line: UInt
|
||||
|
||||
init(
|
||||
level: Logger.Level,
|
||||
metadata: Logger.Metadata?,
|
||||
message: String,
|
||||
error: (any Error)?,
|
||||
source: String,
|
||||
file: String = "",
|
||||
function: String = "",
|
||||
line: UInt = 0
|
||||
) {
|
||||
self.level = level
|
||||
self.metadata = metadata
|
||||
self.message = message
|
||||
self.error = error
|
||||
self.source = source
|
||||
self.file = file
|
||||
self.function = function
|
||||
self.line = line
|
||||
}
|
||||
}
|
||||
|
||||
extension History {
|
||||
func assertExist(
|
||||
level: Logger.Level,
|
||||
message: String,
|
||||
error: (any Error)? = nil,
|
||||
metadata: Logger.Metadata? = nil,
|
||||
source: String? = nil,
|
||||
file: String = #filePath,
|
||||
@@ -239,10 +295,10 @@ extension History {
|
||||
column: Int = #column
|
||||
) {
|
||||
let source = source ?? Logger.currentModule(fileID: "\(fileID)")
|
||||
let entry = self.find(level: level, message: message, metadata: metadata, source: source)
|
||||
let entry = self.find(level: level, message: message, error: error, metadata: metadata, source: source)
|
||||
#expect(
|
||||
entry != nil,
|
||||
"entry not found: \(level), \(source), \(String(describing: metadata)), \(message)",
|
||||
"entry not found: \(level), \(source), \(String(describing: metadata)), \(message), \(String(describing: error))",
|
||||
sourceLocation: SourceLocation(fileID: fileID, filePath: file, line: line, column: column)
|
||||
)
|
||||
}
|
||||
@@ -250,6 +306,7 @@ extension History {
|
||||
func assertNotExist(
|
||||
level: Logger.Level,
|
||||
message: String,
|
||||
error: (any Error)? = nil,
|
||||
metadata: Logger.Metadata? = nil,
|
||||
source: String? = nil,
|
||||
file: String = #filePath,
|
||||
@@ -258,15 +315,21 @@ extension History {
|
||||
column: Int = #column
|
||||
) {
|
||||
let source = source ?? Logger.currentModule(fileID: "\(fileID)")
|
||||
let entry = self.find(level: level, message: message, metadata: metadata, source: source)
|
||||
let entry = self.find(level: level, message: message, error: error, metadata: metadata, source: source)
|
||||
#expect(
|
||||
entry == nil,
|
||||
"entry was found: \(level), \(source), \(String(describing: metadata)), \(message)",
|
||||
"entry was found: \(level), \(source), \(String(describing: metadata)), \(message), \(String(describing: error))",
|
||||
sourceLocation: SourceLocation(fileID: fileID, filePath: file, line: line, column: column)
|
||||
)
|
||||
}
|
||||
|
||||
func find(level: Logger.Level, message: String, metadata: Logger.Metadata? = nil, source: String) -> LogEntry? {
|
||||
func find(
|
||||
level: Logger.Level,
|
||||
message: String,
|
||||
error: (any Error)? = nil,
|
||||
metadata: Logger.Metadata? = nil,
|
||||
source: String
|
||||
) -> LogEntry? {
|
||||
self.entries.first { entry in
|
||||
if entry.level != level {
|
||||
return false
|
||||
@@ -274,6 +337,9 @@ extension History {
|
||||
if entry.message != message {
|
||||
return false
|
||||
}
|
||||
if !errorsEqual(error, entry.error) {
|
||||
return false
|
||||
}
|
||||
if let lhs = entry.metadata, let rhs = metadata {
|
||||
if lhs.count != rhs.count {
|
||||
return false
|
||||
@@ -300,18 +366,29 @@ extension History {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
private func errorsEqual(_ lhs: (any Error)?, _ rhs: (any Error)?) -> Bool {
|
||||
switch (lhs, rhs) {
|
||||
case (nil, nil):
|
||||
return true
|
||||
case let (l?, r?):
|
||||
return "\(l)" == "\(r)" && String(reflecting: type(of: l)) == String(reflecting: type(of: r))
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// MDC stands for Mapped Diagnostic Context
|
||||
public class MDC {
|
||||
class MDC {
|
||||
private let lock = NSLock()
|
||||
private var storage = [Int: Logger.Metadata]()
|
||||
|
||||
public static let global = MDC()
|
||||
static let global = MDC()
|
||||
|
||||
private init() {}
|
||||
|
||||
public subscript(metadataKey: String) -> Logger.Metadata.Value? {
|
||||
subscript(metadataKey: String) -> Logger.Metadata.Value? {
|
||||
get {
|
||||
self.lock.withLock {
|
||||
self.storage[self.threadId]?[metadataKey]
|
||||
@@ -327,19 +404,19 @@ public class MDC {
|
||||
}
|
||||
}
|
||||
|
||||
public var metadata: Logger.Metadata {
|
||||
var metadata: Logger.Metadata {
|
||||
self.lock.withLock {
|
||||
self.storage[self.threadId] ?? [:]
|
||||
}
|
||||
}
|
||||
|
||||
public func clear() {
|
||||
func clear() {
|
||||
self.lock.withLock {
|
||||
_ = self.storage.removeValue(forKey: self.threadId)
|
||||
}
|
||||
}
|
||||
|
||||
public func with(metadata: Logger.Metadata, _ body: () throws -> Void) rethrows {
|
||||
func with(metadata: Logger.Metadata, _ body: () throws -> Void) rethrows {
|
||||
for (key, value) in metadata {
|
||||
self[key] = value
|
||||
}
|
||||
@@ -351,7 +428,7 @@ public class MDC {
|
||||
try body()
|
||||
}
|
||||
|
||||
public func with<T>(metadata: Logger.Metadata, _ body: () throws -> T) rethrows -> T {
|
||||
func with<T>(metadata: Logger.Metadata, _ body: () throws -> T) rethrows -> T {
|
||||
for (key, value) in metadata {
|
||||
self[key] = value
|
||||
}
|
||||
@@ -375,6 +452,10 @@ public class MDC {
|
||||
return Int(pthread_mach_thread_np(pthread_self()))
|
||||
#elseif os(Windows)
|
||||
return Int(GetCurrentThreadId())
|
||||
#elseif os(FreeBSD)
|
||||
return Int(pthread_getthreadid_np())
|
||||
#elseif os(OpenBSD)
|
||||
return Int(bitPattern: pthread_self())
|
||||
#else
|
||||
return Int(pthread_self())
|
||||
#endif
|
||||
@@ -385,13 +466,13 @@ internal struct TestLibrary: Sendable {
|
||||
private let logger = Logger(label: "TestLibrary")
|
||||
private let queue = DispatchQueue(label: "TestLibrary")
|
||||
|
||||
public init() {}
|
||||
init() {}
|
||||
|
||||
public func doSomething() {
|
||||
func doSomething() {
|
||||
self.logger.info("TestLibrary::doSomething")
|
||||
}
|
||||
|
||||
public func doSomethingAsync(completion: @escaping @Sendable () -> Void) {
|
||||
func doSomethingAsync(completion: @escaping @Sendable () -> Void) {
|
||||
// libraries that use global loggers and async, need to make sure they propagate the
|
||||
// logging metadata when creating a new thread
|
||||
let metadata = MDC.global.metadata
|
||||
|
||||
@@ -29,12 +29,14 @@ struct SendableTest {
|
||||
let message1 = Logger.Message(stringLiteral: "critical 1")
|
||||
let message2 = Logger.Message(stringLiteral: "critical 2")
|
||||
let metadata: Logger.Metadata = ["key": "value"]
|
||||
let error = TestError()
|
||||
|
||||
let task = Task.detached {
|
||||
logger.info("info")
|
||||
logger.critical(message1)
|
||||
logger.critical(message2)
|
||||
logger.warning(.init(stringLiteral: "warning"), metadata: metadata)
|
||||
logger.warning("error", error: error)
|
||||
}
|
||||
|
||||
await task.value
|
||||
@@ -42,5 +44,8 @@ struct SendableTest {
|
||||
testLogging.history.assertExist(level: .critical, message: "critical 1", metadata: [:])
|
||||
testLogging.history.assertExist(level: .critical, message: "critical 2", metadata: [:])
|
||||
testLogging.history.assertExist(level: .warning, message: "warning", metadata: metadata)
|
||||
testLogging.history.assertExist(level: .warning, message: "error", error: error)
|
||||
}
|
||||
|
||||
final class TestError: Error {}
|
||||
}
|
||||
Reference in new issue
Block a user