Compare commits

..
7 Commits
Author SHA1 Message Date
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
9 changed files with 243 additions and 29 deletions

No files matched your search

+17 -2
View File
@@ -35,6 +35,12 @@ jobs:
uses: apple/swift-nio/.github/workflows/benchmarks.yml@main
with:
benchmark_package_path: "Benchmarks"
macos-benchmarks:
name: macOS benchmarks
uses: apple/swift-nio/.github/workflows/macos_benchmarks.yml@main
with:
benchmark_package_path: "Benchmarks"
macos_xcode_16_4_enabled: true
macos_xcode_26_1_enabled: true
@@ -42,8 +48,8 @@ jobs:
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 +61,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
+16 -2
View File
@@ -39,6 +39,12 @@ jobs:
uses: apple/swift-nio/.github/workflows/benchmarks.yml@main
with:
benchmark_package_path: "Benchmarks"
macos-benchmarks:
name: macOS benchmarks
uses: apple/swift-nio/.github/workflows/macos_benchmarks.yml@main
with:
benchmark_package_path: "Benchmarks"
macos_runner_pool: general
macos_xcode_16_4_enabled: true
macos_xcode_26_1_enabled: true
@@ -47,8 +53,8 @@ jobs:
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 +66,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 +80,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
@@ -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 }
}
}
@@ -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: **Ready for Implementation**
- 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.
+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)
}
}
+14 -1
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)
@@ -1026,6 +1026,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]()