Compare commits

..
10 Commits
Author SHA1 Message Date
Vladimir Kukushkin 7ee16e4656 The SLG-0002 implementation is merged, update the proposal status (#399)
Just bumping the status before making the release.
2026-01-14 13:04:51 +00:00
Vladimir Kukushkin 1ccd2c5a27 [SLG-0002] Implementation: Compile-time log level elimination using traits (#389)
Add compile-time traits for eliminating log levels from binaries

###  Motivation:

Applications often know in advance which log levels will never be needed
in production. For example, a production service might only need warning
and above, while trace and debug levels are only useful during
development. This PR introduces
compile-time traits that completely eliminate unwanted log levels from
binaries, achieving zero runtime overhead for disabled log statements.

### Modifications:

- Added seven `MaxLogLevel*` traits
- Extended benchmarks with the `MaxLogLevelWarning` suite
- Added "Disable log levels during compilation" section to the best
practices guide

### Result:

Users can eliminate unwanted log levels at compile time by specifying
traits in their `Package.swift` dependency declaration.
2026-01-13 14:23:51 +00:00
Salman Chishti 477fab4170 Upgrade GitHub Actions for Node 24 compatibility (#397)
## Summary

Upgrade GitHub Actions to their latest versions to ensure compatibility
with Node 24, as Node 20 will reach end-of-life in April 2026.

## Changes

| Action | Old Version(s) | New Version | Release | Files |
|--------|---------------|-------------|---------|-------|
| `actions/checkout` |
[`v4`](https://github.com/actions/checkout/releases/tag/v4) |
[`v6`](https://github.com/actions/checkout/releases/tag/v6) |
[Release](https://github.com/actions/checkout/releases/tag/v6) |
pull_request_label.yml |

## Context

Per [GitHub's
announcement](https://github.blog/changelog/2025-09-19-deprecation-of-node-20-on-github-actions-runners/),
Node 20 is being deprecated and runners will begin using Node 24 by
default starting March 4th, 2026.

### Why this matters

- **Node 20 EOL**: April 2026
- **Node 24 default**: March 4th, 2026
- **Action**: Update to latest action versions that support Node 24

### Security Note

Actions that were previously pinned to commit SHAs remain pinned to SHAs
(updated to the latest release SHA) to maintain the security benefits of
immutable references.

### Testing

These changes only affect CI/CD workflow configurations and should not
impact application functionality. The workflows should be tested by
running them on a branch before merging.

Signed-off-by: Salman Muin Kayser Chishti <13schishti@gmail.com>
2025-12-18 06:27:47 +09:00
Vladimir Kukushkin bc386b95f2 [SLG-0002]: Compile-time log level elimination using traits (#391)
Enable compile-time elimination of log levels to achieve zero runtime
overhead for logs that will never be needed in production.

### 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.

### Modifications:

The "SLG-0002: Compile-time log level elimination using traits" proposal
doc added.

### Result:

The proposal is ready for implementation.
2025-12-11 12:31:11 +00:00
Vladimir Kukushkin 6856e42a3f Adapt separate benchmark workflows from swift-nio (#396)
Depends on https://github.com/apple/swift-nio/pull/3461, which is not
yet merged

### Motivation:

`swift-nio` now has 2 separate workflows for running benchmarks on Linux
and macOS to remove unnecessary noise of skipped macOS benchmarks, see
[`swift-nio` PR](https://github.com/apple/swift-nio/pull/3461) for
details.

### Modifications:

Split Linux and macOS benchmarks into different jobs.

### Result:

Linux and macOS benchmarks are running as different jobs.
2025-12-11 12:47:43 +01:00
Francesco Paolo Severino cdaa5ac879 Conform Logger.Level to CustomStringConvertible and LosslessStringConvertible (#395)
Conform `Logger.Level` to `CustomStringConvertible` and
`LosslessStringConvertible`.

### Motivation:

There are libraries, such as Vapor, that add these conformances
privately and `@retroactive`ly. This would avoid having to implement
these conformances manually in each library and would unify and
standardise the implementation.

### Modifications:

Make `Logger.Level` conform to `CustomStringConvertible` and
`LosslessStringConvertible`, adding a public `description` computed
property that returns the `rawValue` and a public initializer that takes
a `description` string, lowercases it, and passes it to the `rawValue`
initializer.

### Result:

`Logger.Level` conforms to `CustomStringConvertible` and
`LosslessStringConvertible`.
2025-12-08 20:11:23 +01:00
hamzahrmalik b1fa4ef41f Make InMemoryLogging available on all platforms (#394)
Make InMemoryLogging available on all platforms

### Motivation:

Users might want to adopt the in memory logger on lower platform
versions.

### Modifications:

Remove availability annotations by using swift-logs own Lock instead of
Mutex

### Result:

In memory logger can be used on all platforms that swift-log supports
2025-12-04 11:52:31 +00:00
Max DesiatovandKonrad `ktoso` Malawski 63eaca6f4d Add Wasm builds to pull_request.yml (#371)
Co-authored-by: Konrad `ktoso` Malawski <konrad_malawski@apple.com>
2025-12-04 19:02:45 +09:00
Max Desiatov f3a82f1119 Fix Android build error with @preconcurrency import Android (#393) 2025-12-04 08:33:10 +09:00
Vladimir Kukushkin 6b380c9f4b Move pre-process proposal to the proposals folder (#392)
Move single pre-process proposal file to the new location.

### Motivation:

To have all the proposals in one place.

### Modifications:

One .md file moved.

### Result:

All proposals are in one place.
2025-12-03 16:27:10 +01:00
38 changed files with 758 additions and 140 deletions

No files matched your search

+34 -4
View File
@@ -31,19 +31,40 @@ jobs:
windows_nightly_main_arguments_override: "--explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
benchmarks:
name: Benchmarks
name: Benchmarks (NoTraits)
uses: apple/swift-nio/.github/workflows/benchmarks.yml@main
with:
benchmark_package_path: "Benchmarks"
benchmark_package_path: "Benchmarks/NoTraits"
macos-benchmarks:
name: macOS benchmarks (NoTraits)
uses: apple/swift-nio/.github/workflows/macos_benchmarks.yml@main
with:
benchmark_package_path: "Benchmarks/NoTraits"
macos_xcode_16_4_enabled: true
macos_xcode_26_1_enabled: true
benchmarks-MaxLogLevelWarningBenchmarks-trait:
name: Benchmarks (MaxLogLevelWarning)
needs: benchmarks
uses: apple/swift-nio/.github/workflows/benchmarks.yml@main
with:
benchmark_package_path: "Benchmarks/MaxLogLevelWarning"
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
@@ -55,6 +76,15 @@ jobs:
build_scheme: swift-log-Package
swift_test_enabled: true
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
uses: apple/swift-nio/.github/workflows/release_builds.yml@main
+36 -4
View File
@@ -35,20 +35,44 @@ jobs:
windows_nightly_main_arguments_override: "--explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
benchmarks:
name: Benchmarks
name: Benchmarks (NoTraits)
uses: apple/swift-nio/.github/workflows/benchmarks.yml@main
with:
benchmark_package_path: "Benchmarks"
benchmark_package_path: "Benchmarks/NoTraits"
macos-benchmarks:
name: macOS benchmarks (NoTraits)
uses: apple/swift-nio/.github/workflows/macos_benchmarks.yml@main
with:
benchmark_package_path: "Benchmarks/NoTraits"
macos_runner_pool: general
macos_xcode_16_4_enabled: true
macos_xcode_26_1_enabled: true
benchmarks-MaxLogLevelWarningBenchmarks-trait:
name: Benchmarks (MaxLogLevelWarning)
# Workaround for reusing the same benchmarks.yml workflow
needs: benchmarks
uses: apple/swift-nio/.github/workflows/benchmarks.yml@main
with:
benchmark_package_path: "Benchmarks/MaxLogLevelWarning"
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 +84,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 +98,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
+1 -1
View File
@@ -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
+2
View File
@@ -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")
}
}
}
}
+8
View File
@@ -0,0 +1,8 @@
.DS_Store
/.build
/Packages
xcuserdata/
DerivedData/
.swiftpm/configuration/registries.json
.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
.netrc
@@ -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")
]
)
]
)
+8
View File
@@ -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")
}
}
+37
View File
@@ -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")
]
)
]
)
@@ -0,0 +1,4 @@
{
"instructions" : 937,
"objectAllocCount" : 0
}
@@ -0,0 +1,4 @@
{
"instructions" : 1718,
"objectAllocCount" : 0
}
@@ -0,0 +1,4 @@
{
"instructions" : 855,
"objectAllocCount" : 0
}
@@ -0,0 +1,4 @@
{
"instructions" : 1636,
"objectAllocCount" : 0
}
+15 -18
View File
@@ -1,30 +1,27 @@
// swift-tools-version: 6.0
// swift-tools-version: 6.1
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "Benchmarks",
name: "BenchmarksFactory",
platforms: [
.macOS(.v13)
],
products: [
.library(name: "BenchmarksFactory", targets: ["BenchmarksFactory"])
],
dependencies: [
.package(path: "../"),
.package(url: "https://github.com/ordo-one/package-benchmark.git", from: "1.29.6"),
.package(path: "../"), // swift-log
],
targets: [
.target(
name: "BenchmarksFactory",
dependencies: [
.product(name: "Benchmark", package: "package-benchmark"),
.product(name: "Logging", package: "swift-log"),
]
)
]
)
// Benchmark of SwiftLogBenchmarks
package.targets += [
.executableTarget(
name: "SwiftLogBenchmarks",
dependencies: [
.product(name: "Benchmark", package: "package-benchmark"),
.product(name: "Logging", package: "swift-log"),
],
path: "Benchmarks/SwiftLogBenchmarks",
plugins: [
.plugin(name: "BenchmarkPlugin", package: "package-benchmark")
]
)
]
@@ -0,0 +1,55 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Logging API open source project
//
// Copyright (c) 2025 Apple Inc. and the Swift Logging API project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Swift Logging API project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Benchmark
import Foundation
import Logging
public func makeBenchmark(
loggerLevel: Logger.Level,
logLevel: Logger.Level,
_ suffix: String = "",
_ body: @escaping (Logger) -> Void
) {
let iterations = 1_000_000
let metrics: [BenchmarkMetric] = [.instructions, .objectAllocCount]
var logger = Logger(label: "BenchmarkRunner_\(loggerLevel)_\(logLevel)")
// Use a NoOpLogHandler to avoid polluting the logs
logger.handler = NoOpLogHandler(label: "NoOpLogHandler")
logger.logLevel = loggerLevel
Benchmark(
"\(logLevel)_log_with_\(loggerLevel)_log_level\(suffix)",
configuration: .init(
metrics: metrics,
maxIterations: iterations,
thresholds: [
.instructions: BenchmarkThresholds(
relative: [
.p90: 1.0 // we only record p90
]
),
.objectAllocCount: BenchmarkThresholds(
absolute: [
.p90: 0 // we only record p90
]
),
]
)
) { _ in
body(logger)
}
}
@@ -1,4 +0,0 @@
{
"instructions" : 3279,
"objectAllocCount" : 1
}
@@ -1,4 +0,0 @@
{
"instructions" : 3197,
"objectAllocCount" : 1
}
@@ -1,4 +0,0 @@
{
"instructions" : 3197,
"objectAllocCount" : 1
}
@@ -1,4 +0,0 @@
{
"instructions" : 3197,
"objectAllocCount" : 1
}
+19 -1
View File
@@ -1,4 +1,4 @@
// swift-tools-version:6.0
// swift-tools-version:6.1
//===----------------------------------------------------------------------===//
//
// 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",
+55
View File
@@ -0,0 +1,55 @@
// 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"])
],
targets: [
.target(
name: "Logging",
dependencies: []
),
.testTarget(
name: "LoggingTests",
dependencies: ["Logging"]
),
]
)
for target in package.targets {
var settings = target.swiftSettings ?? []
settings.append(.enableExperimentalFeature("StrictConcurrency=complete"))
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 --- //
@@ -13,7 +13,6 @@
//===----------------------------------------------------------------------===//
import Logging
import Synchronization
/// 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 }
}
}
@@ -9,7 +9,7 @@ creating well-behaved libraries that don't overwhelm logging systems or misuse
severity levels. This practice provides clear guidance on when to use each
level.
### Motivation
### Motivation
Libraries must be well-behaved across various use cases and cannot assume
specific logging backend configurations. Using inappropriate log levels can
@@ -51,7 +51,7 @@ Each level serves different purposes:
- **Performance**: May impact performance; assume it won't be used in production.
- **Content**: Internal state, detailed operation flows, diagnostic information.
##### Debug Level
##### Debug Level
- **Usage**: May be enabled in some production deployments.
- **Performance**: Should not significantly undermine production performance.
- **Content**: High-level operation overview, connection events, major decisions.
@@ -128,7 +128,7 @@ logger.info("Request failed")
```swift
// ❌ Bad: Normal operations at info level flood production logs
logger.info("HTTP request received")
logger.info("Database query executed")
logger.info("Database query executed")
logger.info("Response sent")
// ✅ Good: Use appropriate levels instead
@@ -0,0 +1,73 @@
# Disable log levels during compilation
SwiftLog provides compile-time traits to eliminate less severe log levels from
your binary reducing the runtime overhead.
## Motivation
When deploying applications to production, you often know in advance which log
levels will never be needed. For example, a production service might only need
warning and above, while trace and debug levels are only useful during
development. By using traits, you can completely remove these unnecessary log
levels at compile time, achieving zero runtime overhead.
## Available traits
SwiftLog defines seven maximum log level traits, ordered from most permissive
to most restrictive:
- `MaxLogLevelDebug`: Debug and above available (compiles out trace)
- `MaxLogLevelInfo`: Info and above available (compiles out trace, debug)
- `MaxLogLevelNotice`: Notice and above available (compiles out trace, debug,
info)
- `MaxLogLevelWarning`: Warning and above available (compiles out trace, debug,
info, notice)
- `MaxLogLevelError`: Error and above available (compiles out trace, debug,
info, notice, warning)
- `MaxLogLevelCritical`: Only critical available (compiles out all except
critical)
- `MaxLogLevelNone`: All logging compiled out (no log levels available)
By default (when no traits are specified), all log levels are available.
When you specify a maximum log level trait, all less severe levels are
completely removed from your binary at compile time. This applies to both
level-specific methods (e.g., `logger.debug()`) and calls to the generic
`logger.log(level:)` method. Traits are additive. If multiple max level traits
are specified, the most restrictive one takes effect.
> Note: Traits should only be set by the applications and not libraries as
> any traits defined in a transitive dependency will affect the whole resolution tree.
## Example
To enable a trait, specify it when declaring your package dependency:
```swift
// In your Package.swift:
dependencies: [
.package(
url: "https://github.com/apple/swift-log.git",
from: "1.0.0",
traits: ["MaxLogLevelWarning"]
)
]
```
With `MaxLogLevelWarning` enabled, all trace, debug, info, and notice log
statements are compiled out:
```swift
// These become no-ops (compiled out completely):
logger.trace("This will not be in the binary")
logger.debug("This will not be in the binary")
logger.info("This will not be in the binary")
logger.notice("This will not be in the binary")
logger.log(level: .debug, "This will not log anything")
// These work normally:
logger.warning("This still works")
logger.error("This still works")
logger.critical("This still works")
logger.log(level: .error, "This still works")
```
@@ -1,11 +1,11 @@
# Metadata Providers
Authors: [Moritz Lang](https://github.com/slashmo), [Konrad 'ktoso' Malawski](https://github.com/ktoso)
## Introduction
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.
+1
View File
@@ -92,6 +92,7 @@ backend.
- <doc:LoggingBestPractices>
- <doc:ImplementingALogHandler>
- <doc:DisableLogLevelsDuringCompilation>
### Contributing
+6 -6
View File
@@ -48,7 +48,7 @@ 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 {
package final class Lock: @unchecked Sendable {
#if canImport(WASILibc)
// WASILibc is single threaded, provides no locks
#elseif os(Windows)
@@ -60,7 +60,7 @@ internal final class Lock: @unchecked Sendable {
#endif
/// Create a new lock.
public init() {
package init() {
#if canImport(WASILibc)
// WASILibc is single threaded, provides no locks
#elseif os(Windows)
@@ -92,7 +92,7 @@ internal final class Lock: @unchecked Sendable {
///
/// Whenever possible, consider using `withLock` instead of this method and
/// `unlock`, to simplify lock handling.
public func lock() {
package func lock() {
#if canImport(WASILibc)
// WASILibc is single threaded, provides no locks
#elseif os(Windows)
@@ -107,7 +107,7 @@ internal final class Lock: @unchecked Sendable {
///
/// Whenever possible, consider using `withLock` instead of this method and
/// `lock`, to simplify lock handling.
public func unlock() {
package func unlock() {
#if canImport(WASILibc)
// WASILibc is single threaded, provides no locks
#elseif os(Windows)
@@ -129,7 +129,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,7 +139,7 @@ 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)
}
}
+97 -8
View File
@@ -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,6 +125,66 @@ 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(
@@ -220,7 +282,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 +292,7 @@ extension Logger {
function: function,
line: line
)
#endif
}
/// Log a message at the 'trace' log level.
@@ -281,7 +345,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 +355,7 @@ extension Logger {
function: function,
line: line
)
#endif
}
/// Log a message at the 'debug' log level.
@@ -342,7 +408,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 +418,7 @@ extension Logger {
function: function,
line: line
)
#endif
}
/// Log a message at the 'info' log level.
@@ -403,7 +471,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 +481,7 @@ extension Logger {
function: function,
line: line
)
#endif
}
/// Log a message at the 'notice' log level.
@@ -464,7 +534,8 @@ extension Logger {
function: String = #function,
line: UInt = #line
) {
self.log(
#if !MaxLogLevelError && !MaxLogLevelCritical && !MaxLogLevelNone
self._log(
level: .warning,
message(),
metadata: metadata(),
@@ -473,6 +544,7 @@ extension Logger {
function: function,
line: line
)
#endif
}
/// Log a message at the 'warning' log level.
@@ -525,7 +597,8 @@ extension Logger {
function: String = #function,
line: UInt = #line
) {
self.log(
#if !MaxLogLevelCritical && !MaxLogLevelNone
self._log(
level: .error,
message(),
metadata: metadata(),
@@ -534,6 +607,7 @@ extension Logger {
function: function,
line: line
)
#endif
}
/// Log a message at the 'error' log level.
@@ -586,7 +660,8 @@ extension Logger {
function: String = #function,
line: UInt = #line
) {
self.log(
#if !MaxLogLevelNone
self._log(
level: .critical,
message(),
metadata: metadata(),
@@ -595,6 +670,7 @@ extension Logger {
function: function,
line: line
)
#endif
}
/// Log a message at the 'critical' log level.
@@ -1026,6 +1102,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:
@@ -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
+5
View File
@@ -957,6 +957,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]()