mirror of
https://github.com/apple/swift-log
synced 2026-11-22 03:40:39 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
532d8b5295 | ||
|
|
f8ce47d3b0 | ||
|
|
1ef0345e1e | ||
|
|
5996c7a1b4 | ||
|
|
1aacf8affa | ||
|
|
bd5ff0d8e4 | ||
|
|
f79ba6a75f | ||
|
|
6763fd0b73 | ||
|
|
32e8d72446 | ||
|
|
b2eff1c427 | ||
|
|
ba2a9f5b93 | ||
|
|
3e3ef75109 | ||
|
|
bd4519f1c2 |
No files matched your search
+1
-53
@@ -1,55 +1,3 @@
|
||||
# Code of Conduct
|
||||
To be a truly great community, SwiftLog needs to welcome developers from all walks of life,
|
||||
with different backgrounds, and with a wide range of experience. A diverse and friendly
|
||||
community will have more great ideas, more unique perspectives, and produce more great
|
||||
code. We will work diligently to make the SwiftLog community welcoming to everyone.
|
||||
|
||||
To give clarity of what is expected of our members, SwiftLog has adopted the code of conduct
|
||||
defined by [contributor-covenant.org](https://www.contributor-covenant.org). This document is used across many open source
|
||||
communities, and we think it articulates our values well. The full text is copied below:
|
||||
|
||||
### Contributor Code of Conduct v1.3
|
||||
As contributors and maintainers of this project, and in the interest of fostering an open and
|
||||
welcoming community, we pledge to respect all people who contribute through reporting
|
||||
issues, posting feature requests, updating documentation, submitting pull requests or patches,
|
||||
and other activities.
|
||||
|
||||
We are committed to making participation in this project a harassment-free experience for
|
||||
everyone, regardless of level of experience, gender, gender identity and expression, sexual
|
||||
orientation, disability, personal appearance, body size, race, ethnicity, age, religion, or
|
||||
nationality.
|
||||
|
||||
Examples of unacceptable behavior by participants include:
|
||||
- The use of sexualized language or imagery
|
||||
- Personal attacks
|
||||
- Trolling or insulting/derogatory comments
|
||||
- Public or private harassment
|
||||
- Publishing other’s private information, such as physical or electronic addresses, without explicit permission
|
||||
- Other unethical or unprofessional conduct
|
||||
|
||||
Project maintainers have the right and responsibility to remove, edit, or reject comments,
|
||||
commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of
|
||||
Conduct, or to ban temporarily or permanently any contributor for other behaviors that they
|
||||
deem inappropriate, threatening, offensive, or harmful.
|
||||
|
||||
By adopting this Code of Conduct, project maintainers commit themselves to fairly and
|
||||
consistently applying these principles to every aspect of managing this project. Project
|
||||
maintainers who do not follow or enforce the Code of Conduct may be permanently removed
|
||||
from the project team.
|
||||
|
||||
This code of conduct applies both within project spaces and in public spaces when an
|
||||
individual is representing the project or its community.
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by
|
||||
contacting a project maintainer at [swift-log-conduct@group.apple.com](mailto:swift-log-conduct@group.apple.com). All complaints will be reviewed and
|
||||
investigated and will result in a response that is deemed necessary and appropriate to the
|
||||
circumstances. Maintainers are obligated to maintain confidentiality with regard to the reporter
|
||||
of an incident.
|
||||
|
||||
*This policy is adapted from the Contributor Code of Conduct [version 1.3.0](https://contributor-covenant.org/version/1/3/0/).*
|
||||
|
||||
### Reporting
|
||||
A working group of community members is committed to promptly addressing any [reported issues](mailto:swift-server-conduct@group.apple.com).
|
||||
Working group members are volunteers appointed by the project lead, with a
|
||||
preference for individuals with varied backgrounds and perspectives. Membership is expected
|
||||
to change regularly, and may grow or shrink.
|
||||
The code of conduct for this project can be found at https://swift.org/code-of-conduct.
|
||||
@@ -1,33 +0,0 @@
|
||||
// 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"]),
|
||||
],
|
||||
targets: [
|
||||
.target(
|
||||
name: "Logging",
|
||||
dependencies: []
|
||||
),
|
||||
.testTarget(
|
||||
name: "LoggingTests",
|
||||
dependencies: ["Logging"]
|
||||
),
|
||||
]
|
||||
)
|
||||
@@ -69,7 +69,7 @@ As the API has just launched, not many implementations exist yet. If you are int
|
||||
| [Kitura/HeliumLogger](https://github.com/Kitura/HeliumLogger) |a logging backend widely used in the Kitura ecosystem |
|
||||
| [ianpartridge/swift-log-**syslog**](https://github.com/ianpartridge/swift-log-syslog) | a [syslog](https://en.wikipedia.org/wiki/Syslog) backend|
|
||||
| [Adorkable/swift-log-**format-and-pipe**](https://github.com/Adorkable/swift-log-format-and-pipe) | a backend that allows customization of the output format and the resulting destination |
|
||||
| [chrisaljoudi/swift-log-**oslog**](https://github.com/chrisaljoudi/swift-log-oslog) | an OSLog [Unified Logging](https://developer.apple.com/documentation/os/logging) backend for use on Apple platforms. **Important Note:** we recommend using os_log directly as decribed [here](https://developer.apple.com/documentation/os/logging). Using os_log through swift-log using this backend will be less efficient and will also prevent specifying the privacy of the message. The backend always uses `%{public}@` as the format string and eagerly converts all string interpolations to strings. This has two drawbacks: 1. the static components of the string interpolation would be eagerly copied by the unified logging system, which will result in loss of performance. 2. It makes all messages public, which changes the default privacy policy of os_log, and doesn't allow specifying fine-grained privacy of sections of the message. In a separate on-going work, Swift APIs for os_log are being improved and made to align closely with swift-log APIs. References: [Unifying Logging Levels](https://forums.swift.org/t/custom-string-interpolation-and-compile-time-interpretation-applied-to-logging/18799), [Making os_log accept string interpolations using compile-time interpretation](https://forums.swift.org/t/logging-levels-for-swifts-server-side-logging-apis-and-new-os-log-apis/20365). |
|
||||
| [chrisaljoudi/swift-log-**oslog**](https://github.com/chrisaljoudi/swift-log-oslog) | an OSLog [Unified Logging](https://developer.apple.com/documentation/os/logging) backend for use on Apple platforms. **Important Note:** we recommend using os_log directly as described [here](https://developer.apple.com/documentation/os/logging). Using os_log through swift-log using this backend will be less efficient and will also prevent specifying the privacy of the message. The backend always uses `%{public}@` as the format string and eagerly converts all string interpolations to strings. This has two drawbacks: 1. the static components of the string interpolation would be eagerly copied by the unified logging system, which will result in loss of performance. 2. It makes all messages public, which changes the default privacy policy of os_log, and doesn't allow specifying fine-grained privacy of sections of the message. In a separate on-going work, Swift APIs for os_log are being improved and made to align closely with swift-log APIs. References: [Unifying Logging Levels](https://forums.swift.org/t/custom-string-interpolation-and-compile-time-interpretation-applied-to-logging/18799), [Making os_log accept string interpolations using compile-time interpretation](https://forums.swift.org/t/logging-levels-for-swifts-server-side-logging-apis-and-new-os-log-apis/20365). |
|
||||
| [Brainfinance/StackdriverLogging](https://github.com/Brainfinance/StackdriverLogging) | a structured JSON logging backend for use on Google Cloud Platform with the [Stackdriver logging agent](https://cloud.google.com/logging/docs/agent) |
|
||||
| [DnV1eX/GoogleCloudLogging](https://github.com/DnV1eX/GoogleCloudLogging) | a client-side library for logging application events in [Google Cloud](https://console.cloud.google.com/logs) via REST API v2. |
|
||||
| [vapor/console-kit](https://github.com/vapor/console-kit/) | print log messages to a terminal with stylized ([ANSI](https://en.wikipedia.org/wiki/ANSI_escape_code)) output |
|
||||
@@ -85,6 +85,8 @@ As the API has just launched, not many implementations exist yet. If you are int
|
||||
| [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/supabase). |
|
||||
| [kiliankoe/swift-log-matrix](https://swiftpackageindex.com/kiliankoe/swift-log-matrix) | a logging backend for sending logs directly to a [Matrix](https://matrix.org) room |
|
||||
| [DiscordBM/DiscordLogger](https://github.com/DiscordBM/DiscordLogger) | a Discord logging implementation to send your logs over to a Discord channel in a good-looking manner and with a lot of configuration options including the ability to send only a few important log-levels such as `warning`/`error`/`critical`. |
|
||||
| Your library? | [Get in touch!](https://forums.swift.org/c/server) |
|
||||
|
||||
## What is an API package?
|
||||
|
||||
@@ -177,7 +177,11 @@ extension LogHandler {
|
||||
nil
|
||||
}
|
||||
set {
|
||||
self.log(level: .warning, message: "Attempted to set metadataProvider on \(Self.self) that did not implement support for them. Please contact the log handler maintainer to implement metadata provider support.", metadata: nil, source: "Logging", file: #file, function: #function, line: #line)
|
||||
#if DEBUG
|
||||
if LoggingSystem.warnOnceLogHandlerNotSupportedMetadataProvider(Self.self) {
|
||||
self.log(level: .warning, message: "Attempted to set metadataProvider on \(Self.self) that did not implement support for them. Please contact the log handler maintainer to implement metadata provider support.", metadata: nil, source: "Logging", file: #file, function: #function, line: #line)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+112
-12
@@ -12,7 +12,7 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
|
||||
#if canImport(Darwin)
|
||||
import Darwin
|
||||
#elseif os(Windows)
|
||||
import CRT
|
||||
@@ -663,6 +663,10 @@ public enum LoggingSystem {
|
||||
private static let _factory = FactoryBox { label, _ in StreamLogHandler.standardOutput(label: label) }
|
||||
private static let _metadataProviderFactory = MetadataProviderBox(nil)
|
||||
|
||||
#if DEBUG
|
||||
private static var _warnOnceBox: WarnOnceBox = WarnOnceBox()
|
||||
#endif
|
||||
|
||||
/// `bootstrap` is a one-time configuration function which globally selects the desired logging backend
|
||||
/// implementation. `bootstrap` can be called at maximum once in any given program, calling it more than once will
|
||||
/// lead to undefined behavior, most likely a crash.
|
||||
@@ -708,9 +712,7 @@ public enum LoggingSystem {
|
||||
|
||||
fileprivate static var factory: (String, Logger.MetadataProvider?) -> LogHandler {
|
||||
return { label, metadataProvider in
|
||||
var handler = self._factory.underlying(label, metadataProvider)
|
||||
handler.metadataProvider = metadataProvider
|
||||
return handler
|
||||
self._factory.underlying(label, metadataProvider)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -727,6 +729,15 @@ public enum LoggingSystem {
|
||||
return self._metadataProviderFactory.metadataProvider
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
/// Used to warn only once about a specific ``LogHandler`` type when it does not support ``Logger/MetadataProvider``,
|
||||
/// but an attempt was made to set a metadata provider on such handler. In order to avoid flooding the system with
|
||||
/// warnings such warning is only emitted in debug mode, and even then at-most once for a handler type.
|
||||
internal static func warnOnceLogHandlerNotSupportedMetadataProvider<Handler: LogHandler>(_ type: Handler.Type) -> Bool {
|
||||
self._warnOnceBox.warnOnceLogHandlerNotSupportedMetadataProvider(type: type)
|
||||
}
|
||||
#endif
|
||||
|
||||
private final class FactoryBox {
|
||||
private let lock = ReadWriteLock()
|
||||
fileprivate var _underlying: (_ label: String, _ provider: Logger.MetadataProvider?) -> LogHandler
|
||||
@@ -911,7 +922,9 @@ extension Logger {
|
||||
/// instead of the system wide bootstrapped one, when a log statement is about to be emitted.
|
||||
public init(label: String, metadataProvider: MetadataProvider) {
|
||||
self = Logger(label: label, factory: { label in
|
||||
LoggingSystem.factory(label, metadataProvider)
|
||||
var handler = LoggingSystem.factory(label, metadataProvider)
|
||||
handler.metadataProvider = metadataProvider
|
||||
return handler
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1039,6 +1052,8 @@ extension Logger {
|
||||
public struct MultiplexLogHandler: LogHandler {
|
||||
private var handlers: [LogHandler]
|
||||
private var effectiveLogLevel: Logger.Level
|
||||
/// This metadata provider runs after all metadata providers of the multiplexed handlers.
|
||||
private var _metadataProvider: Logger.MetadataProvider?
|
||||
|
||||
/// Create a `MultiplexLogHandler`.
|
||||
///
|
||||
@@ -1051,6 +1066,13 @@ public struct MultiplexLogHandler: LogHandler {
|
||||
self.effectiveLogLevel = handlers.map { $0.logLevel }.min() ?? .trace
|
||||
}
|
||||
|
||||
public init(_ handlers: [LogHandler], metadataProvider: Logger.MetadataProvider?) {
|
||||
assert(!handlers.isEmpty, "MultiplexLogHandler.handlers MUST NOT be empty")
|
||||
self.handlers = handlers
|
||||
self.effectiveLogLevel = handlers.map { $0.logLevel }.min() ?? .trace
|
||||
self._metadataProvider = metadataProvider
|
||||
}
|
||||
|
||||
public var logLevel: Logger.Level {
|
||||
get {
|
||||
return self.effectiveLogLevel
|
||||
@@ -1061,6 +1083,43 @@ public struct MultiplexLogHandler: LogHandler {
|
||||
}
|
||||
}
|
||||
|
||||
public var metadataProvider: Logger.MetadataProvider? {
|
||||
get {
|
||||
if self.handlers.count == 1 {
|
||||
if let innerHandler = self.handlers.first?.metadataProvider {
|
||||
if let multiplexHandlerProvider = self._metadataProvider {
|
||||
return .multiplex([innerHandler, multiplexHandlerProvider])
|
||||
} else {
|
||||
return innerHandler
|
||||
}
|
||||
} else if let multiplexHandlerProvider = self._metadataProvider {
|
||||
return multiplexHandlerProvider
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
} else {
|
||||
var providers: [Logger.MetadataProvider] = []
|
||||
let additionalMetadataProviderCount = (self._metadataProvider != nil ? 1 : 0)
|
||||
providers.reserveCapacity(self.handlers.count + additionalMetadataProviderCount)
|
||||
for handler in self.handlers {
|
||||
if let provider = handler.metadataProvider {
|
||||
providers.append(provider)
|
||||
}
|
||||
}
|
||||
if let multiplexHandlerProvider = self._metadataProvider {
|
||||
providers.append(multiplexHandlerProvider)
|
||||
}
|
||||
guard !providers.isEmpty else {
|
||||
return nil
|
||||
}
|
||||
return .multiplex(providers)
|
||||
}
|
||||
}
|
||||
set {
|
||||
self.mutatingForEachHandler { $0.metadataProvider = newValue }
|
||||
}
|
||||
}
|
||||
|
||||
public func log(level: Logger.Level,
|
||||
message: Logger.Message,
|
||||
metadata: Logger.Metadata?,
|
||||
@@ -1075,13 +1134,22 @@ public struct MultiplexLogHandler: LogHandler {
|
||||
|
||||
public var metadata: Logger.Metadata {
|
||||
get {
|
||||
var effectiveMetadata: Logger.Metadata = [:]
|
||||
var effective: Logger.Metadata = [:]
|
||||
// as a rough estimate we assume that the underlying handlers have a similar metadata count,
|
||||
// and we use the first one's current count to estimate how big of a dictionary we need to allocate:
|
||||
effectiveMetadata.reserveCapacity(self.handlers.first!.metadata.count) // !-safe, we always have at least one handler
|
||||
return self.handlers.reduce(into: effectiveMetadata) { effectiveMetadata, handler in
|
||||
effectiveMetadata.merge(handler.metadata, uniquingKeysWith: { l, _ in l })
|
||||
effective.reserveCapacity(self.handlers.first!.metadata.count) // !-safe, we always have at least one handler
|
||||
|
||||
for handler in self.handlers {
|
||||
effective.merge(handler.metadata, uniquingKeysWith: { _, handlerMetadata in handlerMetadata })
|
||||
if let provider = handler.metadataProvider {
|
||||
effective.merge(provider.get(), uniquingKeysWith: { _, provided in provided })
|
||||
}
|
||||
}
|
||||
if let provider = self._metadataProvider {
|
||||
effective.merge(provider.get(), uniquingKeysWith: { _, provided in provided })
|
||||
}
|
||||
|
||||
return effective
|
||||
}
|
||||
set {
|
||||
self.mutatingForEachHandler { $0.metadata = newValue }
|
||||
@@ -1174,7 +1242,7 @@ internal struct StdioOutputStream: TextOutputStream {
|
||||
}
|
||||
|
||||
// Prevent name clashes
|
||||
#if os(macOS) || os(tvOS) || os(iOS) || os(watchOS)
|
||||
#if canImport(Darwin)
|
||||
let systemStderr = Darwin.stderr
|
||||
let systemStdout = Darwin.stdout
|
||||
#elseif os(Windows)
|
||||
@@ -1209,11 +1277,21 @@ public struct StreamLogHandler: LogHandler {
|
||||
return StreamLogHandler(label: label, stream: StdioOutputStream.stdout, metadataProvider: LoggingSystem.metadataProvider)
|
||||
}
|
||||
|
||||
/// Factory that makes a `StreamLogHandler` to directs its output to `stderr`
|
||||
/// Factory that makes a `StreamLogHandler` that directs its output to `stdout`
|
||||
public static func standardOutput(label: String, metadataProvider: Logger.MetadataProvider?) -> StreamLogHandler {
|
||||
return StreamLogHandler(label: label, stream: StdioOutputStream.stdout, metadataProvider: metadataProvider)
|
||||
}
|
||||
|
||||
/// Factory that makes a `StreamLogHandler` that directs its output to `stderr`
|
||||
public static func standardError(label: String) -> StreamLogHandler {
|
||||
return StreamLogHandler(label: label, stream: StdioOutputStream.stderr, metadataProvider: LoggingSystem.metadataProvider)
|
||||
}
|
||||
|
||||
/// Factory that makes a `StreamLogHandler` that direct its output to `stderr`
|
||||
public static func standardError(label: String, metadataProvider: Logger.MetadataProvider?) -> StreamLogHandler {
|
||||
return StreamLogHandler(label: label, stream: StdioOutputStream.stderr, metadataProvider: metadataProvider)
|
||||
}
|
||||
|
||||
private let stream: _SendableTextOutputStream
|
||||
private let label: String
|
||||
|
||||
@@ -1287,7 +1365,7 @@ public struct StreamLogHandler: LogHandler {
|
||||
metadata.merge(explicit, uniquingKeysWith: { _, explicit in explicit })
|
||||
}
|
||||
|
||||
return explicit
|
||||
return metadata
|
||||
}
|
||||
|
||||
private func prettify(_ metadata: Logger.Metadata) -> String? {
|
||||
@@ -1429,6 +1507,28 @@ extension Logger.MetadataValue: ExpressibleByArrayLiteral {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Debug only warnings
|
||||
|
||||
#if DEBUG
|
||||
/// Contains state to manage all kinds of "warn only once" warnings which the logging system may want to issue.
|
||||
private final class WarnOnceBox {
|
||||
private let lock: Lock = Lock()
|
||||
private var warnOnceLogHandlerNotSupportedMetadataProviderPerType: [ObjectIdentifier: Bool] = [:]
|
||||
|
||||
func warnOnceLogHandlerNotSupportedMetadataProvider<Handler: LogHandler>(type: Handler.Type) -> Bool {
|
||||
self.lock.withLock {
|
||||
let id = ObjectIdentifier(type)
|
||||
if warnOnceLogHandlerNotSupportedMetadataProviderPerType[id] ?? false {
|
||||
return false // don't warn, it was already warned about
|
||||
} else {
|
||||
warnOnceLogHandlerNotSupportedMetadataProviderPerType[id] = true
|
||||
return true // warn about this handler type, it is the first time we encountered it
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
// MARK: - Sendable support helpers
|
||||
|
||||
#if compiler(>=5.7.0)
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
|
||||
#if canImport(Darwin)
|
||||
import Darwin
|
||||
#elseif os(Windows)
|
||||
import CRT
|
||||
|
||||
@@ -31,6 +31,8 @@ extension LoggingTest {
|
||||
("testMultiplexLogHandlerNeedNotMaterializeValuesMultipleTimes", testMultiplexLogHandlerNeedNotMaterializeValuesMultipleTimes),
|
||||
("testMultiplexLogHandlerMetadata_settingMetadataThroughToUnderlyingHandlers", testMultiplexLogHandlerMetadata_settingMetadataThroughToUnderlyingHandlers),
|
||||
("testMultiplexLogHandlerMetadata_readingHandlerMetadata", testMultiplexLogHandlerMetadata_readingHandlerMetadata),
|
||||
("testMultiplexMetadataProviderSet", testMultiplexMetadataProviderSet),
|
||||
("testMultiplexMetadataProviderExtract", testMultiplexMetadataProviderExtract),
|
||||
("testDictionaryMetadata", testDictionaryMetadata),
|
||||
("testListMetadata", testListMetadata),
|
||||
("testStringConvertibleMetadata", testStringConvertibleMetadata),
|
||||
@@ -56,9 +58,11 @@ extension LoggingTest {
|
||||
("testStreamLogHandlerOutputFormat", testStreamLogHandlerOutputFormat),
|
||||
("testStreamLogHandlerOutputFormatWithMetaData", testStreamLogHandlerOutputFormatWithMetaData),
|
||||
("testStreamLogHandlerOutputFormatWithOrderedMetadata", testStreamLogHandlerOutputFormatWithOrderedMetadata),
|
||||
("testStreamLogHandlerWritesIncludeMetadataProviderMetadata", testStreamLogHandlerWritesIncludeMetadataProviderMetadata),
|
||||
("testStdioOutputStreamWrite", testStdioOutputStreamWrite),
|
||||
("testStdioOutputStreamFlush", testStdioOutputStreamFlush),
|
||||
("testOverloadingError", testOverloadingError),
|
||||
("testCompileInitializeStandardStreamLogHandlersWithMetadataProviders", testCompileInitializeStandardStreamLogHandlersWithMetadataProviders),
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,7 @@
|
||||
@testable import Logging
|
||||
import XCTest
|
||||
|
||||
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
|
||||
#if canImport(Darwin)
|
||||
import Darwin
|
||||
#elseif os(Windows)
|
||||
import WinSDK
|
||||
@@ -220,7 +220,84 @@ class LoggingTest: XCTestCase {
|
||||
XCTAssertEqual(multiplexLogger.handler.metadata, [
|
||||
"one": "111",
|
||||
"two": "222",
|
||||
"in": "in-1",
|
||||
"in": "in-2",
|
||||
])
|
||||
}
|
||||
|
||||
func testMultiplexMetadataProviderSet() {
|
||||
let logging1 = TestLogging()
|
||||
let logging2 = TestLogging()
|
||||
|
||||
var handler1 = logging1.make(label: "1")
|
||||
handler1.metadata["one"] = "111"
|
||||
handler1.metadata["in"] = "in-1"
|
||||
handler1.metadataProvider = .constant([
|
||||
"provider-1": "provided-111",
|
||||
"provider-overlap": "provided-111",
|
||||
])
|
||||
var handler2 = logging2.make(label: "2")
|
||||
handler2.metadata["two"] = "222"
|
||||
handler2.metadata["in"] = "in-2"
|
||||
handler2.metadataProvider = .constant([
|
||||
"provider-2": "provided-222",
|
||||
"provider-overlap": "provided-222",
|
||||
])
|
||||
|
||||
LoggingSystem.bootstrapInternal { _ in
|
||||
MultiplexLogHandler([handler1, handler2])
|
||||
}
|
||||
|
||||
let multiplexLogger = Logger(label: "test")
|
||||
|
||||
XCTAssertEqual(multiplexLogger.handler.metadata, [
|
||||
"one": "111",
|
||||
"two": "222",
|
||||
"in": "in-2",
|
||||
"provider-1": "provided-111",
|
||||
"provider-2": "provided-222",
|
||||
"provider-overlap": "provided-222",
|
||||
])
|
||||
XCTAssertEqual(multiplexLogger.handler.metadataProvider?.get(), [
|
||||
"provider-1": "provided-111",
|
||||
"provider-2": "provided-222",
|
||||
"provider-overlap": "provided-222",
|
||||
])
|
||||
}
|
||||
|
||||
func testMultiplexMetadataProviderExtract() {
|
||||
let logging1 = TestLogging()
|
||||
let logging2 = TestLogging()
|
||||
|
||||
var handler1 = logging1.make(label: "1")
|
||||
handler1.metadataProvider = .constant([
|
||||
"provider-1": "provided-111",
|
||||
"provider-overlap": "provided-111",
|
||||
])
|
||||
var handler2 = logging2.make(label: "2")
|
||||
handler2.metadata["two"] = "222"
|
||||
handler2.metadata["in"] = "in-2"
|
||||
handler2.metadataProvider = .constant([
|
||||
"provider-2": "provided-222",
|
||||
"provider-overlap": "provided-222",
|
||||
])
|
||||
|
||||
LoggingSystem.bootstrapInternal({ _, metadataProvider in
|
||||
MultiplexLogHandler(
|
||||
[handler1, handler2],
|
||||
metadataProvider: metadataProvider
|
||||
)
|
||||
}, metadataProvider: .constant([
|
||||
"provider-overlap": "provided-outer",
|
||||
]))
|
||||
|
||||
let multiplexLogger = Logger(label: "test")
|
||||
|
||||
let provider = multiplexLogger.metadataProvider!
|
||||
|
||||
XCTAssertEqual(provider.get(), [
|
||||
"provider-1": "provided-111",
|
||||
"provider-2": "provided-222",
|
||||
"provider-overlap": "provided-outer",
|
||||
])
|
||||
}
|
||||
|
||||
@@ -824,6 +901,24 @@ class LoggingTest: XCTestCase {
|
||||
XCTAssert(interceptStream.strings[1].contains("a=a1 b=b1"), "LINES: \(interceptStream.strings[1])")
|
||||
}
|
||||
|
||||
func testStreamLogHandlerWritesIncludeMetadataProviderMetadata() {
|
||||
let interceptStream = InterceptStream()
|
||||
LoggingSystem.bootstrapInternal({ _, metadataProvider in
|
||||
StreamLogHandler(label: "test", stream: interceptStream, metadataProvider: metadataProvider)
|
||||
}, metadataProvider: .exampleMetadataProvider)
|
||||
let log = Logger(label: "test")
|
||||
|
||||
let testString = "my message is better than yours"
|
||||
log.critical("\(testString)")
|
||||
|
||||
let messageSucceeded = interceptStream.interceptedText?.trimmingCharacters(in: .whitespacesAndNewlines).hasSuffix(testString)
|
||||
|
||||
XCTAssertTrue(messageSucceeded ?? false)
|
||||
XCTAssertEqual(interceptStream.strings.count, 1)
|
||||
let message = interceptStream.strings.first!
|
||||
XCTAssertTrue(message.contains("example=example-value"), "message must contain metadata, was: \(message)")
|
||||
}
|
||||
|
||||
func testStdioOutputStreamWrite() {
|
||||
self.withWriteReadFDsAndReadBuffer { writeFD, readFD, readBuffer in
|
||||
let logStream = StdioOutputStream(file: writeFD, flushMode: .always)
|
||||
@@ -934,6 +1029,30 @@ class LoggingTest: XCTestCase {
|
||||
|
||||
logging.history.assertExist(level: .error, message: "errorDescription")
|
||||
}
|
||||
|
||||
func testCompileInitializeStandardStreamLogHandlersWithMetadataProviders() {
|
||||
// avoid "unreachable code" warnings
|
||||
let dontExecute = Int.random(in: 100 ... 200) == 1
|
||||
guard dontExecute else {
|
||||
return
|
||||
}
|
||||
|
||||
// default usage
|
||||
LoggingSystem.bootstrap(StreamLogHandler.standardOutput)
|
||||
LoggingSystem.bootstrap(StreamLogHandler.standardError)
|
||||
|
||||
// with metadata handler, explicitly, public api
|
||||
LoggingSystem.bootstrap({ label, metadataProvider in
|
||||
StreamLogHandler.standardOutput(label: label, metadataProvider: metadataProvider)
|
||||
}, metadataProvider: .exampleMetadataProvider)
|
||||
LoggingSystem.bootstrap({ label, metadataProvider in
|
||||
StreamLogHandler.standardError(label: label, metadataProvider: metadataProvider)
|
||||
}, metadataProvider: .exampleMetadataProvider)
|
||||
|
||||
// with metadata handler, still pretty
|
||||
LoggingSystem.bootstrap(StreamLogHandler.standardOutput, metadataProvider: .exampleMetadataProvider)
|
||||
LoggingSystem.bootstrap(StreamLogHandler.standardError, metadataProvider: .exampleMetadataProvider)
|
||||
}
|
||||
}
|
||||
|
||||
extension Logger {
|
||||
@@ -957,6 +1076,10 @@ extension Logger.MetadataProvider {
|
||||
static var exampleMetadataProvider: Self {
|
||||
.init { ["example": .string("example-value")] }
|
||||
}
|
||||
|
||||
static func constant(_ metadata: Logger.Metadata) -> Self {
|
||||
.init { metadata }
|
||||
}
|
||||
}
|
||||
|
||||
// Sendable
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
@testable import Logging
|
||||
import XCTest
|
||||
|
||||
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
|
||||
#if canImport(Darwin)
|
||||
import Darwin
|
||||
#elseif os(Windows)
|
||||
import WinSDK
|
||||
@@ -25,7 +25,9 @@ import Glibc
|
||||
final class MetadataProviderTest: XCTestCase {
|
||||
func testLoggingMergesOneOffMetadataWithProvidedMetadataFromExplicitlyPassed() throws {
|
||||
let logging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal(logging.make)
|
||||
LoggingSystem.bootstrapInternal(logging.makeWithMetadataProvider,
|
||||
metadataProvider: .init { ["common": "initial"]
|
||||
})
|
||||
|
||||
let logger = Logger(label: #function, metadataProvider: .init {
|
||||
[
|
||||
@@ -42,21 +44,31 @@ final class MetadataProviderTest: XCTestCase {
|
||||
}
|
||||
|
||||
func testLogHandlerThatDidNotImplementProvidersButSomeoneAttemptsToSetOneOnIt() {
|
||||
#if DEBUG
|
||||
// we only emit these warnings in debug mode
|
||||
let logging = TestLogging()
|
||||
var handler = LogHandlerThatDidNotImplementMetadataProviders(testLogging: logging)
|
||||
|
||||
handler.metadataProvider = .simpleTestProvider
|
||||
|
||||
logging.history.assertExist(level: .warning, message: "Attempted to set metadataProvider on LogHandlerThatDidNotImplementMetadataProviders that did not implement support for them. Please contact the log handler maintainer to implement metadata provider support.", source: "Logging")
|
||||
|
||||
let countBefore = logging.history.entries.count
|
||||
handler.metadataProvider = .simpleTestProvider
|
||||
XCTAssertEqual(countBefore, logging.history.entries.count, "Should only log the warning once")
|
||||
#endif
|
||||
}
|
||||
|
||||
func testLogHandlerThatDidImplementProvidersButSomeoneAttemptsToSetOneOnIt() {
|
||||
#if DEBUG
|
||||
// we only emit these warnings in debug mode
|
||||
let logging = TestLogging()
|
||||
var handler = LogHandlerThatDidImplementMetadataProviders(testLogging: logging)
|
||||
|
||||
handler.metadataProvider = .simpleTestProvider
|
||||
|
||||
logging.history.assertNotExist(level: .warning, message: "Attempted to set metadataProvider on LogHandlerThatDidImplementMetadataProviders that did not implement support for them. Please contact the log handler maintainer to implement metadata provider support.", source: "Logging")
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -359,7 +359,7 @@ public class MDC {
|
||||
}
|
||||
|
||||
private var threadId: Int {
|
||||
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
|
||||
#if canImport(Darwin)
|
||||
return Int(pthread_mach_thread_np(pthread_self()))
|
||||
#elseif os(Windows)
|
||||
return Int(GetCurrentThreadId())
|
||||
|
||||
@@ -6,7 +6,8 @@ services:
|
||||
image: swift-log:20.04-5.7
|
||||
build:
|
||||
args:
|
||||
base_image: "swiftlang/swift:nightly-main-focal"
|
||||
ubuntu_version: "focal"
|
||||
swift_version: "5.7"
|
||||
|
||||
test:
|
||||
image: swift-log:20.04-5.7
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
version: "3"
|
||||
|
||||
services:
|
||||
|
||||
runtime-setup:
|
||||
image: swift-log:20.04-5.8
|
||||
build:
|
||||
args:
|
||||
ubuntu_version: "focal"
|
||||
swift_version: "5.8"
|
||||
|
||||
test:
|
||||
image: swift-log:20.04-5.8
|
||||
environment:
|
||||
- FORCE_TEST_DISCOVERY=--enable-test-discovery
|
||||
#- SANITIZER_ARG=--sanitize=thread
|
||||
|
||||
shell:
|
||||
image: swift-log:20.04-5.8
|
||||
@@ -3,16 +3,16 @@ version: "3"
|
||||
services:
|
||||
|
||||
runtime-setup:
|
||||
image: swift-log:20.04-main
|
||||
image: swift-log:22.04-5.9
|
||||
build:
|
||||
args:
|
||||
base_image: "swiftlang/swift:nightly-main-focal"
|
||||
base_image: "swiftlang/swift:nightly-5.9-jammy"
|
||||
|
||||
test:
|
||||
image: swift-log:20.04-main
|
||||
image: swift-log:22.04-5.9
|
||||
environment:
|
||||
- FORCE_TEST_DISCOVERY=--enable-test-discovery
|
||||
#- SANITIZER_ARG=--sanitize=thread
|
||||
|
||||
shell:
|
||||
image: swift-log:20.04-main
|
||||
image: swift-log:22.04-5.9
|
||||
@@ -0,0 +1,18 @@
|
||||
version: "3"
|
||||
|
||||
services:
|
||||
|
||||
runtime-setup:
|
||||
image: swift-log:22.04-main
|
||||
build:
|
||||
args:
|
||||
base_image: "swiftlang/swift:nightly-main-jammy"
|
||||
|
||||
test:
|
||||
image: swift-log:22.04-main
|
||||
environment:
|
||||
- FORCE_TEST_DISCOVERY=--enable-test-discovery
|
||||
#- SANITIZER_ARG=--sanitize=thread
|
||||
|
||||
shell:
|
||||
image: swift-log:22.04-main
|
||||
Reference in new issue
Block a user