mirror of
https://github.com/apple/swift-log
synced 2026-11-22 03:40:39 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 | ||
|
|
b1fa4ef41f | ||
|
|
63eaca6f4d | ||
|
|
f3a82f1119 | ||
|
|
6b380c9f4b |
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
|
||||
@@ -30,20 +30,28 @@ jobs:
|
||||
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
|
||||
|
||||
static-sdk:
|
||||
name: Static SDK
|
||||
static-linux:
|
||||
name: Static Linux Swift SDK
|
||||
# Workaround https://github.com/nektos/act/issues/1875
|
||||
uses: apple/swift-nio/.github/workflows/static_sdk.yml@main
|
||||
|
||||
@@ -53,7 +61,29 @@ 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
|
||||
uses: apple/swift-nio/.github/workflows/wasm_swift_sdk.yml@main
|
||||
|
||||
android:
|
||||
name: Android Swift SDK
|
||||
# Workaround https://github.com/nektos/act/issues/1875
|
||||
uses: apple/swift-nio/.github/workflows/android_swift_sdk.yml@main
|
||||
|
||||
release-builds:
|
||||
name: Release builds
|
||||
|
||||
@@ -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.8
|
||||
with:
|
||||
license_header_check_project_name: "Swift Logging API"
|
||||
|
||||
@@ -34,21 +34,31 @@ jobs:
|
||||
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
|
||||
|
||||
static-sdk:
|
||||
name: Static SDK
|
||||
static-linux:
|
||||
name: Static Linux Swift SDK
|
||||
# Workaround https://github.com/nektos/act/issues/1875
|
||||
uses: apple/swift-nio/.github/workflows/static_sdk.yml@main
|
||||
|
||||
@@ -60,6 +70,10 @@ jobs:
|
||||
build_scheme: swift-log-Package
|
||||
swift_test_enabled: true
|
||||
|
||||
android:
|
||||
name: Android Swift SDK
|
||||
# Workaround https://github.com/nektos/act/issues/1875
|
||||
uses: apple/swift-nio/.github/workflows/android_swift_sdk.yml@main
|
||||
|
||||
release-builds:
|
||||
name: Release builds
|
||||
@@ -70,3 +84,7 @@ jobs:
|
||||
windows_6_2_enabled: true
|
||||
windows_nightly_next_enabled: true
|
||||
windows_nightly_main_enabled: true
|
||||
|
||||
wasm:
|
||||
name: Wasm Swift SDK
|
||||
uses: apple/swift-nio/.github/workflows/wasm_swift_sdk.yml@main
|
||||
@@ -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" : 1605,
|
||||
"objectAllocCount" : 0
|
||||
}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"instructions" : 1608,
|
||||
"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.0
|
||||
// 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" : 981,
|
||||
"objectAllocCount" : 0
|
||||
}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"instructions" : 1351,
|
||||
"objectAllocCount" : 0
|
||||
}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"instructions" : 893,
|
||||
"objectAllocCount" : 0
|
||||
}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"instructions" : 1605,
|
||||
"objectAllocCount" : 0
|
||||
}
|
||||
+14
-17
@@ -4,27 +4,24 @@
|
||||
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,61 @@
|
||||
// swift-tools-version:6.0
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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"]),
|
||||
],
|
||||
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
|
||||
}
|
||||
@@ -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,8 +12,7 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Logging
|
||||
import Synchronization
|
||||
public import Logging
|
||||
|
||||
/// A custom log handler which just collects logs into memory.
|
||||
/// You can then retrieve an array of those log entries.
|
||||
@@ -35,7 +34,6 @@ import Synchronization
|
||||
/// let logEntries = logger.entries
|
||||
/// ```
|
||||
///
|
||||
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, *)
|
||||
public struct InMemoryLogHandler: LogHandler {
|
||||
public var metadata: Logger.Metadata = [:]
|
||||
public var metadataProvider: Logger.MetadataProvider?
|
||||
@@ -58,12 +56,13 @@ public struct InMemoryLogHandler: LogHandler {
|
||||
}
|
||||
}
|
||||
|
||||
private final class LogStore: Sendable {
|
||||
private let logs: Mutex<[Entry]> = .init([])
|
||||
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) {
|
||||
self.logs.withLock {
|
||||
$0.append(
|
||||
self.lock.withLockVoid {
|
||||
self._entries.append(
|
||||
Entry(
|
||||
level: level,
|
||||
message: message,
|
||||
@@ -74,13 +73,13 @@ public struct InMemoryLogHandler: LogHandler {
|
||||
}
|
||||
|
||||
fileprivate func clear() {
|
||||
self.logs.withLock {
|
||||
$0.removeAll()
|
||||
self.lock.withLockVoid {
|
||||
_entries.removeAll()
|
||||
}
|
||||
}
|
||||
|
||||
var entries: [Entry] {
|
||||
self.logs.withLock { $0 }
|
||||
self.lock.withLock { self._entries }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -93,6 +92,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, metadata: mergedMetadata)
|
||||
}
|
||||
|
||||
@available(*, deprecated, renamed: "log(event:)")
|
||||
public func log(
|
||||
level: Logger.Level,
|
||||
message: Logger.Message,
|
||||
@@ -102,14 +113,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")
|
||||
```
|
||||
+5
-5
@@ -1,11 +1,11 @@
|
||||
# Metadata Providers
|
||||
|
||||
Authors: [Moritz Lang](https://github.com/slashmo), [Konrad 'ktoso' Malawski](https://github.com/ktoso)
|
||||
|
||||
## Introduction
|
||||
# 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.
|
||||
|
||||
## Authors
|
||||
|
||||
[Moritz Lang](https://github.com/slashmo), [Konrad 'ktoso' Malawski](https://github.com/ktoso)
|
||||
|
||||
## Motivation
|
||||
|
||||
To benefit from tools such as [Distributed Tracing](https://github.com/apple/swift-distributed-tracing) it is necessary for libraries to make use of the trace information.
|
||||
@@ -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: **Ready for Implementation**
|
||||
- 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,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: **Ready for Implementation**
|
||||
- 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
|
||||
|
||||
|
||||
+85
-63
@@ -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.
|
||||
internal 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.
|
||||
public init() {
|
||||
#if canImport(WASILibc)
|
||||
// WASILibc is single threaded, provides no locks
|
||||
#elseif os(Windows)
|
||||
package init() {
|
||||
#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
|
||||
}
|
||||
|
||||
@@ -92,12 +111,10 @@ internal final class Lock: @unchecked Sendable {
|
||||
///
|
||||
/// Whenever possible, consider using `withLock` instead of this method and
|
||||
/// `unlock`, to simplify lock handling.
|
||||
public func lock() {
|
||||
#if canImport(WASILibc)
|
||||
// WASILibc is single threaded, provides no locks
|
||||
#elseif os(Windows)
|
||||
package func lock() {
|
||||
#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
|
||||
@@ -107,19 +124,15 @@ internal final class Lock: @unchecked Sendable {
|
||||
///
|
||||
/// Whenever possible, consider using `withLock` instead of this method and
|
||||
/// `lock`, to simplify lock handling.
|
||||
public func unlock() {
|
||||
#if canImport(WASILibc)
|
||||
// WASILibc is single threaded, provides no locks
|
||||
#elseif os(Windows)
|
||||
package func unlock() {
|
||||
#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
|
||||
@@ -129,7 +142,7 @@ extension Lock {
|
||||
/// - Parameter body: The block to execute while holding the lock.
|
||||
/// - Returns: The value returned by the block.
|
||||
@inlinable
|
||||
internal func withLock<T>(_ body: () throws -> T) rethrows -> T {
|
||||
package func withLock<T>(_ body: () throws -> T) rethrows -> T {
|
||||
self.lock()
|
||||
defer {
|
||||
self.unlock()
|
||||
@@ -139,11 +152,28 @@ extension Lock {
|
||||
|
||||
// specialise Void return (for performance)
|
||||
@inlinable
|
||||
internal func withLockVoid(_ body: () throws -> Void) rethrows {
|
||||
package func withLockVoid(_ body: () throws -> Void) rethrows {
|
||||
try self.withLock(body)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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,87 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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 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.level = level
|
||||
self.message = message
|
||||
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,
|
||||
|
||||
+306
-124
@@ -19,7 +19,7 @@ import CRT
|
||||
#elseif canImport(Glibc)
|
||||
@preconcurrency import Glibc
|
||||
#elseif canImport(Android)
|
||||
import Android
|
||||
@preconcurrency import Android
|
||||
#elseif canImport(Musl)
|
||||
import Musl
|
||||
#elseif canImport(WASILibc)
|
||||
@@ -102,6 +102,8 @@ extension Logger {
|
||||
/// If the `logLevel` passed to this method is more severe than the `Logger`'s ``logLevel``, the library
|
||||
/// logs the message, otherwise nothing will happen.
|
||||
///
|
||||
/// NOTE: This method adds a constant overhead over calling level-specific methods.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - level: The severity level of the `message`.
|
||||
/// - message: The message to be logged. The `message` parameter supports any string interpolation literal.
|
||||
@@ -123,16 +125,78 @@ extension Logger {
|
||||
file: String = #fileID,
|
||||
function: String = #function,
|
||||
line: UInt = #line
|
||||
) {
|
||||
#if MaxLogLevelDebug || MaxLogLevelInfo || MaxLogLevelNotice || MaxLogLevelWarning || MaxLogLevelError || MaxLogLevelCritical || MaxLogLevelNone
|
||||
// A constant overhead is added for dynamic log level calls if one of the traits is enabled.
|
||||
// This allows picking the necessary implementation with compiled out body in runtime.
|
||||
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)
|
||||
case .info:
|
||||
self.info(message(), metadata: metadata(), source: source(), file: file, function: function, line: line)
|
||||
case .notice:
|
||||
self.notice(message(), metadata: metadata(), source: source(), file: file, function: function, line: line)
|
||||
case .warning:
|
||||
self.warning(message(), metadata: metadata(), source: source(), file: file, function: function, line: line)
|
||||
case .error:
|
||||
self.error(message(), metadata: metadata(), source: source(), file: file, function: function, line: line)
|
||||
case .critical:
|
||||
self.critical(message(), metadata: metadata(), source: source(), file: file, function: function, line: line)
|
||||
}
|
||||
#else
|
||||
// If no logs are excluded in the compile time, we can avoid checking the log level that extra time and go log it.
|
||||
self._log(
|
||||
level: level,
|
||||
message(),
|
||||
metadata: metadata(),
|
||||
source: source(),
|
||||
file: file,
|
||||
function: function,
|
||||
line: line
|
||||
)
|
||||
#endif
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// - 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
|
||||
package 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 self.logLevel <= level {
|
||||
self.handler.log(
|
||||
level: level,
|
||||
message: message(),
|
||||
metadata: metadata(),
|
||||
source: source() ?? Logger.currentModule(fileID: (file)),
|
||||
file: file,
|
||||
function: function,
|
||||
line: line
|
||||
event: LogEvent(
|
||||
level: level,
|
||||
message: message(),
|
||||
metadata: metadata(),
|
||||
source: source(),
|
||||
file: file,
|
||||
function: function,
|
||||
line: line
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -220,7 +284,8 @@ extension Logger {
|
||||
function: String = #function,
|
||||
line: UInt = #line
|
||||
) {
|
||||
self.log(
|
||||
#if !MaxLogLevelDebug && !MaxLogLevelInfo && !MaxLogLevelNotice && !MaxLogLevelWarning && !MaxLogLevelError && !MaxLogLevelCritical && !MaxLogLevelNone
|
||||
self._log(
|
||||
level: .trace,
|
||||
message(),
|
||||
metadata: metadata(),
|
||||
@@ -229,6 +294,7 @@ extension Logger {
|
||||
function: function,
|
||||
line: line
|
||||
)
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Log a message at the 'trace' log level.
|
||||
@@ -281,7 +347,8 @@ extension Logger {
|
||||
function: String = #function,
|
||||
line: UInt = #line
|
||||
) {
|
||||
self.log(
|
||||
#if !MaxLogLevelInfo && !MaxLogLevelNotice && !MaxLogLevelWarning && !MaxLogLevelError && !MaxLogLevelCritical && !MaxLogLevelNone
|
||||
self._log(
|
||||
level: .debug,
|
||||
message(),
|
||||
metadata: metadata(),
|
||||
@@ -290,6 +357,7 @@ extension Logger {
|
||||
function: function,
|
||||
line: line
|
||||
)
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Log a message at the 'debug' log level.
|
||||
@@ -342,7 +410,8 @@ extension Logger {
|
||||
function: String = #function,
|
||||
line: UInt = #line
|
||||
) {
|
||||
self.log(
|
||||
#if !MaxLogLevelNotice && !MaxLogLevelWarning && !MaxLogLevelError && !MaxLogLevelCritical && !MaxLogLevelNone
|
||||
self._log(
|
||||
level: .info,
|
||||
message(),
|
||||
metadata: metadata(),
|
||||
@@ -351,6 +420,7 @@ extension Logger {
|
||||
function: function,
|
||||
line: line
|
||||
)
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Log a message at the 'info' log level.
|
||||
@@ -403,7 +473,8 @@ extension Logger {
|
||||
function: String = #function,
|
||||
line: UInt = #line
|
||||
) {
|
||||
self.log(
|
||||
#if !MaxLogLevelWarning && !MaxLogLevelError && !MaxLogLevelCritical && !MaxLogLevelNone
|
||||
self._log(
|
||||
level: .notice,
|
||||
message(),
|
||||
metadata: metadata(),
|
||||
@@ -412,6 +483,7 @@ extension Logger {
|
||||
function: function,
|
||||
line: line
|
||||
)
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Log a message at the 'notice' log level.
|
||||
@@ -464,7 +536,8 @@ extension Logger {
|
||||
function: String = #function,
|
||||
line: UInt = #line
|
||||
) {
|
||||
self.log(
|
||||
#if !MaxLogLevelError && !MaxLogLevelCritical && !MaxLogLevelNone
|
||||
self._log(
|
||||
level: .warning,
|
||||
message(),
|
||||
metadata: metadata(),
|
||||
@@ -473,6 +546,7 @@ extension Logger {
|
||||
function: function,
|
||||
line: line
|
||||
)
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Log a message at the 'warning' log level.
|
||||
@@ -525,7 +599,8 @@ extension Logger {
|
||||
function: String = #function,
|
||||
line: UInt = #line
|
||||
) {
|
||||
self.log(
|
||||
#if !MaxLogLevelCritical && !MaxLogLevelNone
|
||||
self._log(
|
||||
level: .error,
|
||||
message(),
|
||||
metadata: metadata(),
|
||||
@@ -534,6 +609,7 @@ extension Logger {
|
||||
function: function,
|
||||
line: line
|
||||
)
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Log a message at the 'error' log level.
|
||||
@@ -586,7 +662,8 @@ extension Logger {
|
||||
function: String = #function,
|
||||
line: UInt = #line
|
||||
) {
|
||||
self.log(
|
||||
#if !MaxLogLevelNone
|
||||
self._log(
|
||||
level: .critical,
|
||||
message(),
|
||||
metadata: metadata(),
|
||||
@@ -595,6 +672,7 @@ extension Logger {
|
||||
function: function,
|
||||
line: line
|
||||
)
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Log a message at the 'critical' log level.
|
||||
@@ -636,7 +714,7 @@ extension Logger {
|
||||
///
|
||||
/// The default (``StreamLogHandler``) is intended to be a convenience.
|
||||
/// For production applications, implement the ``LogHandler`` protocol directly, or use a community-maintained backend.
|
||||
public enum LoggingSystem {
|
||||
public enum LoggingSystem: Sendable {
|
||||
private static let _factory = FactoryBox(
|
||||
{ label, _ in StreamLogHandler.standardError(label: label) },
|
||||
violationErrorMesage: "logging system can only be initialized once per process."
|
||||
@@ -1026,6 +1104,19 @@ extension Logger.Level: Comparable {
|
||||
}
|
||||
}
|
||||
|
||||
extension Logger.Level: CustomStringConvertible, LosslessStringConvertible {
|
||||
/// A textual representation of the log level.
|
||||
public var description: String {
|
||||
self.rawValue
|
||||
}
|
||||
|
||||
/// Creates a log level from its textual representation.
|
||||
/// - Parameter description: A textual representation of the log level, case insensitive.
|
||||
public init?(_ description: String) {
|
||||
self.init(rawValue: description.lowercased())
|
||||
}
|
||||
}
|
||||
|
||||
// Extension has to be done on explicit type rather than Logger.Metadata.Value as workaround for
|
||||
// https://bugs.swift.org/browse/SR-9687
|
||||
// Then we could write it as follows and it would work under Swift 5 and not only 4 as it does currently:
|
||||
@@ -1216,17 +1307,14 @@ public struct MultiplexLogHandler: LogHandler {
|
||||
/// Log a message using the log level and source that you provide.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - level: The log level to log the `message`.
|
||||
/// - message: The message to be logged. The `message` parameter supports any string interpolation literal.
|
||||
/// - 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`.
|
||||
/// - event: The log event containing the level, message, metadata, and source location.
|
||||
public func log(event: LogEvent) {
|
||||
for handler in self.handlers where handler.logLevel <= event.level {
|
||||
handler.log(event: event)
|
||||
}
|
||||
}
|
||||
|
||||
@available(*, deprecated, renamed: "log(event:)")
|
||||
public func log(
|
||||
level: Logger.Level,
|
||||
message: Logger.Message,
|
||||
@@ -1236,8 +1324,8 @@ public struct MultiplexLogHandler: LogHandler {
|
||||
function: String,
|
||||
line: UInt
|
||||
) {
|
||||
for handler in self.handlers where handler.logLevel <= level {
|
||||
handler.log(
|
||||
self.log(
|
||||
event: LogEvent(
|
||||
level: level,
|
||||
message: message,
|
||||
metadata: metadata,
|
||||
@@ -1246,8 +1334,9 @@ public struct MultiplexLogHandler: LogHandler {
|
||||
function: function,
|
||||
line: line
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
/// Get or set the entire metadata storage as a dictionary.
|
||||
public var metadata: Logger.Metadata {
|
||||
get {
|
||||
@@ -1299,38 +1388,40 @@ public struct MultiplexLogHandler: LogHandler {
|
||||
}
|
||||
}
|
||||
|
||||
#if canImport(WASILibc) || os(Android)
|
||||
internal typealias CFilePointer = OpaquePointer
|
||||
#else
|
||||
internal typealias CFilePointer = UnsafeMutablePointer<FILE>
|
||||
#endif
|
||||
|
||||
/// A wrapper to facilitate `print`-ing to stderr and stdio that
|
||||
/// ensures access to the underlying `FILE` is locked to prevent
|
||||
/// cross-thread interleaving of output.
|
||||
internal struct StdioOutputStream: TextOutputStream, @unchecked Sendable {
|
||||
internal let file: CFilePointer
|
||||
internal let flushMode: FlushMode
|
||||
private let _writeBytes: (UnsafeBufferPointer<UInt8>) -> Void
|
||||
private let _flush: () -> Void
|
||||
|
||||
// Using a generic initializer lets Swift infer the concrete file-pointer type
|
||||
// at each call site from the values passed. This avoids a CFilePointer typealias
|
||||
// that cannot vary by Android API level (API 23 exposes FILE as
|
||||
// UnsafeMutablePointer<FILE>; API 24+ makes it OpaquePointer).
|
||||
internal init<F>(
|
||||
file: F,
|
||||
flushMode: FlushMode,
|
||||
lock: ((F) -> Void)?,
|
||||
unlock: ((F) -> Void)?,
|
||||
write: @escaping (UnsafeRawPointer, Int, Int, F) -> Int,
|
||||
flush: @escaping (F) -> Int32
|
||||
) {
|
||||
self.flushMode = flushMode
|
||||
self._writeBytes = { bytes in
|
||||
lock?(file)
|
||||
defer { unlock?(file) }
|
||||
if let base = bytes.baseAddress, bytes.count > 0 {
|
||||
_ = write(base, 1, bytes.count, file)
|
||||
}
|
||||
}
|
||||
self._flush = { _ = flush(file) }
|
||||
}
|
||||
|
||||
internal func write(_ string: String) {
|
||||
self.contiguousUTF8(string).withContiguousStorageIfAvailable { utf8Bytes in
|
||||
#if os(Windows)
|
||||
_lock_file(self.file)
|
||||
#elseif canImport(WASILibc)
|
||||
// no file locking on WASI
|
||||
#else
|
||||
flockfile(self.file)
|
||||
#endif
|
||||
defer {
|
||||
#if os(Windows)
|
||||
_unlock_file(self.file)
|
||||
#elseif canImport(WASILibc)
|
||||
// no file locking on WASI
|
||||
#else
|
||||
funlockfile(self.file)
|
||||
#endif
|
||||
}
|
||||
_ = fwrite(utf8Bytes.baseAddress!, 1, utf8Bytes.count, self.file)
|
||||
self._writeBytes(utf8Bytes)
|
||||
if case .always = self.flushMode {
|
||||
self.flush()
|
||||
}
|
||||
@@ -1339,7 +1430,7 @@ internal struct StdioOutputStream: TextOutputStream, @unchecked Sendable {
|
||||
|
||||
/// Flush the underlying stream.
|
||||
internal func flush() {
|
||||
_ = fflush(self.file)
|
||||
self._flush()
|
||||
}
|
||||
|
||||
internal func contiguousUTF8(_ string: String) -> String.UTF8View {
|
||||
@@ -1348,44 +1439,148 @@ internal struct StdioOutputStream: TextOutputStream, @unchecked Sendable {
|
||||
return contiguousString.utf8
|
||||
}
|
||||
|
||||
internal static let stderr = {
|
||||
// Prevent name clashes
|
||||
internal static let stderr: StdioOutputStream = {
|
||||
#if canImport(Darwin)
|
||||
let systemStderr = Darwin.stderr
|
||||
return StdioOutputStream(
|
||||
file: Darwin.stderr,
|
||||
flushMode: .always,
|
||||
lock: flockfile,
|
||||
unlock: funlockfile,
|
||||
write: fwrite,
|
||||
flush: fflush
|
||||
)
|
||||
#elseif os(Windows)
|
||||
let systemStderr = CRT.stderr
|
||||
return StdioOutputStream(
|
||||
file: CRT.stderr,
|
||||
flushMode: .always,
|
||||
lock: _lock_file,
|
||||
unlock: _unlock_file,
|
||||
write: fwrite,
|
||||
flush: fflush
|
||||
)
|
||||
#elseif canImport(Glibc)
|
||||
let systemStderr = Glibc.stderr!
|
||||
#if os(FreeBSD) || os(OpenBSD)
|
||||
return StdioOutputStream(
|
||||
file: Glibc.stderr,
|
||||
flushMode: .always,
|
||||
lock: flockfile,
|
||||
unlock: funlockfile,
|
||||
write: fwrite,
|
||||
flush: fflush
|
||||
)
|
||||
#else
|
||||
return StdioOutputStream(
|
||||
file: Glibc.stderr!,
|
||||
flushMode: .always,
|
||||
lock: flockfile,
|
||||
unlock: funlockfile,
|
||||
write: fwrite,
|
||||
flush: fflush
|
||||
)
|
||||
#endif
|
||||
#elseif canImport(Android)
|
||||
let systemStderr = Android.stderr
|
||||
return StdioOutputStream(
|
||||
file: Android.stderr,
|
||||
flushMode: .always,
|
||||
lock: flockfile,
|
||||
unlock: funlockfile,
|
||||
write: fwrite,
|
||||
flush: fflush
|
||||
)
|
||||
#elseif canImport(Musl)
|
||||
let systemStderr = Musl.stderr!
|
||||
return StdioOutputStream(
|
||||
file: Musl.stderr!,
|
||||
flushMode: .always,
|
||||
lock: flockfile,
|
||||
unlock: funlockfile,
|
||||
write: fwrite,
|
||||
flush: fflush
|
||||
)
|
||||
#elseif canImport(WASILibc)
|
||||
let systemStderr = WASILibc.stderr!
|
||||
// no file locking on WASI
|
||||
return StdioOutputStream(
|
||||
file: WASILibc.stderr!,
|
||||
flushMode: .always,
|
||||
lock: nil,
|
||||
unlock: nil,
|
||||
write: fwrite,
|
||||
flush: fflush
|
||||
)
|
||||
#else
|
||||
#error("Unsupported runtime")
|
||||
#endif
|
||||
return StdioOutputStream(file: systemStderr, flushMode: .always)
|
||||
}()
|
||||
|
||||
internal static let stdout = {
|
||||
// Prevent name clashes
|
||||
internal static let stdout: StdioOutputStream = {
|
||||
#if canImport(Darwin)
|
||||
let systemStdout = Darwin.stdout
|
||||
return StdioOutputStream(
|
||||
file: Darwin.stdout,
|
||||
flushMode: .always,
|
||||
lock: flockfile,
|
||||
unlock: funlockfile,
|
||||
write: fwrite,
|
||||
flush: fflush
|
||||
)
|
||||
#elseif os(Windows)
|
||||
let systemStdout = CRT.stdout
|
||||
return StdioOutputStream(
|
||||
file: CRT.stdout,
|
||||
flushMode: .always,
|
||||
lock: _lock_file,
|
||||
unlock: _unlock_file,
|
||||
write: fwrite,
|
||||
flush: fflush
|
||||
)
|
||||
#elseif canImport(Glibc)
|
||||
let systemStdout = Glibc.stdout!
|
||||
#if os(FreeBSD) || os(OpenBSD)
|
||||
return StdioOutputStream(
|
||||
file: Glibc.stdout,
|
||||
flushMode: .always,
|
||||
lock: flockfile,
|
||||
unlock: funlockfile,
|
||||
write: fwrite,
|
||||
flush: fflush
|
||||
)
|
||||
#else
|
||||
return StdioOutputStream(
|
||||
file: Glibc.stdout!,
|
||||
flushMode: .always,
|
||||
lock: flockfile,
|
||||
unlock: funlockfile,
|
||||
write: fwrite,
|
||||
flush: fflush
|
||||
)
|
||||
#endif
|
||||
#elseif canImport(Android)
|
||||
let systemStdout = Android.stdout
|
||||
return StdioOutputStream(
|
||||
file: Android.stdout,
|
||||
flushMode: .always,
|
||||
lock: flockfile,
|
||||
unlock: funlockfile,
|
||||
write: fwrite,
|
||||
flush: fflush
|
||||
)
|
||||
#elseif canImport(Musl)
|
||||
let systemStdout = Musl.stdout!
|
||||
return StdioOutputStream(
|
||||
file: Musl.stdout!,
|
||||
flushMode: .always,
|
||||
lock: flockfile,
|
||||
unlock: funlockfile,
|
||||
write: fwrite,
|
||||
flush: fflush
|
||||
)
|
||||
#elseif canImport(WASILibc)
|
||||
let systemStdout = WASILibc.stdout!
|
||||
// no file locking on WASI
|
||||
return StdioOutputStream(
|
||||
file: WASILibc.stdout!,
|
||||
flushMode: .always,
|
||||
lock: nil,
|
||||
unlock: nil,
|
||||
write: fwrite,
|
||||
flush: fflush
|
||||
)
|
||||
#else
|
||||
#error("Unsupported runtime")
|
||||
#endif
|
||||
return StdioOutputStream(file: systemStdout, flushMode: .always)
|
||||
}()
|
||||
|
||||
/// Defines the flushing strategy for the underlying stream.
|
||||
@@ -1484,30 +1679,12 @@ public struct StreamLogHandler: LogHandler {
|
||||
/// Log a message using the log level and source that you provide.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - level: The log level to log the `message`.
|
||||
/// - message: The message to be logged. The `message` parameter supports any string interpolation literal.
|
||||
/// - explicitMetadata: 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`.
|
||||
public func log(
|
||||
level: Logger.Level,
|
||||
message: Logger.Message,
|
||||
metadata explicitMetadata: Logger.Metadata?,
|
||||
source: String,
|
||||
file: String,
|
||||
function: String,
|
||||
line: UInt
|
||||
) {
|
||||
/// - event: The log event containing the level, message, metadata, and source location.
|
||||
public func log(event: LogEvent) {
|
||||
let effectiveMetadata = StreamLogHandler.prepareMetadata(
|
||||
base: self.metadata,
|
||||
provider: self.metadataProvider,
|
||||
explicit: explicitMetadata
|
||||
explicit: event.metadata
|
||||
)
|
||||
|
||||
let prettyMetadata: String?
|
||||
@@ -1519,7 +1696,30 @@ public struct StreamLogHandler: LogHandler {
|
||||
|
||||
var stream = self.stream
|
||||
stream.write(
|
||||
"\(self.timestamp()) \(level)\(self.label.isEmpty ? "" : " ")\(self.label):\(prettyMetadata.map { " \($0)" } ?? "") [\(source)] \(message)\n"
|
||||
"\(self.timestamp()) \(event.level)\(self.label.isEmpty ? "" : " ")\(self.label):\(prettyMetadata.map { " \($0)" } ?? "") [\(event.source)] \(event.message)\n"
|
||||
)
|
||||
}
|
||||
|
||||
@available(*, deprecated, renamed: "log(event:)")
|
||||
public func log(
|
||||
level: Logger.Level,
|
||||
message: Logger.Message,
|
||||
metadata: Logger.Metadata?,
|
||||
source: String,
|
||||
file: String,
|
||||
function: String,
|
||||
line: UInt
|
||||
) {
|
||||
self.log(
|
||||
event: LogEvent(
|
||||
level: level,
|
||||
message: message,
|
||||
metadata: metadata,
|
||||
source: source,
|
||||
file: file,
|
||||
function: function,
|
||||
line: line
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1589,46 +1789,28 @@ public struct SwiftLogNoOpLogHandler: LogHandler {
|
||||
/// Creates a no-op log handler.
|
||||
public init(_: String) {}
|
||||
|
||||
/// A proxy that discards every log message it receives.
|
||||
/// A proxy that discards every log event it receives.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - level: The log level to log the `message`.
|
||||
/// - message: The message to be logged. The `message` parameter supports any string interpolation literal.
|
||||
/// - metadata: One-off metadata to attach to this 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`.
|
||||
/// - event: The log event to discard.
|
||||
@inlinable public func log(event: LogEvent) {}
|
||||
|
||||
@available(*, deprecated, renamed: "log(event:)")
|
||||
@inlinable public func log(
|
||||
level: Logger.Level,
|
||||
message: Logger.Message,
|
||||
metadata: Logger.Metadata?,
|
||||
source: String,
|
||||
file: String,
|
||||
function: String,
|
||||
line: UInt
|
||||
) {}
|
||||
|
||||
/// A proxy that discards every log message that you provide.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - level: The log level to log the `message`.
|
||||
/// - message: The message to be logged. The `message` parameter supports any string interpolation literal.
|
||||
/// - 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`.
|
||||
public func log(
|
||||
level: Logger.Level,
|
||||
message: Logger.Message,
|
||||
metadata: Logger.Metadata?,
|
||||
source: String,
|
||||
@available(*, deprecated, renamed: "log(event:)")
|
||||
@inlinable public func log(
|
||||
level: Logging.Logger.Level,
|
||||
message: Logging.Logger.Message,
|
||||
metadata: Logging.Logger.Metadata?,
|
||||
file: String,
|
||||
function: String,
|
||||
line: UInt
|
||||
|
||||
@@ -18,7 +18,6 @@ import Testing
|
||||
|
||||
struct InMemoryLogHandlerTests {
|
||||
@Test
|
||||
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, *)
|
||||
func collectsLogs() {
|
||||
let (logHandler, logger) = self.makeTestLogger()
|
||||
logger.info("hello", metadata: ["key1": "value1", "key2": ["a", "b", "c"]])
|
||||
@@ -35,7 +34,6 @@ struct InMemoryLogHandlerTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, *)
|
||||
func metadataFromLoggerEndsUpInEntry() {
|
||||
var (logHandler, logger) = self.makeTestLogger()
|
||||
logger[metadataKey: "test"] = "value"
|
||||
@@ -55,7 +53,6 @@ struct InMemoryLogHandlerTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, *)
|
||||
func moreSpecificMetadataOverridesGlobal() {
|
||||
let testProvider = Logger.MetadataProvider {
|
||||
["a": "1", "b": "1", "c": "1"]
|
||||
@@ -73,7 +70,6 @@ struct InMemoryLogHandlerTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, *)
|
||||
func clear() {
|
||||
let (logHandler, logger) = self.makeTestLogger()
|
||||
logger.info("hello", metadata: ["key1": "value1", "key2": ["a", "b", "c"]])
|
||||
@@ -88,7 +84,6 @@ struct InMemoryLogHandlerTests {
|
||||
)
|
||||
}
|
||||
|
||||
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, *)
|
||||
private func makeTestLogger(metadataProvider: Logger.MetadataProvider? = nil) -> (InMemoryLogHandler, Logger) {
|
||||
var logHandler = InMemoryLogHandler()
|
||||
logHandler.metadataProvider = metadataProvider
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
}
|
||||
@@ -443,13 +443,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 +459,7 @@ struct LoggingTest {
|
||||
return self._value!
|
||||
}
|
||||
|
||||
public var description: String {
|
||||
var description: String {
|
||||
"\(self.value)"
|
||||
}
|
||||
}
|
||||
@@ -543,15 +543,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 }
|
||||
@@ -869,16 +861,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 +946,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 +1106,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 +1133,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 +1158,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 +1184,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 +1218,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 +1261,7 @@ struct LoggingTest {
|
||||
}
|
||||
|
||||
// the actual test
|
||||
body(writeFD, readFD, readBuffer)
|
||||
body(stream, readFD, readBuffer)
|
||||
|
||||
for fd in fds {
|
||||
#if os(Windows)
|
||||
@@ -1287,7 +1304,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 +1349,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,20 @@ 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,
|
||||
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: level, metadata: metadata, message: message, source: source)
|
||||
self.recorder.record(level: event.level, metadata: metadata, message: event.message, source: event.source)
|
||||
}
|
||||
|
||||
private var _logLevel: Logger.Level?
|
||||
@@ -125,7 +117,7 @@ internal struct TestLogHandler: LogHandler {
|
||||
}
|
||||
}
|
||||
|
||||
public var metadata: Logger.Metadata {
|
||||
var metadata: Logger.Metadata {
|
||||
get {
|
||||
self._metadata
|
||||
}
|
||||
@@ -183,6 +175,30 @@ internal class Recorder: History {
|
||||
}
|
||||
}
|
||||
|
||||
func record(
|
||||
level: Logger.Level,
|
||||
metadata: Logger.Metadata?,
|
||||
message: Logger.Message,
|
||||
source: String,
|
||||
file: String,
|
||||
function: String,
|
||||
line: UInt
|
||||
) {
|
||||
self.lock.withLock {
|
||||
self._entries.append(
|
||||
LogEntry(
|
||||
level: level,
|
||||
metadata: metadata,
|
||||
message: message.description,
|
||||
source: source,
|
||||
file: file,
|
||||
function: function,
|
||||
line: line
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
var entries: [LogEntry] {
|
||||
self.lock.withLock { self._entries }
|
||||
}
|
||||
@@ -225,6 +241,27 @@ internal struct LogEntry {
|
||||
let metadata: Logger.Metadata?
|
||||
let message: String
|
||||
let source: String
|
||||
let file: String
|
||||
let function: String
|
||||
let line: UInt
|
||||
|
||||
init(
|
||||
level: Logger.Level,
|
||||
metadata: Logger.Metadata?,
|
||||
message: String,
|
||||
source: String,
|
||||
file: String = "",
|
||||
function: String = "",
|
||||
line: UInt = 0
|
||||
) {
|
||||
self.level = level
|
||||
self.metadata = metadata
|
||||
self.message = message
|
||||
self.source = source
|
||||
self.file = file
|
||||
self.function = function
|
||||
self.line = line
|
||||
}
|
||||
}
|
||||
|
||||
extension History {
|
||||
@@ -303,15 +340,15 @@ extension History {
|
||||
}
|
||||
|
||||
/// 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 +364,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 +388,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 +412,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 +426,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
|
||||
|
||||
Reference in new issue
Block a user