Compare commits

...
Author SHA1 Message Date
Konrad `ktoso` Malawski fc3aaf1b75 Push baggage pick-up into LogHandlers 2022-11-14 12:11:00 +09:00
Konrad `ktoso` Malawski 7bdda417df Update Logging.swift 2022-10-25 18:04:11 +09:00
Konrad `ktoso` MalawskiandYim Lee 4c9b50fa60 Update proposals/0001-metadata-providers.md
Co-authored-by: Yim Lee <yim_lee@apple.com>
2022-10-04 14:32:59 +09:00
Konrad `ktoso` MalawskiandYim Lee 28ccbd72d9 Update proposals/0001-metadata-providers.md
Co-authored-by: Yim Lee <yim_lee@apple.com>
2022-10-04 14:32:54 +09:00
Moritz Lang 552f91cab2 Fix Swift 5.2 Package manifest 2022-10-03 12:08:53 +02:00
Moritz Lang d9717f5de3 Run SwiftFormat 2022-10-03 12:07:08 +02:00
Moritz Lang 6f9aaba8e8 Conditionally compile task-local tests 2022-10-03 11:58:49 +02:00
Moritz Lang 23ea0c2f24 Provide correct fallback log methods 2022-10-03 11:56:02 +02:00
Moritz Lang ebea1c0baa Generate linux tests 2022-10-03 11:53:35 +02:00
Moritz Lang e3fd0e4df6 Only conform metadata providers to Sendable if available 2022-10-03 11:52:12 +02:00
Moritz Lang 96fdafb0b8 Use Baggage fork for Swift 5.0 support 2022-10-03 11:43:31 +02:00
Moritz Lang 921cb5344c Add more examples to proposal 2022-09-30 11:38:53 +02:00
Moritz Lang 9a1f7eb0f5 Make Logger.metadataProvider mutable 2022-09-21 12:25:02 +02:00
Konrad `ktoso` Malawski 2c3ee82e27 minor nitpick, use string interpolation where we can 2022-09-21 09:19:37 +02:00
Moritz Lang 7cbc402e0d Update proposal to latest API 2022-09-20 23:47:04 +02:00
Moritz Lang 3e437856cc Disable metadata provider by passing nil-baggage 2022-09-20 23:47:04 +02:00
Moritz Lang 5e980ddce2 Add global metadata provider to LoggingSystem 2022-09-20 23:47:03 +02:00
Konrad `ktoso` MalawskiandMoritz Lang 4c8caad4d8 Apply suggestions from code review
Co-authored-by: Moritz Lang <hi@slashmo.codes>
2022-09-20 23:47:03 +02:00
Konrad `ktoso` Malawski 5abb878a84 Some additions 2022-09-20 23:47:03 +02:00
Moritz Lang e3db5dc433 Add optional Baggage argument to log methods 2022-09-20 23:47:03 +02:00
Moritz Lang 784405d8c9 Add MetadataProvider struct and multiplex provider 2022-09-20 23:47:03 +02:00
Moritz Lang fa5af66dd8 Extract task-local Baggage within log function 2022-09-20 23:47:03 +02:00
Moritz Lang a4a2505e1f [WIP] Write metadata providers proposal 2022-09-20 23:47:03 +02:00
Moritz Lang 0c569842df [WIP] Add Baggage-powered metadata provider 2022-09-20 23:47:03 +02:00
Moritz Lang ddb59ca90a Add InstrumentationBaggage dependency 2022-09-20 23:47:03 +02:00
Ruslan Kavetsky f7b7977065 Update README.md (#233) 2022-09-17 15:00:35 +09:00
Konrad `ktoso` Malawski ce09fe6dac Undo 5.7 package files, not needed yet (#232)
* Undo 5.7 package files, not needed yet

* no need for xcrun in docs preview script
2022-08-24 12:33:23 +09:00
Konrad `ktoso` Malawski a8e1148aa5 =docc Move to multiple Package.swift files (#231)
* +docc prepare for docc docs

* fix syntax in one of the package files

* ignore package.resolved
2022-08-23 18:29:56 +09:00
Konrad `ktoso` Malawski 483e2bbcdd =docc Make docs use symbol references (#230) 2022-08-23 17:11:11 +09:00
Konrad `ktoso` MalawskiandYim Lee d5bf59c6b2 [docs] Minimal docc setup and landing page (#226)
* [docs] Minimal docc setup and landing page

* move index file

* Update Sources/Logging/Logging.swift

Co-authored-by: Yim Lee <yim_lee@apple.com>

Co-authored-by: Yim Lee <yim_lee@apple.com>
2022-08-23 16:08:28 +09:00
Konrad `ktoso` Malawski 6fe203dc33 [sendable] MetadataValue conformance must be unchecked on 5.6 now 2022-08-15 09:19:49 +09:00
Konrad `ktoso` Malawski 6b0ccb1ca8 [sendable] Sendable conformance checks cause errors on 5.6 but warnings on 5.7 2022-08-15 09:19:49 +09:00
Joseph HeckandKonrad `ktoso` Malawski 8fc79cae9d minimal DocC markdown to order Logger.Levels (#225)
* minimal DocC markdown to order Logger.Levels

Motivation:

When viewed in documentation generated by DocC, the enumeration levels
are ordered alphabetically, removintg the implied ordering in the
source. The written overview of the enum relies on that ordering to make
sense.

Modifications:

Adding a single file that provides structure to Logging/Logger/Levels
within DocC generated documentation.

Result:

When imported into a project that leverages Swift 5.6 (such as Vapor),
the generated documentation for the levels provided by
Logging/Logger/Levels are displayed in the order intended/expected by
the documentation.

* Adding a Swift 5.6 version of Package.swift

Motivation:

Per DocC team, an updated version is required for the DocC changes
to be picked up and reflected in generated dcumentation, even for
upstream projects already using swift 5.6 or later.

Modifications:

Adding Package.Swift@5.6 with the swift version updated.

Result:

Hopefully, documentation updates in DocC generated content will be
reflected.

* Updating linuxmain test generation for <swift5.6

Motivation:

To appease CI, added #if statements into generated LinuxMain
content to handle conditional compilation with Swift 5.6 and later.

Modifications:

Added #if statements to test generating script and re-ran the script

Result:

CI will hopefully pass.

* also guard the LinuxMain file

* Force using test discovery on 5.6+ even though tools version is latest
but LinuxMain exists

* cleanup

* simplify docc links

* formatting revert

* ignore Package-swift5.6.swift from soundness license check

Co-authored-by: Konrad `ktoso` Malawski <konrad_malawski@apple.com>
2022-07-20 14:38:17 +09:00
tomer doron f2e8667d50 adopt sendable (#218)
motivation: adjust to swift 5.6

changes:
* define sendable shims for protocols and structs that may be used in async context
* adjust tests
* add a test to make sure no warning are emitted
2022-07-01 16:38:19 -07:00
tomer doron 9f3731aa55 better abstration for LoggingSystem state (#222)
motivation: prepare for sendable checks

changes:
* abstract the LoggingSystem state into a "boxed" class that handles the locking
* adjust call sites
2022-06-29 11:07:50 -07:00
Guilherme Souza 2bf6215b68 Add binaryscraping/swift-log-supabase to README (#221) 2022-05-10 11:39:59 -07:00
tomer doron 432a93204e ci update (#219)
motivation: 5.6 is out

changes:
* use release version of 5.6
* add docker setup for 5.7 (using nightly for now)
2022-03-16 21:04:07 -07:00
Cory Benfield dc6dd5caaa Add 5.6 nightly CI (#214)
The 5.6 nightly images are available, let's use them.
2022-01-18 10:03:36 -08:00
tomer doron 5db2bc495a update doc generation script (#213)
motivation: source-kitten has changed how its invoked

changes:
* invoke source-kitten with the correct flags
* make location of source-kitten source checkout more robust
2021-12-16 15:18:06 -08:00
Andriy Druk 4e75f88c6a Add Android support (#209) 2021-10-26 16:20:20 -07:00
tomer doron 77192b9e21 add docker setup for 5.5 (#211)
motivation: ci on 5.5

changes: add docker setup for 5.5
2021-10-18 15:15:28 -07:00
tomer doron b172d1ae3d fix jazzy issues on older versions of ubuntu (#210) 2021-10-18 15:03:31 -07:00
34 changed files with 2351 additions and 179 deletions

No files matched your search

+1
View File
@@ -1,4 +1,5 @@
.DS_Store
Package.resolved
/.build
/Packages
/*.xcodeproj
+8 -2
View File
@@ -1,4 +1,4 @@
// swift-tools-version:5.0
// swift-tools-version:5.6
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Logging API open source project
@@ -20,10 +20,16 @@ let package = Package(
products: [
.library(name: "Logging", targets: ["Logging"]),
],
dependencies: [
.package(url: "https://github.com/apple/swift-docc-plugin", from: "1.0.0"),
.package(url: "https://github.com/slashmo/swift-distributed-tracing-baggage", branch: "support/swift-5.0"),
],
targets: [
.target(
name: "Logging",
dependencies: []
dependencies: [
.product(name: "InstrumentationBaggage", package: "swift-distributed-tracing-baggage"),
]
),
.testTarget(
name: "LoggingTests",
+38
View File
@@ -0,0 +1,38 @@
// swift-tools-version:5.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"]),
],
dependencies: [
.package(url: "https://github.com/slashmo/swift-distributed-tracing-baggage", .branch("support/swift-5.0")),
],
targets: [
.target(
name: "Logging",
dependencies: [
.product(name: "InstrumentationBaggage", package: "swift-distributed-tracing-baggage"),
]
),
.testTarget(
name: "LoggingTests",
dependencies: ["Logging"]
),
]
)
+38
View File
@@ -0,0 +1,38 @@
// swift-tools-version:5.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"]),
],
dependencies: [
.package(url: "https://github.com/slashmo/swift-distributed-tracing-baggage", .branch("support/swift-5.0")),
],
targets: [
.target(
name: "Logging",
dependencies: [
.product(name: "InstrumentationBaggage", package: "swift-distributed-tracing-baggage"),
]
),
.testTarget(
name: "LoggingTests",
dependencies: ["Logging"]
),
]
)
+38
View File
@@ -0,0 +1,38 @@
// swift-tools-version:5.2
//===----------------------------------------------------------------------===//
//
// 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"]),
],
dependencies: [
.package(url: "https://github.com/slashmo/swift-distributed-tracing-baggage", .branch("support/swift-5.0")),
],
targets: [
.target(
name: "Logging",
dependencies: [
.product(name: "InstrumentationBaggage", package: "swift-distributed-tracing-baggage"),
]
),
.testTarget(
name: "LoggingTests",
dependencies: ["Logging"]
),
]
)
+38
View File
@@ -0,0 +1,38 @@
// swift-tools-version:5.3
//===----------------------------------------------------------------------===//
//
// 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"]),
],
dependencies: [
.package(url: "https://github.com/slashmo/swift-distributed-tracing-baggage", .branch("support/swift-5.0")),
],
targets: [
.target(
name: "Logging",
dependencies: [
.product(name: "InstrumentationBaggage", package: "swift-distributed-tracing-baggage"),
]
),
.testTarget(
name: "LoggingTests",
dependencies: ["Logging"]
),
]
)
+38
View File
@@ -0,0 +1,38 @@
// swift-tools-version:5.4
//===----------------------------------------------------------------------===//
//
// 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"]),
],
dependencies: [
.package(url: "https://github.com/slashmo/swift-distributed-tracing-baggage", .branch("support/swift-5.0")),
],
targets: [
.target(
name: "Logging",
dependencies: [
.product(name: "InstrumentationBaggage", package: "swift-distributed-tracing-baggage"),
]
),
.testTarget(
name: "LoggingTests",
dependencies: ["Logging"]
),
]
)
+38
View File
@@ -0,0 +1,38 @@
// swift-tools-version:5.5
//===----------------------------------------------------------------------===//
//
// 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"]),
],
dependencies: [
.package(url: "https://github.com/slashmo/swift-distributed-tracing-baggage", branch: "support/swift-5.0"),
],
targets: [
.target(
name: "Logging",
dependencies: [
.product(name: "InstrumentationBaggage", package: "swift-distributed-tracing-baggage"),
]
),
.testTarget(
name: "LoggingTests",
dependencies: ["Logging"]
),
]
)
+2 -1
View File
@@ -84,6 +84,7 @@ As the API has just launched, not many implementations exist yet. If you are int
| [luoxiu/LogDog](https://github.com/luoxiu/LogDog) | user-friendly logging with sinks and appenders |
| [ShivaHuang/swift-log-SwiftyBeaver](https://github.com/ShivaHuang/swift-log-SwiftyBeaver) | a logging backend for printing colored logging to Xcode console / file, or sending encrypted logging to [SwiftyBeaver](https://swiftybeaver.com) platform. |
| [Apodini/swift-log-elk](https://github.com/Apodini/swift-log-elk) | a logging backend that formats, caches and sends log data to [elastic/logstash](https://github.com/elastic/logstash) |
| [binaryscraping/swift-log-supabase](https://github.com/binaryscraping/swift-log-supabase) | a logging backend that sends log entries to [Supabase](https://github.com/supabase/supbase). |
| Your library? | [Get in touch!](https://forums.swift.org/c/server) |
## What is an API package?
@@ -156,7 +157,7 @@ A `LogHandler` or logging backend implementation is anything that conforms to th
```swift
public protocol LogHandler {
func log(level: Logger.Level, message: Logger.Message, metadata: Logger.Metadata?, file: String, function: String, line: UInt)
func log(level: Logger.Level, message: Logger.Message, metadata: Logger.Metadata?, source: String, file: String, function: String, line: UInt)
subscript(metadataKey _: String) -> Logger.Metadata.Value? { get set }
+13
View File
@@ -0,0 +1,13 @@
# ``Logging/Logger/Level``
## Topics
### Log levels
- ``trace``
- ``debug``
- ``info``
- ``notice``
- ``warning``
- ``error``
- ``critical``
+30
View File
@@ -0,0 +1,30 @@
# ``Logging``
A Logging API for Swift.
## Getting Started
If you have a server-side Swift application, or maybe a cross-platform (for example Linux & macOS) app/library, and you would like to log, we think targeting this logging API package is a great idea. Below you'll find all you need to know to get started.
### Log handler implementations
This package offers the common Logging API as well as a very simple stdout log handler.
In a real system or application, you will want to use one of the many community maintained log handler implementations.
Please refer to the [complete list of community maintained logging backend implementations](https://github.com/apple/swift-log#selecting-a-logging-backend-implementation-applications-only).
## Topics
### Logging API
- ``Logger``
- ``LoggingSystem``
### Log Handlers
- ``LogHandler``
- ``MultiplexLogHandler``
- ``StreamLogHandler``
- ``SwiftLogNoOpLogHandler``
+19 -10
View File
@@ -28,9 +28,7 @@
#if canImport(WASILibc)
// No locking on WASILibc
#else
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
#elseif canImport(Darwin)
import Darwin
#elseif os(Windows)
import WinSDK
@@ -138,7 +136,9 @@ extension Lock {
/// one used by NIO. On Windows, the lock is based on the substantially similar
/// `SRWLOCK` type.
internal final class ReadWriteLock {
#if os(Windows)
#if canImport(WASILibc)
// WASILibc is single threaded, provides no locks
#elseif os(Windows)
fileprivate let rwlock: UnsafeMutablePointer<SRWLOCK> =
UnsafeMutablePointer.allocate(capacity: 1)
fileprivate var shared: Bool = true
@@ -149,7 +149,9 @@ internal final class ReadWriteLock {
/// Create a new lock.
public init() {
#if os(Windows)
#if canImport(WASILibc)
// WASILibc is single threaded, provides no locks
#elseif os(Windows)
InitializeSRWLock(self.rwlock)
#else
let err = pthread_rwlock_init(self.rwlock, nil)
@@ -158,7 +160,9 @@ internal final class ReadWriteLock {
}
deinit {
#if os(Windows)
#if canImport(WASILibc)
// WASILibc is single threaded, provides no locks
#elseif os(Windows)
// SRWLOCK does not need to be free'd
#else
let err = pthread_rwlock_destroy(self.rwlock)
@@ -172,7 +176,9 @@ internal final class ReadWriteLock {
/// Whenever possible, consider using `withReaderLock` instead of this
/// method and `unlock`, to simplify lock handling.
public func lockRead() {
#if os(Windows)
#if canImport(WASILibc)
// WASILibc is single threaded, provides no locks
#elseif os(Windows)
AcquireSRWLockShared(self.rwlock)
self.shared = true
#else
@@ -186,7 +192,9 @@ internal final class ReadWriteLock {
/// Whenever possible, consider using `withWriterLock` instead of this
/// method and `unlock`, to simplify lock handling.
public func lockWrite() {
#if os(Windows)
#if canImport(WASILibc)
// WASILibc is single threaded, provides no locks
#elseif os(Windows)
AcquireSRWLockExclusive(self.rwlock)
self.shared = false
#else
@@ -201,7 +209,9 @@ internal final class ReadWriteLock {
/// instead of this method and `lockRead` and `lockWrite`, to simplify lock
/// handling.
public func unlock() {
#if os(Windows)
#if canImport(WASILibc)
// WASILibc is single threaded, provides no locks
#elseif os(Windows)
if self.shared {
ReleaseSRWLockShared(self.rwlock)
} else {
@@ -261,4 +271,3 @@ extension ReadWriteLock {
try self.withWriterLock(body)
}
}
#endif
+38 -3
View File
@@ -15,14 +15,14 @@
/// A `LogHandler` is an implementation of a logging backend.
///
/// This type is an implementation detail and should not normally be used, unless implementing your own logging backend.
/// To use the SwiftLog API, please refer to the documentation of `Logger`.
/// To use the SwiftLog API, please refer to the documentation of ``Logger``.
///
/// # Implementation requirements
///
/// To implement your own `LogHandler` you should respect a few requirements that are necessary so applications work
/// as expected regardless of the selected `LogHandler` implementation.
///
/// - The `LogHandler` must be a `struct`.
/// - The ``LogHandler`` must be a `struct`.
/// - The metadata and `logLevel` properties must be implemented so that setting them on a `Logger` does not affect
/// other `Logger`s.
///
@@ -113,7 +113,7 @@
/// Please note that the above `LogHandler` will still pass the 'log level is a value' test above it iff the global log
/// level has not been overridden. And most importantly it passes the requirement listed above: A change to the log
/// level on one `Logger` should not affect the log level of another `Logger` variable.
public protocol LogHandler {
public protocol LogHandler: _SwiftLogSendableLogHandler {
/// This method is called when a `LogHandler` 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.
@@ -126,6 +126,18 @@ public protocol LogHandler {
/// - file: The file the log message was emitted from.
/// - function: The function the log line was emitted from.
/// - line: The line the log message was emitted from.
func log(level: Logger.Level,
message: Logger.Message,
metadata: Logger.Metadata?,
baggage: Logger.BaggageStrategy,
source: String,
file: String,
function: String,
line: UInt)
/// SwiftLog 1.4 compatibility method. Please do _not_ implement, implement
/// `log(level:message:metadata:baggage:source:file:function:line:)` instead.
@available(*, deprecated, renamed: "log(level:message:metadata:baggage:source:file:function:line:)")
func log(level: Logger.Level,
message: Logger.Message,
metadata: Logger.Metadata?,
@@ -168,15 +180,30 @@ extension LogHandler {
public func log(level: Logger.Level,
message: Logger.Message,
metadata: Logger.Metadata?,
baggage: Logger.BaggageStrategy,
source: String,
file: String,
function: String,
line: UInt) {
/// This implementation drops the `baggage` parameter
self.log(level: level, message: message, metadata: metadata, source: source, file: file, function: function, line: line)
}
@available(*, deprecated, renamed: "log(level:message:metadata:baggage:source:file:function:line:)")
public func log(level: Logger.Level,
message: Logger.Message,
metadata: Logger.Metadata?,
source: String,
file: String,
function: String,
line: UInt) {
/// This implementation drops the `source` parameter
self.log(level: level, message: message, metadata: metadata, file: file, function: function, line: line)
}
@available(*, deprecated, renamed: "log(level:message:metadata:source:file:function:line:)")
public func log(level: Logging.Logger.Level, message: Logging.Logger.Message, metadata: Logging.Logger.Metadata?, file: String, function: String, line: UInt) {
/// This implementation obtains the source from the `file` parameter
self.log(level: level,
message: message,
metadata: metadata,
@@ -186,3 +213,11 @@ extension LogHandler {
line: line)
}
}
// MARK: - Sendable support helpers
#if compiler(>=5.6)
@preconcurrency public protocol _SwiftLogSendableLogHandler: Sendable {}
#else
public protocol _SwiftLogSendableLogHandler {}
#endif
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -22,7 +22,7 @@ import XCTest
/// Do NOT edit this file directly as it will be regenerated automatically when needed.
///
#if os(Linux) || os(FreeBSD) || os(Windows)
#if os(Linux) || os(FreeBSD) || os(Windows) || os(Android)
@testable import LoggingTests
XCTMain([
+1 -1
View File
@@ -63,7 +63,7 @@ private struct OldSchoolLogHandler: LogHandler {
let recorder: Recorder
func make(label: String) -> LogHandler {
return TestLogHandler(label: label, config: self.config, recorder: self.recorder)
return TestLogHandler(label: label, config: self.config, recorder: self.recorder, metadataProvider: LoggingSystem.metadataProvider)
}
func log(level: Logger.Level, message: Logger.Message, metadata: Logger.Metadata?, file: String, function: String, line: UInt) {
+3 -3
View File
@@ -18,7 +18,7 @@ class GlobalLoggerTest: XCTestCase {
func test1() throws {
// bootstrap with our test logging impl
let logging = TestLogging()
LoggingSystem.bootstrapInternal(logging.make)
LoggingSystem.bootstrapInternal(logging.make(label:metadataProvider:))
// change test logging config to log traces and above
logging.config.set(value: Logger.Level.debug)
@@ -45,7 +45,7 @@ class GlobalLoggerTest: XCTestCase {
func test2() throws {
// bootstrap with our test logging impl
let logging = TestLogging()
LoggingSystem.bootstrapInternal(logging.make)
LoggingSystem.bootstrapInternal(logging.make(label:metadataProvider:))
// change test logging config to log errors and above
logging.config.set(value: Logger.Level.error)
@@ -72,7 +72,7 @@ class GlobalLoggerTest: XCTestCase {
func test3() throws {
// bootstrap with our test logging impl
let logging = TestLogging()
LoggingSystem.bootstrapInternal(logging.make)
LoggingSystem.bootstrapInternal(logging.make(label:metadataProvider:))
// change test logging config
logging.config.set(value: .warning)
+2 -2
View File
@@ -18,7 +18,7 @@ class LocalLoggerTest: XCTestCase {
func test1() throws {
// bootstrap with our test logging impl
let logging = TestLogging()
LoggingSystem.bootstrapInternal(logging.make)
LoggingSystem.bootstrapInternal(logging.make(label:metadataProvider:))
// change test logging config to log traces and above
logging.config.set(value: Logger.Level.debug)
@@ -46,7 +46,7 @@ class LocalLoggerTest: XCTestCase {
func test2() throws {
// bootstrap with our test logging impl
let logging = TestLogging()
LoggingSystem.bootstrapInternal(logging.make)
LoggingSystem.bootstrapInternal(logging.make(label:metadataProvider:))
// change test logging config to log errors and above
logging.config.set(value: Logger.Level.error)
@@ -44,6 +44,15 @@ extension LoggingTest {
("testLogsEmittedFromSubdirectoryGetCorrectModuleInNewerSwifts", testLogsEmittedFromSubdirectoryGetCorrectModuleInNewerSwifts),
("testLogMessageWithStringInterpolation", testLogMessageWithStringInterpolation),
("testLoggingAString", testLoggingAString),
("testLoggingCallsMetadataProviderWithTaskLocalBaggage", testLoggingCallsMetadataProviderWithTaskLocalBaggage),
("testLoggingCallsMetadataProviderWithExplicitlyPassedBaggage", testLoggingCallsMetadataProviderWithExplicitlyPassedBaggage),
("testLoggingMergesOneOffMetadataWithProvidedMetadataFromTaskLocalBaggage", testLoggingMergesOneOffMetadataWithProvidedMetadataFromTaskLocalBaggage),
("testLoggingMergesOneOffMetadataWithProvidedMetadataFromExplicitlyPassedBaggage", testLoggingMergesOneOffMetadataWithProvidedMetadataFromExplicitlyPassedBaggage),
("testLoggingPrefersExplicitBaggageOverTaskLocal", testLoggingPrefersExplicitBaggageOverTaskLocal),
("testLoggingWithExplicitlyPassedNilBaggageDoesNotPickUpTaskLocalBaggage", testLoggingWithExplicitlyPassedNilBaggageDoesNotPickUpTaskLocalBaggage),
("testMultiplexMetadataProviderMergesInSpecifiedOrder", testMultiplexMetadataProviderMergesInSpecifiedOrder),
("testLoggerWithoutFactoryOverrideDefaultsToUsingLoggingSystemMetadataProvider", testLoggerWithoutFactoryOverrideDefaultsToUsingLoggingSystemMetadataProvider),
("testLoggerWithFactoryOverrideDefaultsToUsingLoggingSystemMetadataProvider", testLoggerWithFactoryOverrideDefaultsToUsingLoggingSystemMetadataProvider),
("testMultiplexerIsValue", testMultiplexerIsValue),
("testLoggerWithGlobalOverride", testLoggerWithGlobalOverride),
("testLogLevelCases", testLogLevelCases),
+268 -24
View File
@@ -1,3 +1,4 @@
import InstrumentationBaggage
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Logging API open source project
@@ -26,7 +27,7 @@ class LoggingTest: XCTestCase {
func testAutoclosure() throws {
// bootstrap with our test logging impl
let logging = TestLogging()
LoggingSystem.bootstrapInternal(logging.make)
LoggingSystem.bootstrapInternal(logging.make(label:metadataProvider:))
var logger = Logger(label: "test")
logger.logLevel = .info
@@ -230,7 +231,7 @@ class LoggingTest: XCTestCase {
func testDictionaryMetadata() {
let testLogging = TestLogging()
LoggingSystem.bootstrapInternal(testLogging.make)
LoggingSystem.bootstrapInternal(testLogging.make(label:metadataProvider:))
var logger = Logger(label: "\(#function)")
logger[metadataKey: "foo"] = ["bar": "buz"]
@@ -246,7 +247,7 @@ class LoggingTest: XCTestCase {
func testListMetadata() {
let testLogging = TestLogging()
LoggingSystem.bootstrapInternal(testLogging.make)
LoggingSystem.bootstrapInternal(testLogging.make(label:metadataProvider:))
var logger = Logger(label: "\(#function)")
logger[metadataKey: "foo"] = ["bar", "buz"]
@@ -262,7 +263,7 @@ class LoggingTest: XCTestCase {
// Example of custom "box" which may be used to implement "render at most once" semantics
// Not thread-safe, thus should not be shared across threads.
internal class LazyMetadataBox: CustomStringConvertible {
internal final class LazyMetadataBox: CustomStringConvertible {
private var makeValue: (() -> String)?
private var _value: String?
@@ -289,7 +290,7 @@ class LoggingTest: XCTestCase {
func testStringConvertibleMetadata() {
let testLogging = TestLogging()
LoggingSystem.bootstrapInternal(testLogging.make)
LoggingSystem.bootstrapInternal(testLogging.make(label:metadataProvider:))
var logger = Logger(label: "\(#function)")
logger[metadataKey: "foo"] = .stringConvertible("raw-string")
@@ -309,7 +310,7 @@ class LoggingTest: XCTestCase {
func testAutoClosuresAreNotForcedUnlessNeeded() {
let testLogging = TestLogging()
LoggingSystem.bootstrapInternal(testLogging.make)
LoggingSystem.bootstrapInternal(testLogging.make(label:metadataProvider:))
var logger = Logger(label: "\(#function)")
logger.logLevel = .error
@@ -323,7 +324,7 @@ class LoggingTest: XCTestCase {
func testLocalMetadata() {
let testLogging = TestLogging()
LoggingSystem.bootstrapInternal(testLogging.make)
LoggingSystem.bootstrapInternal(testLogging.make(label:metadataProvider:))
var logger = Logger(label: "\(#function)")
logger.info("hello world!", metadata: ["foo": "bar"])
@@ -364,7 +365,7 @@ class LoggingTest: XCTestCase {
func testAllLogLevelsExceptCriticalCanBeBlocked() {
let testLogging = TestLogging()
LoggingSystem.bootstrapInternal(testLogging.make)
LoggingSystem.bootstrapInternal(testLogging.make(label:metadataProvider:))
var logger = Logger(label: "\(#function)")
logger.logLevel = .critical
@@ -388,7 +389,7 @@ class LoggingTest: XCTestCase {
func testAllLogLevelsWork() {
let testLogging = TestLogging()
LoggingSystem.bootstrapInternal(testLogging.make)
LoggingSystem.bootstrapInternal(testLogging.make(label:metadataProvider:))
var logger = Logger(label: "\(#function)")
logger.logLevel = .trace
@@ -412,7 +413,7 @@ class LoggingTest: XCTestCase {
func testAllLogLevelByFunctionRefWithSource() {
let testLogging = TestLogging()
LoggingSystem.bootstrapInternal(testLogging.make)
LoggingSystem.bootstrapInternal(testLogging.make(label:metadataProvider:))
var logger = Logger(label: "\(#function)")
logger.logLevel = .trace
@@ -444,7 +445,7 @@ class LoggingTest: XCTestCase {
func testAllLogLevelByFunctionRefWithoutSource() {
let testLogging = TestLogging()
LoggingSystem.bootstrapInternal(testLogging.make)
LoggingSystem.bootstrapInternal(testLogging.make(label:metadataProvider:))
var logger = Logger(label: "\(#function)")
logger.logLevel = .trace
@@ -461,18 +462,18 @@ class LoggingTest: XCTestCase {
trace("yes: trace", [:], #fileID, #function, #line)
debug("yes: debug", [:], #fileID, #function, #line)
info("yes: info", [:], #fileID, #function, #line)
notice("yes: notice", [:], #fileID, #function, #line)
notice("yes: notice", [:], #fileID, #function, #line)
warning("yes: warning", [:], #fileID, #function, #line)
error("yes: error", [:], #fileID, #function, #line)
critical("yes: critical", [:], #fileID, #function, #line)
#else
trace("yes: trace", [:], #file, #function, #line)
debug("yes: debug", [:], #file, #function, #line)
info("yes: info", [:], #file, #function, #line)
notice("yes: notice", [:], #file, #function, #line)
warning("yes: warning", [:], #file, #function, #line)
error("yes: error", [:], #file, #function, #line)
critical("yes: critical", [:], #file, #function, #line)
trace("yes: trace", [:], nil, #file, #function, #line)
debug("yes: debug", [:], nil, #file, #function, #line)
info("yes: info", [:], nil, #file, #function, #line)
notice("yes: notice", [:], nil, #file, #function, #line)
warning("yes: warning", [:], nil, #file, #function, #line)
error("yes: error", [:], nil, #file, #function, #line)
critical("yes: critical", [:], nil, #file, #function, #line)
#endif
testLogging.history.assertExist(level: .trace, message: "yes: trace")
@@ -486,7 +487,7 @@ class LoggingTest: XCTestCase {
func testLogsEmittedFromSubdirectoryGetCorrectModuleInNewerSwifts() {
let testLogging = TestLogging()
LoggingSystem.bootstrapInternal(testLogging.make)
LoggingSystem.bootstrapInternal(testLogging.make(label:metadataProvider:))
var logger = Logger(label: "\(#function)")
logger.logLevel = .trace
@@ -510,7 +511,7 @@ class LoggingTest: XCTestCase {
func testLogMessageWithStringInterpolation() {
let testLogging = TestLogging()
LoggingSystem.bootstrapInternal(testLogging.make)
LoggingSystem.bootstrapInternal(testLogging.make(label:metadataProvider:))
var logger = Logger(label: "\(#function)")
logger.logLevel = .debug
@@ -523,7 +524,7 @@ class LoggingTest: XCTestCase {
func testLoggingAString() {
let testLogging = TestLogging()
LoggingSystem.bootstrapInternal(testLogging.make)
LoggingSystem.bootstrapInternal(testLogging.make(label:metadataProvider:))
var logger = Logger(label: "\(#function)")
logger.logLevel = .debug
@@ -537,6 +538,237 @@ class LoggingTest: XCTestCase {
testLogging.history.assertExist(level: .debug, message: "hello world!")
}
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
func testLoggingCallsMetadataProviderWithTaskLocalBaggage() throws {
#if swift(>=5.5) && canImport(_Concurrency)
let logging = TestLogging()
LoggingSystem.bootstrapInternal(logging.make(label:metadataProvider:))
var logger = Logger(label: #function, metadataProvider: .init { baggage in
guard let baggage = baggage, let testID = baggage[TestIDKey.self] else {
XCTFail("Expected Baggage to be passed along to the metadata provider.")
return nil
}
return ["provider": .string(testID)]
})
logger.logLevel = .trace
var baggage = Baggage.topLevel
baggage[TestIDKey.self] = "42"
Baggage.$current.withValue(baggage) {
logger.trace("test")
logger.debug("test")
logger.info("test")
logger.notice("test")
logger.warning("test")
logger.error("test")
logger.critical("test")
}
logging.history.assertExist(level: .trace, message: "test", metadata: ["provider": "42"])
logging.history.assertExist(level: .debug, message: "test", metadata: ["provider": "42"])
logging.history.assertExist(level: .info, message: "test", metadata: ["provider": "42"])
logging.history.assertExist(level: .notice, message: "test", metadata: ["provider": "42"])
logging.history.assertExist(level: .warning, message: "test", metadata: ["provider": "42"])
logging.history.assertExist(level: .error, message: "test", metadata: ["provider": "42"])
logging.history.assertExist(level: .critical, message: "test", metadata: ["provider": "42"])
enum TestIDKey: BaggageKey {
typealias Value = String
}
#endif
}
func testLoggingCallsMetadataProviderWithExplicitlyPassedBaggage() throws {
let logging = TestLogging()
LoggingSystem.bootstrapInternal(logging.make(label:metadataProvider:))
var logger = Logger(label: #function, metadataProvider: .init { baggage in
guard let baggage = baggage, let testID = baggage[TestIDKey.self] else {
XCTFail("Expected Baggage to be passed along to the metadata provider.")
return nil
}
return ["provider": .string(testID)]
})
logger.logLevel = .trace
var baggage = Baggage.topLevel
baggage[TestIDKey.self] = "42"
logger.trace("test", baggage: baggage)
logger.debug("test", baggage: baggage)
logger.info("test", baggage: baggage)
logger.notice("test", baggage: baggage)
logger.warning("test", baggage: baggage)
logger.error("test", baggage: baggage)
logger.critical("test", baggage: baggage)
logging.history.assertExist(level: .trace, message: "test", metadata: ["provider": "42"])
logging.history.assertExist(level: .debug, message: "test", metadata: ["provider": "42"])
logging.history.assertExist(level: .info, message: "test", metadata: ["provider": "42"])
logging.history.assertExist(level: .notice, message: "test", metadata: ["provider": "42"])
logging.history.assertExist(level: .warning, message: "test", metadata: ["provider": "42"])
logging.history.assertExist(level: .error, message: "test", metadata: ["provider": "42"])
logging.history.assertExist(level: .critical, message: "test", metadata: ["provider": "42"])
enum TestIDKey: BaggageKey {
typealias Value = String
}
}
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
func testLoggingMergesOneOffMetadataWithProvidedMetadataFromTaskLocalBaggage() throws {
#if swift(>=5.5) && canImport(_Concurrency)
let logging = TestLogging()
LoggingSystem.bootstrapInternal(logging.make(label:metadataProvider:))
let logger = Logger(label: #function, metadataProvider: .init { _ in
[
"common": "provider",
"provider": "42",
]
})
Baggage.$current.withValue(.topLevel) {
logger.log(level: .info, "test", metadata: ["one-off": "42", "common": "one-off"])
}
logging.history.assertExist(level: .info,
message: "test",
metadata: ["common": "one-off", "one-off": "42", "provider": "42"])
#endif
}
func testLoggingMergesOneOffMetadataWithProvidedMetadataFromExplicitlyPassedBaggage() throws {
let logging = TestLogging()
LoggingSystem.bootstrapInternal(logging.make(label:metadataProvider:))
let logger = Logger(label: #function, metadataProvider: .init { _ in
[
"common": "provider",
"provider": "42",
]
})
logger.log(level: .info, "test", metadata: ["one-off": "42", "common": "one-off"], baggage: .explicitlyPassed(.topLevel))
logging.history.assertExist(level: .info,
message: "test",
metadata: ["common": "one-off", "one-off": "42", "provider": "42"])
}
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
func testLoggingPrefersExplicitBaggageOverTaskLocal() {
#if swift(>=5.5) && canImport(_Concurrency)
let logging = TestLogging()
LoggingSystem.bootstrapInternal(logging.make(label:metadataProvider:))
var logger = Logger(label: #function, metadataProvider: .init { baggage in
guard let baggage = baggage, let testID = baggage[TestIDKey.self] else {
XCTFail("Expected Baggage to be passed along to the metadata provider.")
return nil
}
return ["provider": .string(testID)]
})
logger.logLevel = .trace
var taskLocalBaggage = Baggage.topLevel
taskLocalBaggage[TestIDKey.self] = "task-local"
var explicitBaggage = Baggage.topLevel
explicitBaggage[TestIDKey.self] = "explicit"
Baggage.$current.withValue(taskLocalBaggage) {
logger.trace("test", metadata: ["one-off": "42"], baggage: explicitBaggage)
logger.debug("test", metadata: ["one-off": "42"], baggage: explicitBaggage)
logger.info("test", metadata: ["one-off": "42"], baggage: explicitBaggage)
logger.notice("test", metadata: ["one-off": "42"], baggage: explicitBaggage)
logger.warning("test", metadata: ["one-off": "42"], baggage: explicitBaggage)
logger.error("test", metadata: ["one-off": "42"], baggage: explicitBaggage)
logger.critical("test", metadata: ["one-off": "42"], baggage: explicitBaggage)
}
logging.history.assertExist(level: .trace, message: "test", metadata: ["one-off": "42", "provider": "explicit"])
logging.history.assertExist(level: .debug, message: "test", metadata: ["one-off": "42", "provider": "explicit"])
logging.history.assertExist(level: .info, message: "test", metadata: ["one-off": "42", "provider": "explicit"])
logging.history.assertExist(level: .notice, message: "test", metadata: ["one-off": "42", "provider": "explicit"])
logging.history.assertExist(level: .warning, message: "test", metadata: ["one-off": "42", "provider": "explicit"])
logging.history.assertExist(level: .error, message: "test", metadata: ["one-off": "42", "provider": "explicit"])
logging.history.assertExist(level: .critical, message: "test", metadata: ["one-off": "42", "provider": "explicit"])
enum TestIDKey: BaggageKey {
typealias Value = String
}
#endif
}
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
func testLoggingWithExplicitlyPassedNilBaggageDoesNotPickUpTaskLocalBaggage() {
#if swift(>=5.5) && canImport(_Concurrency)
let logging = TestLogging()
LoggingSystem.bootstrapInternal(logging.make(label:metadataProvider:))
let logger = Logger(label: #function, metadataProvider: .init { baggage in
XCTAssertNil(baggage)
return ["provider": .string("42")]
})
Baggage.$current.withValue(.topLevel) {
logger.log(level: .info, "test", baggage: .ignore)
}
logging.history.assertExist(level: .info, message: "test", metadata: ["provider": "42"])
#endif
}
func testMultiplexMetadataProviderMergesInSpecifiedOrder() {
let logging = TestLogging()
let providerA = Logger.MetadataProvider { _ in ["provider": "a", "a": "foo"] }
let providerB = Logger.MetadataProvider { _ in ["provider": "b", "b": "bar"] }
let logger = Logger(label: #function,
factory: { label in
logging.make(label: label, metadataProvider: .multiplex([providerA, providerB]))
})
logger.log(level: .info, "test", metadata: ["one-off": "42"])
logging.history.assertExist(level: .info,
message: "test",
metadata: ["provider": "b", "a": "foo", "b": "bar", "one-off": "42"])
}
func testLoggerWithoutFactoryOverrideDefaultsToUsingLoggingSystemMetadataProvider() {
let logging = TestLogging()
LoggingSystem.bootstrapInternal { label in
logging.make(label: label, metadataProvider: .init({ _ in ["provider": "42"] }))
}
let logger = Logger(label: #function)
logger.log(level: .info, "test", metadata: ["one-off": "42"])
logging.history.assertExist(level: .info,
message: "test",
metadata: ["provider": "42", "one-off": "42"])
}
func testLoggerWithFactoryOverrideDefaultsToUsingLoggingSystemMetadataProvider() {
let logging = TestLogging()
LoggingSystem.bootstrapInternal(
metadataProvider: .init({ _ in ["provider": "42"] }),
logging.make(label:metadataProvider:))
let logger = Logger(label: #function, factory: logging.make(label:metadataProvider:))
logger.log(level: .info, "test", metadata: ["one-off": "42"])
logging.history.assertExist(level: .info,
message: "test",
metadata: ["provider": "42", "one-off": "42"])
}
func testMultiplexerIsValue() {
let multi = MultiplexLogHandler([StreamLogHandler.standardOutput(label: "x"), StreamLogHandler.standardOutput(label: "y")])
LoggingSystem.bootstrapInternal { _ in
@@ -806,7 +1038,7 @@ class LoggingTest: XCTestCase {
}
}
func withWriteReadFDsAndReadBuffer(_ body: (UnsafeMutablePointer<FILE>, CInt, UnsafeMutablePointer<Int8>) -> Void) {
func withWriteReadFDsAndReadBuffer(_ body: (CFilePointer, CInt, UnsafeMutablePointer<Int8>) -> Void) {
var fds: [Int32] = [-1, -1]
#if os(Windows)
fds.withUnsafeMutableBufferPointer {
@@ -863,7 +1095,7 @@ class LoggingTest: XCTestCase {
}
// bootstrap with our test logging impl
let logging = TestLogging()
LoggingSystem.bootstrapInternal(logging.make)
LoggingSystem.bootstrapInternal(logging.make(label:metadataProvider:))
var logger = Logger(label: "test")
logger.logLevel = .error
@@ -889,3 +1121,15 @@ extension Logger {
}
#endif
}
// Sendable
#if compiler(>=5.6)
// used to test logging metadata which requires Sendable conformance
// @unchecked Sendable since manages it own state
extension LoggingTest.LazyMetadataBox: @unchecked Sendable {}
// used to test logging stream which requires Sendable conformance
// @unchecked Sendable since manages it own state
extension LoggingTest.InterceptStream: @unchecked Sendable {}
#endif
+1 -1
View File
@@ -19,7 +19,7 @@ class MDCTest: XCTestCase {
func test1() throws {
// bootstrap with our test logger
let logging = TestLogging()
LoggingSystem.bootstrapInternal(logging.make)
LoggingSystem.bootstrapInternal(logging.make(label:metadataProvider:))
// run the program
MDC.global["foo"] = "bar"
+65 -19
View File
@@ -13,6 +13,7 @@
//===----------------------------------------------------------------------===//
import Foundation
@testable import Logging
import InstrumentationBaggage
import XCTest
#if os(Windows)
import WinSDK
@@ -23,7 +24,19 @@ internal struct TestLogging {
private let recorder = Recorder() // shared among loggers
func make(label: String) -> LogHandler {
return TestLogHandler(label: label, config: self.config, recorder: self.recorder)
return TestLogHandler(
label: label,
config: self.config,
recorder: self.recorder,
metadataProvider: LoggingSystem.metadataProvider)
}
func make(label: String, metadataProvider: Logger.MetadataProvider?) -> LogHandler {
return TestLogHandler(
label: label,
config: self.config,
recorder: self.recorder,
metadataProvider: metadataProvider)
}
var config: Config { return self._config }
@@ -31,23 +44,53 @@ internal struct TestLogging {
}
internal struct TestLogHandler: LogHandler {
private let logLevelLock = NSLock()
private let metadataLock = NSLock()
private let recorder: Recorder
private let config: Config
private var logger: Logger // the actual logger
let label: String
init(label: String, config: Config, recorder: Recorder) {
private let metadataProvider: Logger.MetadataProvider?
init(label: String, config: Config, recorder: Recorder, metadataProvider: Logger.MetadataProvider?) {
self.label = label
self.config = config
self.recorder = recorder
self.logger = Logger(label: "test", StreamLogHandler.standardOutput(label: label))
self.logger = Logger(label: "test", StreamLogHandler.standardOutput(label: label, metadataProvider: nil))
self.logger.logLevel = .debug
self.metadataProvider = metadataProvider
}
func log(level: Logger.Level, message: Logger.Message, metadata: Logger.Metadata?, source: String, file: String, function: String, line: UInt) {
let metadata = (self._metadataSet ? self.metadata : MDC.global.metadata).merging(metadata ?? [:], uniquingKeysWith: { _, new in new })
func log(level: Logger.Level,
message: Logger.Message,
metadata explicitMetadata: Logger.Metadata?,
baggage whereIsTheBaggage: Logger.BaggageStrategy,
source: String,
file: String, function: String, line: UInt) {
var baggage: Baggage?
switch whereIsTheBaggage {
case .explicitlyPassed(let b):
baggage = b
case .taskLocal:
#if swift(>=5.5) && canImport(_Concurrency)
if #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) {
baggage = .current
} else {
baggage = nil
}
#else
baggage = nil
#endif
case .ignore:
baggage = nil
}
var metadata = metadataProvider?.provideMetadata(from: baggage) ?? [:]
metadata = metadata.merging(
(self._metadataSet ? self.metadata : MDC.global.metadata).merging(metadata ?? [:], uniquingKeysWith: { _, new in new }),
uniquingKeysWith: { _, new in new })
metadata = metadata.merging(
explicitMetadata ?? [:], uniquingKeysWith: { _, new in new })
self.logger.log(level: level, message, metadata: metadata, source: source, file: file, function: function, line: line)
self.recorder.record(level: level, metadata: metadata, message: message, source: source)
}
@@ -56,10 +99,10 @@ internal struct TestLogHandler: LogHandler {
var logLevel: Logger.Level {
get {
// get from config unless set
return self.logLevelLock.withLock { self._logLevel } ?? self.config.get(key: self.label)
return self._logLevel ?? self.config.get(key: self.label)
}
set {
self.logLevelLock.withLock { self._logLevel = newValue }
self._logLevel = newValue
}
}
@@ -72,26 +115,20 @@ internal struct TestLogHandler: LogHandler {
public var metadata: Logger.Metadata {
get {
// return self.logger.metadata
return self.metadataLock.withLock { self._metadata }
return self._metadata
}
set {
// self.logger.metadata = newValue
self.metadataLock.withLock { self._metadata = newValue }
self._metadata = newValue
}
}
// TODO: would be nice to delegate to local copy of logger but StdoutLogger is a reference type. why?
subscript(metadataKey metadataKey: Logger.Metadata.Key) -> Logger.Metadata.Value? {
get {
// return self.logger[metadataKey: metadataKey]
return self.metadataLock.withLock { self._metadata[metadataKey] }
return self._metadata[metadataKey]
}
set {
// return logger[metadataKey: metadataKey] = newValue
self.metadataLock.withLock {
self._metadata[metadataKey] = newValue
}
self._metadata[metadataKey] = newValue
}
}
}
@@ -342,3 +379,12 @@ internal struct TestLibrary {
}
}
}
// Sendable
#if compiler(>=5.6)
extension TestLogHandler: @unchecked Sendable {}
extension Recorder: @unchecked Sendable {}
extension Config: @unchecked Sendable {}
extension MDC: @unchecked Sendable {}
#endif
+43
View File
@@ -0,0 +1,43 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Logging API open source project
//
// Copyright (c) 2022 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 Dispatch
@testable import Logging
import XCTest
class SendableTest: XCTestCase {
#if compiler(>=5.6)
func testSendableLogger() async {
let testLogging = TestLogging()
LoggingSystem.bootstrapInternal(testLogging.make(label:metadataProvider:))
let logger = Logger(label: "test")
let message1 = Logger.Message(stringLiteral: "critical 1")
let message2 = Logger.Message(stringLiteral: "critical 2")
let metadata: Logger.Metadata = ["key": "value"]
let task = Task.detached {
logger.info("info")
logger.critical(message1)
logger.critical(message2)
logger.warning(.init(stringLiteral: "warning"), metadata: metadata)
}
await task.value
testLogging.history.assertExist(level: .info, message: "info", metadata: [:])
testLogging.history.assertExist(level: .critical, message: "critical 1", metadata: [:])
testLogging.history.assertExist(level: .critical, message: "critical 2", metadata: [:])
testLogging.history.assertExist(level: .warning, message: "warning", metadata: metadata)
}
#endif
}
+2 -3
View File
@@ -18,10 +18,9 @@ RUN apt-get update && apt-get install -y lsof dnsutils netcat-openbsd net-tools
# ruby and jazzy for docs generation
RUN apt-get update && apt-get install -y ruby ruby-dev libsqlite3-dev build-essential
# switch of gem docs building
RUN echo "gem: --no-document" > ~/.gemrc
# jazzy no longer works on xenial as ruby is too old.
RUN if [ "${ubuntu_version}" != "xenial" ] ; then gem install jazzy; fi
RUN if [ "${ubuntu_version}" = "focal" ] ; then echo "gem: --no-document" > ~/.gemrc; fi
RUN if [ "${ubuntu_version}" = "focal" ] ; then gem install jazzy; fi
# tools
RUN mkdir -p $HOME/.tools
+19
View File
@@ -0,0 +1,19 @@
version: "3"
services:
runtime-setup:
image: swift-log:20.04-5.5
build:
args:
ubuntu_version: "focal"
swift_version: "5.5"
test:
image: swift-log:20.04-5.5
environment:
- FORCE_TEST_DISCOVERY=--enable-test-discovery
#- SANITIZER_ARG=--sanitize=thread
shell:
image: swift-log:20.04-5.5
+19
View File
@@ -0,0 +1,19 @@
version: "3"
services:
runtime-setup:
image: swift-log:20.04-5.6
build:
args:
ubuntu_version: "focal"
swift_version: "5.6"
test:
image: swift-log:20.04-5.6
environment:
- FORCE_TEST_DISCOVERY=--enable-test-discovery
#- SANITIZER_ARG=--sanitize=thread
shell:
image: swift-log:20.04-5.6
+18
View File
@@ -0,0 +1,18 @@
version: "3"
services:
runtime-setup:
image: swift-log:20.04-5.7
build:
args:
base_image: "swiftlang/swift:nightly-main-focal"
test:
image: swift-log:20.04-5.7
environment:
- FORCE_TEST_DISCOVERY=--enable-test-discovery
#- SANITIZER_ARG=--sanitize=thread
shell:
image: swift-log:20.04-5.7
+2 -1
View File
@@ -10,7 +10,8 @@ services:
test:
image: swift-log:20.04-main
environment: []
environment:
- FORCE_TEST_DISCOVERY=--enable-test-discovery
#- SANITIZER_ARG=--sanitize=thread
shell:
+2 -2
View File
@@ -28,10 +28,10 @@ services:
test:
<<: *common
command: /bin/bash -xcl "swift test -Xswiftc -warnings-as-errors $${SANITIZER_ARG-}"
command: /bin/bash -xcl "swift test -Xswiftc -warnings-as-errors $${FORCE_TEST_DISCOVERY-} $${SANITIZER_ARG-}"
# util
shell:
<<: *common
entrypoint: /bin/bash
entrypoint: /bin/bash -l
+489
View File
@@ -0,0 +1,489 @@
# 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.
## 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.
Most notably, loggers should participate in tracing by including some trace metadata (such as e.g. a `trace-id`) when logging, as it transparently enables developers to benefit from log correlation using those IDs.
Today, the only supported way of providing such metadata is to pass them along to each log call explicitly:
```swift
logger.info("first this ...", metadata: ["trace-id": MyTracingLibrary.currentTraceID])
logger.info("... now this", metadata: ["trace-id": MyTracingLibrary.currentTraceID])
```
This comes with a couple of downsides:
### Error-prone and repetitive
It's easy to forget passing this metadata to _all_ log statements, resulting in an inconsistent debugging experience as these log statements cannot be found using correlation IDs.
The repetitiveness and verboseness of logging multiple metadata in-line quickly becomes annoying and vastly decreases the signal-to-noise ratio of Swift code trying to be a good citizen and making use of log correlation techniques such as distributed tracing.
### Impossible to implement for libraries
A large portion of logs are not generated by the end-user but by libraries such as AsyncHTTPClient, Vapor etc.
These libraries, by design, don't know about the specific metadata keys that should be included in the logs.
Those keys are after all runtime dependent, and may change depending on what tracing system is configured by the end user.
For example, a specific `Tracer` implementation would use a type representing a trace ID, and has a way of extracting
that trace ID from a `Baggage`. But other libraries can't know about this _specific_ trace ID and therefore would not be
able to pass such values along to their log statements.
## Proposed solution
To support this kind of runtime-generated metadata in `swift-log`, we need to extend the logging APIs in an open-ended way, to allow any kinds of metadata to be provided from the asynchronous context.
To solve this, we propose the extension of swift-log APIs with a new concept: _metadata providers_.
`MetadataProvider` is struct nested in the `Logger` type, sitting alongside `MetadataValue`
and the `Metadata` typealias. It has a single property `metadata` which is a closure from `Baggage?` to `Metadata?`:
```swift
extension Logger {
public struct MetadataProvider: Sendable {
public var metadata: @Sendable (_ baggage: Baggage?) -> Metadata?
public init(metadata: @escaping @Sendable (Baggage?) -> Metadata?) {
self.metadata = metadata
}
}
}
```
### Defining a `MetadataProvider`
While `MetadataProvider`s can be created in an ad-hoc fashion, the struct may be used as a namespace
to define providers in. A Tracing library e.g. could expose its metadata provider via a static property
on `Logger.MetadataProvider`:
```swift
extension Logger.MetadataProvider {
static let tracer = Logger.MetadataProvider { baggage in
guard let spanContext = baggage?.spanContext else { return nil }
return [
"traceID": "\(spanContext.traceID)",
"spanID": "\(spanContext.spanID)",
]
}
}
```
### Using a `MetadataProvider`
A `MetadataProvider` can be set up either globally, on a boot-strapped logging system:
```swift
LoggingSystem.bootstrap(
metadataProvider: .tracer,
StreamLogHandler.standardOutput
)
```
or, on a specific logger, in case some contexts should extract additional information:
```swift
let logger = Logger(label: "example", metadataProvider: .init { baggage in
guard let operationID = baggage?.operationID else { return nil }
return ["extra/opID": "\(opID)"]
})
```
> NOTE: Setting the metadata provider on the logger directly means the `LoggingSystem` metadata provider
> is skipped (if defined), following how an explicitly passed handler `factory`
> overrides the `LoggingSystem`s `factory`.
Once a metadata provider was set up, when a log statement is about to be emitted, the logger will obtain the task-local `Baggage.current`,
and pass it to the metadata providers. The providers can then convert specific baggage items into logger metadata as they see fit.
Those metadata will then be included in the log statement, e.g. like this:
```swift
var baggage = Baggage.topLevel
baggage.spanContext = SpanContext()
Baggage.$current.withValue(baggage) {
test()
}
func test() {
log.info("Test", metadata: ["oneOff": "42"])
// info [traceID: abc, spanID: 123, onOff: 42] Test
}
```
### Multiple `MetadataProvider`s using `MetadataProvider.multiplex(_:)`
Borrowing the concept from log handlers, metadata providers also have a multiplexing implementation.
It is defined as an extension on `MetadataProvider` and is useful in cases where users want to utilize
more than one metadata provider at the same time:
```swift
extension Logger.MetadataProvider {
public static func multiplex(_ providers: [Logger.MetadataProvider]) -> Logger.MetadataProvider {
assert(!providers.isEmpty, "providers MUST NOT be empty")
return Logger.MetadataProvider { baggage in
providers.reduce(into: nil) { metadata, provider in
if let providedMetadata = provider.metadata(baggage) {
if metadata != nil {
metadata!.merge(providedMetadata, uniquingKeysWith: { _, rhs in rhs })
} else {
metadata = providedMetadata
}
}
}
}
}
}
```
Metadata keys are unique, so in case multiple metadata providers return the same key,
the last provider in the array "wins" and provides the value.
### Proposal: Using `Baggage` as the execution context dependent metadata container
We propose that swift-log should use [Swift Distributed Tracing Baggage](https://github.com/apple/swift-distributed-tracing-baggage) for its contextual metadata propagation type, meaning that swift-log would depend on this package.
The `Baggage` type is modeled after the [Propagation format for distributed context: Baggage](https://www.w3.org/TR/baggage/), a W3C working draft, and is intended for all kinds of instrumentation of Swift applications both within and across processes. It is also used by [Swift Distributed Tracing](https://github.com/apple/swift-distributed-tracing), however it is usable even without tracing infrastructure. The baggage package contains the single `Baggage` type, and is expected to have a stable, unchanging API, fit for swift-log to depend upon.
> NOTE: We could potentially even rename the baggage package, if the tracing wording in it is causing confusion here. But realistically, this is its primary purpose: to enable tracing in logging systems, so we think swift-log depending on `swift-distributed-tracing-baggage` is fine.
To start using contextual metadata, end-users configure a metadata provider on the entire logging system or on a specific `Logger` via a new initializer parameter:
```swift
let logger = Logger(label: "example", metadataProvider: { baggage in
// extract values from baggage
guard let traceID = baggage?[TraceIDKey.self] else { return nil }
// convert values into logging metadata
return ["trace-id": traceID]
})
```
### Task-local Baggage
> NOTE: See [SE-0311](https://github.com/apple/swift-evolution/blob/main/proposals/0311-task-locals.md) for an explanation of task-local values in Swift.
Once configured, the `log` function and its log-level-based counterparts will utilize this provider by merging the provided metadata with the one-off metadata within the log statement.
Since `Baggage` is propagaged as a task-local, we do not change any of the existing method signatures, and the baggage is picked up inside the log method:
```swift
extension Logger {
@inlinable
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) {
let effectiveBaggage: Baggage? = {
guard baggage == nil else { return baggage }
let taskLocalBaggage: Baggage?
#if compiler(>=5.5) && canImport(_Concurrency)
if #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *), self.metadataProvider != nil {
taskLocalBaggage = Baggage.current
} else {
taskLocalBaggage = nil
}
#else
taskLocalBaggage = nil
#endif
return taskLocalBaggage
}()
let providerMetadata = metadataProvider?.metadata(effectiveBaggage)
let metadata: Metadata? = {
guard let metadata = metadata(), !metadata.isEmpty else { return providerMetadata }
guard let providerMetadata = providerMetadata else { return metadata }
return providerMetadata.merging(metadata, uniquingKeysWith: { _, oneOffMetadata in oneOffMetadata })
}()
self.handler.log(level: level,
message: message(),
metadata: metadata,
source: source() ?? Logger.currentModule(fileID: (file)),
file: file, function: function, line: line)
}
}
```
Note, that the task-local lookup is only performed when the log message is about to be emitted. No task-local or thread-local lookups are performed when the log level is lower than the level of the current statement or in case no metadata provider was set up.
We also introduce another overload of the log (and trace/debug/info/notice/warning/error/critical) method, which allows libraries to pass a baggage explicitly if they need to (or, disable baggage value extraction by passing `nil` as the value):
```swift
extension Logger {
@inlinable
public func log(level: Logger.Level,
_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
baggage: Baggage?,
source: @autoclosure () -> String? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line) {
if self.logLevel <= level {
let providerMetadata = metadataProvider?.metadata(baggage)
let metadata: Metadata? = {
guard let metadata = metadata(), !metadata.isEmpty else { return providerMetadata }
guard let providerMetadata = providerMetadata else { return metadata }
return providerMetadata.merging(metadata, uniquingKeysWith: { _, oneOffMetadata in oneOffMetadata })
}()
self.handler.log(level: level,
message: message(),
metadata: metadata,
source: source() ?? Logger.currentModule(fileID: (file)),
file: file, function: function, line: line)
}
}
}
```
Practical usage of baggage values is as follows:
```swift
var baggage = Baggage.topLevel
baggage[TestIDKey.self] = "my-awesome-trace-id"
Baggage.$current.withValue(baggage) {
logger.info("Such logging, wow!", metadata: ["one-off": "example"])
// info [my-test-key: my-awesome-trace-id, one-off: example] Such logging, wow!
}
```
This has the advantage of not having to specify the global metadata explicitly anymore.
The task-local baggage is often going to be set by e.g. tracing libraries or frameworks, so end-users do not need to do anything to benefit from tracing,
other than setting up the metadata providers when they bootstrap their logging and tracing systems. For example, assuming some imaginary http framework where http requests are forwarded to an actor for handling, all the end-users of this framework would benefit from contextual metadata, propagated with baggage by logging, as usual:
```swift
actor MyHTTPHandler {
func handle(request: HTTPRequest) async {
Logger(label: "inline").info("Handling request!")
// info [trace-id: 1234-5678] Handling request!
}
}
```
This also solves the issue of libraries not being able to include this kind of metadata since it is done automatically in the background, as long as
the values are stored inside the task-local `Baggage`.
### When to use `Baggage` vs. `Logger[metadataKey:]`
While `Baggage` is context-dependend and changes depending on where the log methods are being called from, the metadata set on a `Logger` is static and not context-dependent. E.g, if you wanted to add things like an instance ID or a subsystem name to a `Logger`, that could be seen as static information and set via `Logger[metadataKey:]`.
```swift
var logger = Logger(label: "org.swift.my-service")
logger[metadataKey: "instanceId"] = "123"
logger.info("Service started.")
// [instanceId: 123] Service started.
```
On the other hand, things like a trace ID are dynamic and context-dependent, therefore would be obtained via `Baggage`:
```swift
logger.info("Product fetched.")
// [traceId: 42] Product fetched.
```
Inline-metadata is suitable for one-offs such as a `productId` or a `paymentMethod` in an online store service, but are not enough to corralate the following log statements, i.e. tying them both to the same request:
```swift
logger.info("Product fetched.", metadata: ["productId": "42"])
logger.info("Product purchased.", metadata: ["paymentMethod": "apple-pay"])
// [productId: 42] Product fetched.
// [paymentMethod: apple-pay] Product fetched.
```
If there was a `Baggage` value with a trace ID surrounding these log statements, they would be automatically correlatable:
```swift
var baggage = Baggage.topLevel
baggage.traceID = 42
Baggage.$current.withValue(baggage) {
logger.info("Product fetched.", metadata: ["productId": "42"])
logger.info("Product purchased.", metadata: ["paymentMethod": "apple-pay"])
}
// [trace-id: 42, productId: 42] Product fetched.
// [trace-id: 42, paymentMethod: apple-pay] Product fetched.
```
### Using Baggage in callback APIs
Many libraries which provide `async` APIs, are implemented on top of Swift NIO, or other callback-heavy libraries (e.g. when wrapping existing non-async database libraries or similar).
The proposed API must work well with such libraries, in the sense that a metadata provider configured by an end-user, should still be useful in such libraries where setting a Task-local baggage is either impossible, or very weird (continiously wrapping every call into "restoring" the current baggage upon every re-entry from a callback):
```swift
class RequestStateMachine: ChannelInboundHandler {
let logger: Logger
func channelActive(context: ChannelHandlerContext) {
logger.debug("Channel active.")
// debug [trace-id: ???] Channel active.
}
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
logger.debug("Received request part.")
// debug [trace-id: ???] Received request part.
}
}
```
In the above example, we want the logger to capture the trace ID of the task that created `MyChannel`, but the delegate methods are called on the NIO event-loop which doesn't set any task-local `Baggage`.
We propose the following strategy for such libraries:
Entry points into such libraries should assume the presence of task-local `Baggage`.
This is the same as with tracing -- e.g. a `startWork()` method, does not need to accept a baggage parameter, but simply query `Baggage.current` if in need of any contextual metadata.
When the library is forced to exit the world of structured concurrency where task-locals work well `*`, they should _get and store_ the current baggage from the user's calling context, e.g. by storing it in a state machine driving class, handler, or actor: `self.baggage = Baggage.current`:
```swift
class RequestStateMachine: ChannelInboundHandler {
let logger: Logger
var baggage: Baggage?
init(logger: Logger) {
self.logger = logger
// in here we can still access the task-local Baggage
self.baggage = Baggage.current
}
func channelActive(context: ChannelHandlerContext) {
logger.debug("Channel active.", baggage: self.baggage)
// debug [trace-id: 42] Channel active.
}
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
logger.debug("Received request part.", baggage: self.baggage)
// debug [trace-id: 42] Received request part.
}
}
```
> `*` situations where task-local baggage just works include: plain synchronous methods, asynchronous methods, as all forms of structured concurrency (async lets and task groups), as well as un-structured (but _not_ detached) tasks (created by calling `Task { ... }`).
The libraries are then free to continue using their callback or delegate-style APIs, and whenever needing to log or restore the baggage they can, either:
- explicitly pass it to a logger: `log.info("Request finished", metadata: [...], baggage: self.baggage)`
- restore the contextual task-local baggage and wrap subsequent calls with: `Baggage.current.withValue(self.baggage) { moreThings() }`
### Rendering provider metadata only once in performance-critical code
In some performance-critical code, you may want to render the provider metadata only once. In such cases, you can call the metadata provider explicitly at the point of entry and instead of passing `Baggage` you'd use the `Logger`'s metadata:
```swift
class PerformanceCriticalRequestStateMachine: ChannelInboundHandler {
let logger: Logger
init(logger: Logger) {
var logger = logger
// in here we can still access the task-local Baggage
if let baggage = Baggage.current, let metadataProvider = logger.metadataProvider {
let metadata = metadataProvider(baggage)
for (key, value) in metadata {
logger[metadataKey: key] = value
}
}
self.logger = logger
}
func channelActive(context: ChannelHandlerContext) {
logger.debug("Channel active.", baggage: nil)
// debug [trace-id: 42] Channel active.
}
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
logger.debug("Received request part.", baggage: nil)
// debug [trace-id: 42] Received request part.
}
}
```
Passing `nil` as the `Baggage` will prevent task-local look-ups in these performance sensitive situations.
> NOTE: Most applications shouldn't need to worry about this and just rely on automatic Baggage propagation using task-locals
> WARNING: The context-dependent metadata becomes static which makes it hard to recover the dynamic information back into `Baggage`, e.g. if you wanted to create a child span in one of those callbacks.
## Alternatives considered
### Removing `LogHandler.Metadata` in favor of `Baggage`
Removing logger metadata is not a good option because it serves a slightly different style of metadata than the baggage.
Baggage is intended for contextual, task-local, metadata which is _carried across multiple libraries_. The values stored in baggage are well-typed, and must declare keys for accessing values in a baggage, this works well for multiple pieces of an application needing to reach for specific baggage items: everyone aware of the `traceID` key, is able to query the baggage for this key (`baggage.traceID`) and obtain a well-typed value. This comes with a higher cost on declaring keys though, as well as a global namespace for those - which is desirable for such kinds of metadata.
This is not the same usage pattern as emitting a plain structured log where we'd like to include the name of an item we just queried:
```swift
log.info("Obtained item! Hooray!", metadata: ["item": "\(item)"])
```
In this example, the key/value pair for `"item"` is pretty ad-hoc, and we never need to refer to it elsewhere in the program. It never is queried by other pieces of the application, nor would it be useful to set it in baggage metadata, as the only purpose of the `item` key here is to log, and forget about it.
### Explicitly passing `Baggage` always
Baggage is designed for use cases like distributed tracing, or similar instrumentation patterns where "all" participating code may need to reach for it.
Specifically in logging, this means that _every_ call site for _every_ log statement would have to pass it explicitly resulting in annoying noisy code:
```swift
class StoresRepository {
func store(byID id: String, eventLoop: EventLoop, logger: Logger, baggage: Baggage) async throws -> Store {
InstrumentationSystem.tracer.withSpan("Fetch Store", baggage: baggage) { span in
logger.info("Fetched store.", baggage: span.baggage)
}
}
}
try await storesRepository.store(
byID: storeID,
eventLoop: eventLoop,
logger: logger,
baggage: baggage
)
```
### Explicitly passing `Logger` always
Imagine we don't have metadata providers, we'd have to manually set trace IDs on loggers which doesn't really work as all libraries involved would need to know about the same specific trace ID. Event if we inverted the dependency to have `Tracing` depend on `Logging` so that we'd be able to define something like "Tracing, please populate this logger with metadata", we'd have to make sure this thing is called in all places to avoid dropping contextual metadata.
```swift
import Tracing
import Logging
let contextualLogger = InstrumentationSystem.tracer.populateTraceMetadata(logger, baggage: baggage)
contextualLogger.info("Request received.")
```
### Tracing providing extensions on Logger
Instead of having `swift-log` depend on `swift-distributed-tracing-baggage` we could also create extensions for `Logger` inside `swift-distributed-tracing` and have users call these new overloaded methods instead:
```swift
extension Logger {
func tinfo(_ message: ..., baggage: Baggage?) {
// ...
}
}
```
Such extensions could work like the currently-proposed APIs, but the risk of users calling the wrong methods is incredibly high and we cannot overload the existing methods' signatures because of ambiguity of call-sides without explicit Baggage being passed:
```swift
logger.info("Hello")
// we want this to pick up Baggage, but the signature would be ambiguous
```
Also, this extension-based contextual metadata would require basically everyone in Server-side Swift to adapt their usage of `Logging` to use these extensions instead. With the proposed APIs, we'd only need to modify `Logging` and any NIO-based libraries such as `AsyncHTTPClient`, `Vapor`, etc. and not every single log statement in every application.
+4 -4
View File
@@ -26,20 +26,20 @@ if [[ "$(uname -s)" == "Linux" ]]; then
swift build
fi
# setup source-kitten if required
source_kitten_source_path="$root_path/.SourceKitten"
mkdir -p "$root_path/.build/sourcekitten"
source_kitten_source_path="$root_path/.build/sourcekitten/source"
if [[ ! -d "$source_kitten_source_path" ]]; then
git clone https://github.com/jpsim/SourceKitten.git "$source_kitten_source_path"
fi
source_kitten_path="$source_kitten_source_path/.build/x86_64-unknown-linux/debug"
source_kitten_path="$source_kitten_source_path/.build/debug"
if [[ ! -d "$source_kitten_path" ]]; then
rm -rf "$source_kitten_source_path/.swift-version"
cd "$source_kitten_source_path" && swift build && cd "$root_path"
fi
# generate
mkdir -p "$root_path/.build/sourcekitten"
for module in "${modules[@]}"; do
if [[ ! -f "$root_path/.build/sourcekitten/$module.json" ]]; then
"$source_kitten_path/sourcekitten" doc --spm-module $module > "$root_path/.build/sourcekitten/$module.json"
"$source_kitten_path/sourcekitten" doc --spm --module-name $module > "$root_path/.build/sourcekitten/$module.json"
fi
done
fi
+1 -1
View File
@@ -94,7 +94,7 @@ def createLinuxMain(testsDirectory, allTestSubDirectories, files)
file.write header(fileName)
file.write "\n"
file.write "#if os(Linux) || os(FreeBSD) || os(Windows)\n"
file.write "#if os(Linux) || os(FreeBSD) || os(Windows) || os(Android)\n"
for testSubDirectory in allTestSubDirectories.sort { |x, y| x <=> y }
file.write '@testable import ' + testSubDirectory + "\n"
end
+16
View File
@@ -0,0 +1,16 @@
#!/bin/bash
##===----------------------------------------------------------------------===##
##
## 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.md for the list of Swift Logging API project authors
##
## SPDX-License-Identifier: Apache-2.0
##
##===----------------------------------------------------------------------===##
swift package --disable-sandbox preview-documentation --target Logging
+2 -2
View File
@@ -32,7 +32,7 @@ here="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
function replace_acceptable_years() {
# this needs to replace all acceptable forms with 'YEARS'
sed -e 's/20[12][78901]-20[12][8901]/YEARS/' -e 's/20[12][8901]/YEARS/'
sed -e 's/20[12][789012]-20[12][89012]/YEARS/' -e 's/20[12][89012]/YEARS/'
}
printf "=> Checking linux tests... "
@@ -86,7 +86,7 @@ for language in swift-or-c bash dtrace; do
matching_files=( -name '*' )
case "$language" in
swift-or-c)
exceptions=( -name c_nio_http_parser.c -o -name c_nio_http_parser.h -o -name cpp_magic.h -o -name Package.swift -o -name CNIOSHA1.h -o -name c_nio_sha1.c -o -name ifaddrs-android.c -o -name ifaddrs-android.h)
exceptions=( -name c_nio_http_parser.c -o -name c_nio_http_parser.h -o -name cpp_magic.h -o -name Package.swift -o name Package-swift5.6.swift -o -name CNIOSHA1.h -o -name c_nio_sha1.c -o -name ifaddrs-android.c -o -name ifaddrs-android.h)
matching_files=( -name '*.swift' -o -name '*.c' -o -name '*.h' )
cat > "$tmp" <<"EOF"
//===----------------------------------------------------------------------===//