Compare commits

..
18 Commits
Author SHA1 Message Date
elishas b3a6373077 Update README.md add shipbook as backend (#304)
Motivation:

Added shipbook as backend for the library.

Modifications:

Just added it to the backend list.

Result:

Will have a fuller list.
2024-06-20 05:18:55 -07:00
Ross Butler 4bcd3dfb11 Added swift-log-ecs to README.md (#298) 2024-06-19 10:06:47 +01:00
Peter Adams 7adcf9aa15 Remove Docc plugin which is no longer required. (#311)
Motivation:

Plugin is no longer required to produce docs.
There are now warnings in the plugin when included
and it will delay build a small amount.

Modifications:

Remove plugin dependency.

Result:

No dependencies.
2024-06-19 09:27:12 +01:00
Peter Adams f5312694b3 Fix deprecation warnings around default log implementations on handlers (#310)
Motivation:

Latest swift introduces new warnings when deprecated default
implementations are used.

Modifications:

Add new log implementation to NoopLogHandler.
Mark test of old method as deprecated to silence warning.

Result:

Warning free builds on latest swift 6 compiler.
2024-06-19 05:19:26 +01:00
Peter Adams 6553ef5893 Add Sendability annotations (#308)
Motivation:

This becomes a critical feature in swift 6.

Modifications:

Add Sendability annotations where required.
Factor out code protected by locks.

Result:

Compiles without warnings with Sendability checking
2024-06-18 08:28:58 -07:00
b1ackturtle 11e749ea6d Remove documentation for non-existent arguments (#309) 2024-06-17 02:16:17 -07:00
Peter Adams d16e216341 Make protocol usage obvious using any and some keywords (#307)
Motivation:

Calling through protocols is more expensive than many other types of call.

Modifications:

Annotate each protocol usage with any or some keywords.

Result:

Protocol usage now obvious
2024-06-10 15:16:46 +01:00
Peter Adams 0f170b4764 Use Set to spot duplicated log handler warnings. (#306)
Motivation:

Feels like a better fit for the problem when a dictionary of bools.

Modifications:

Convert storage to set.

Result:

Fewer lines of code, less waste.
2024-06-10 14:17:43 +01:00
23517234d5 feat: Implement Copy-On-Write (CoW) behavior for Logger struct (#297)
* feat: Implement Copy-On-Write (CoW) behavior for Logger struct

* fix: refactored the struct and added test

* fix: refactored the struct

* fix: refactored the struct

* fix:Added compiler directive and @usableFromInline/@inlinable

* fix: Add endif label

* fix: Remove colon causing expected type

* fix: Add inlinable and moving compiler derective

* nit

* fix: add inlinable

* Update Sources/Logging/Logging.swift

Co-authored-by: Johannes Weiss <johannesweiss@apple.com>

* Update Sources/Logging/Logging.swift

Co-authored-by: Johannes Weiss <johannesweiss@apple.com>

* Update Sources/Logging/Logging.swift

Co-authored-by: Franz Busch <privat@franz-busch.de>

* Update Sources/Logging/Logging.swift

Co-authored-by: Franz Busch <privat@franz-busch.de>

* fix: add self to class declaration and fixed formatting

* fix: make label public

* fix: format

* fix: remove setter

* test: added a test case

---------

Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
Co-authored-by: Franz Busch <privat@franz-busch.de>
2024-05-30 11:18:30 +01:00
Gustavo Cairo c7dcb55fb9 Drop Swift versions earlier than 5.8 (#299)
* Drop Swift versions earlier than 5.8

* Delete build_podspec.sh

* Update check_no_api_breakages script
2024-05-16 10:11:40 +01:00
Franz Busch ebb05e0317 Remove archived repository (#292)
https://github.com/luoxiu/LogDog appears to be archived.
2024-05-09 13:42:36 +01:00
Ayushi Tiwari b1617b3c0c feat: Replace standardOutput to standardError (#295) 2024-05-09 14:21:58 +02:00
Yim Lee c1ff8be7bc Add CI for Swift 5.10 (#287) 2024-01-23 08:24:18 -08:00
Alastair Houghton e97a6fcb1a Changes to build with Musl. (#283)
Added imports of Musl in a few places.  Also added definitions
for `systemStderr` and `systemStdout`.
2023-12-07 10:42:43 -08:00
Tim Condon 4587ac512c Update README.md (#279)
Improve the README to make it easier to find different logging backends
2023-11-24 12:17:59 +09:00
Gwynne Raskind f447991bd2 Don't assume localtime() result is non-nil (#280)
Don't assume localtime() result is non-nil
2023-11-16 16:15:22 -08:00
tomer doron 86ee8ef09e update CI script (#281)
motivation: fix CI

* do not install ruby or jazzy, they are no longer needed
* remove documentation generation script
2023-11-17 07:30:57 +09:00
Florian Friedrich cb28750240 Add CocoaLumberjack to list of logging backends (#276) 2023-08-23 09:46:39 -07:00
46 changed files with 437 additions and 1641 deletions

No files matched your search

+9 -6
View File
@@ -1,4 +1,4 @@
// swift-tools-version:5.6
// swift-tools-version:5.8
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Logging API open source project
@@ -15,22 +15,25 @@
import PackageDescription
let swiftSettings: [SwiftSetting] = [
.enableUpcomingFeature("ExistentialAny"),
]
let package = Package(
name: "swift-log",
products: [
.library(name: "Logging", targets: ["Logging"]),
],
dependencies: [
.package(url: "https://github.com/apple/swift-docc-plugin", from: "1.0.0"),
],
targets: [
.target(
name: "Logging",
dependencies: []
dependencies: [],
swiftSettings: swiftSettings
),
.testTarget(
name: "LoggingTests",
dependencies: ["Logging"]
dependencies: ["Logging"],
swiftSettings: swiftSettings
),
]
)
-33
View File
@@ -1,33 +0,0 @@
// 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"]),
],
targets: [
.target(
name: "Logging",
dependencies: []
),
.testTarget(
name: "LoggingTests",
dependencies: ["Logging"]
),
]
)
-33
View File
@@ -1,33 +0,0 @@
// 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"]),
],
targets: [
.target(
name: "Logging",
dependencies: []
),
.testTarget(
name: "LoggingTests",
dependencies: ["Logging"]
),
]
)
-33
View File
@@ -1,33 +0,0 @@
// 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"]),
],
targets: [
.target(
name: "Logging",
dependencies: []
),
.testTarget(
name: "LoggingTests",
dependencies: ["Logging"]
),
]
)
-33
View File
@@ -1,33 +0,0 @@
// 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"]),
],
targets: [
.target(
name: "Logging",
dependencies: []
),
.testTarget(
name: "LoggingTests",
dependencies: ["Logging"]
),
]
)
-33
View File
@@ -1,33 +0,0 @@
// 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"]),
],
targets: [
.target(
name: "Logging",
dependencies: []
),
.testTarget(
name: "LoggingTests",
dependencies: ["Logging"]
),
]
)
+7 -9
View File
@@ -10,7 +10,7 @@ If you have a server-side Swift application, or maybe a cross-platform (for exam
#### Adding the dependency
`SwiftLog` is designed for Swift 5. To depend on the logging API package, you need to declare your dependency in your `Package.swift`:
`SwiftLog` is designed for Swift 5.8 and later. To depend on the logging API package, you need to declare your dependency in your `Package.swift`:
```swift
.package(url: "https://github.com/apple/swift-log.git", from: "1.0.0"),
@@ -19,10 +19,6 @@ If you have a server-side Swift application, or maybe a cross-platform (for exam
and to your application/library target, add `"Logging"` to your `dependencies`, e.g. like this:
```swift
// Target syntax for Swift up to version 5.1
.target(name: "BestExampleApp", dependencies: ["Logging"]),
// Target for Swift 5.2
.target(name: "BestExampleApp", dependencies: [
.product(name: "Logging", package: "swift-log")
],
@@ -60,9 +56,9 @@ LoggingSystem.bootstrap(StreamLogHandler.standardError)
For further information, please check the [API documentation][api-docs].
<a name="backends"></a>
#### Selecting a logging backend implementation (applications only)
## Available Logging Backends For Applications
As the API has just launched, not many implementations exist yet. If you are interested in implementing one see the "Implementation considerations" section below explaining how to do so. List of existing SwiftLog API compatible libraries:
You can choose from one of the following backends to consume your logs. If you are interested in implementing one see the "Implementation considerations" section below explaining how to do so. List of existing SwiftLog API compatible libraries:
| Repository | Handler Description|
| ----------- | ----------- |
@@ -72,7 +68,7 @@ As the API has just launched, not many implementations exist yet. If you are int
| [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 |
| [vapor/console-kit](https://github.com/vapor/console-kit/) | a logger to the current terminal or stdout with stylized ([ANSI](https://en.wikipedia.org/wiki/ANSI_escape_code)) output. The default logger for all Vapor applications |
| [neallester/swift-log-testing](https://github.com/neallester/swift-log-testing) | provides access to log messages for use in assertions (within test targets) |
| [wlisac/swift-log-slack](https://github.com/wlisac/swift-log-slack) | a logging backend that sends critical log messages to Slack |
| [NSHipster/swift-log-github-actions](https://github.com/NSHipster/swift-log-github-actions) | a logging backend that translates logging messages into [workflow commands for GitHub Actions](https://help.github.com/en/actions/reference/workflow-commands-for-github-actions). |
@@ -81,12 +77,14 @@ As the API has just launched, not many implementations exist yet. If you are int
| [google/SwiftLogFireCloud](https://github.com/google/swiftlogfirecloud) | a logging backend for time series logging which pushes logs as flat files to Firebase Cloud Storage. |
| [crspybits/swift-log-file](https://github.com/crspybits/swift-log-file) | a simple local file logger (using `Foundation` `FileManager`) |
| [sushichop/Puppy](https://github.com/sushichop/Puppy) | a logging backend that supports multiple transports(console, file, syslog, etc.) and has the feature with formatting and file log rotation |
| [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/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`. |
| [CocoaLumberjack](https://github.com/CocoaLumberjack/CocoaLumberjack) | a fast & simple, yet powerful & flexible logging framework for macOS, iOS, tvOS and watchOS, which includes a logging backend for swift-log. |
| [rwbutler/swift-log-ecs](https://github.com/rwbutler/swift-log-ecs) | a logging backend for logging in [ECS Log format](https://www.elastic.co/guide/en/ecs-logging/overview/current/intro.html). Compatible with [Vapor](https://github.com/vapor/vapor) and allows chaining of multiple LogHandlers. |
| [ShipBook/swift-log-**shipbook**](https://github.com/ShipBook/swift-log-shipbook) | a logging backend that sends log entries to [Shipbook](https://www.shipbook.io) - Shipbook gives you the power to remotely gather, search and analyze your user logs and exceptions in the cloud, on a per-user & session basis. |
| Your library? | [Get in touch!](https://forums.swift.org/c/server) |
## What is an API package?
+7 -5
View File
@@ -34,6 +34,8 @@ import Darwin
import WinSDK
#elseif canImport(Glibc)
import Glibc
#elseif canImport(Musl)
import Musl
#else
#error("Unsupported runtime")
#endif
@@ -44,7 +46,7 @@ import Glibc
/// of lock is safe to use with `libpthread`-based threading models, such as the
/// one used by NIO. On Windows, the lock is based on the substantially similar
/// `SRWLOCK` type.
internal final class Lock {
internal final class Lock: @unchecked Sendable {
#if canImport(WASILibc)
// WASILibc is single threaded, provides no locks
#elseif os(Windows)
@@ -146,7 +148,7 @@ extension Lock {
/// of lock is safe to use with `libpthread`-based threading models, such as the
/// one used by NIO. On Windows, the lock is based on the substantially similar
/// `SRWLOCK` type.
internal final class ReadWriteLock {
internal final class ReadWriteLock: @unchecked Sendable {
#if canImport(WASILibc)
// WASILibc is single threaded, provides no locks
#elseif os(Windows)
@@ -187,7 +189,7 @@ internal final class ReadWriteLock {
///
/// Whenever possible, consider using `withReaderLock` instead of this
/// method and `unlock`, to simplify lock handling.
public func lockRead() {
fileprivate func lockRead() {
#if canImport(WASILibc)
// WASILibc is single threaded, provides no locks
#elseif os(Windows)
@@ -203,7 +205,7 @@ internal final class ReadWriteLock {
///
/// Whenever possible, consider using `withWriterLock` instead of this
/// method and `unlock`, to simplify lock handling.
public func lockWrite() {
fileprivate func lockWrite() {
#if canImport(WASILibc)
// WASILibc is single threaded, provides no locks
#elseif os(Windows)
@@ -220,7 +222,7 @@ internal final class ReadWriteLock {
/// Whenever possible, consider using `withReaderLock` and `withWriterLock`
/// instead of this method and `lockRead` and `lockWrite`, to simplify lock
/// handling.
public func unlock() {
fileprivate func unlock() {
#if canImport(WASILibc)
// WASILibc is single threaded, provides no locks
#elseif os(Windows)
-4
View File
@@ -212,8 +212,4 @@ extension LogHandler {
// 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
+2 -16
View File
@@ -18,17 +18,15 @@ import Darwin
import CRT
#elseif canImport(Glibc)
import Glibc
#elseif canImport(Musl)
import Musl
#elseif canImport(WASILibc)
import WASILibc
#else
#error("Unsupported runtime")
#endif
#if compiler(>=5.6)
@preconcurrency protocol _SwiftLogSendable: Sendable {}
#else
protocol _SwiftLogSendable {}
#endif
extension Logger {
/// A `MetadataProvider` is used to automatically inject runtime-generated metadata
@@ -59,28 +57,16 @@ extension Logger {
/// if necessary.
public struct MetadataProvider: _SwiftLogSendable {
/// Provide ``Logger.Metadata`` from current context.
#if swift(>=5.5) && canImport(_Concurrency) // we could instead typealias the function type, but it was requested that we avoid this for better developer experience
@usableFromInline
internal let _provideMetadata: @Sendable() -> Metadata
#else
@usableFromInline
internal let _provideMetadata: () -> Metadata
#endif
/// Create a new `MetadataProvider`.
///
/// - Parameter provideMetadata: A closure extracting metadata from the current execution context.
#if swift(>=5.5) && canImport(_Concurrency)
public init(_ provideMetadata: @escaping @Sendable() -> Metadata) {
self._provideMetadata = provideMetadata
}
#else
public init(_ provideMetadata: @escaping () -> Metadata) {
self._provideMetadata = provideMetadata
}
#endif
/// Invoke the metadata provider and return the generated contextual ``Logger/Metadata``.
public func get() -> Metadata {
return self._provideMetadata()
-36
View File
@@ -1,36 +0,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
//
//===----------------------------------------------------------------------===//
//
// LinuxMain.swift
//
import XCTest
///
/// NOTE: This file was generated by generate_linux_tests.rb
///
/// Do NOT edit this file directly as it will be regenerated automatically when needed.
///
#if os(Linux) || os(FreeBSD) || os(Windows) || os(Android)
@testable import LoggingTests
XCTMain([
testCase(CompatibilityTest.allTests),
testCase(GlobalLoggerTest.allTests),
testCase(LocalLoggerTest.allTests),
testCase(LoggingTest.allTests),
testCase(MDCTest.allTests),
testCase(MetadataProviderTest.allTests),
])
#endif
@@ -1,31 +0,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
//
//===----------------------------------------------------------------------===//
//
// CompatibilityTest+XCTest.swift
//
import XCTest
///
/// NOTE: This file was generated by generate_linux_tests.rb
///
/// Do NOT edit this file directly as it will be regenerated automatically when needed.
///
extension CompatibilityTest {
static var allTests: [(String, (CompatibilityTest) -> () throws -> Void)] {
return [
("testAllLogLevelsWorkWithOldSchoolLogHandlerWorks", testAllLogLevelsWorkWithOldSchoolLogHandlerWorks),
]
}
}
+7 -4
View File
@@ -16,10 +16,11 @@
import XCTest
final class CompatibilityTest: XCTestCase {
@available(*, deprecated, message: "Testing deprecated functionality")
func testAllLogLevelsWorkWithOldSchoolLogHandlerWorks() {
let testLogging = OldSchoolTestLogging()
var logger = Logger(label: "\(#function)", factory: testLogging.make)
var logger = Logger(label: "\(#function)", factory: { testLogging.make(label: $0) })
logger.logLevel = .trace
logger.trace("yes: trace")
@@ -45,7 +46,8 @@ private struct OldSchoolTestLogging {
private let _config = Config() // shared among loggers
private let recorder = Recorder() // shared among loggers
func make(label: String) -> LogHandler {
@available(*, deprecated, message: "Testing deprecated functionality")
func make(label: String) -> any LogHandler {
return OldSchoolLogHandler(label: label,
config: self.config,
recorder: self.recorder,
@@ -54,15 +56,16 @@ private struct OldSchoolTestLogging {
}
var config: Config { return self._config }
var history: History { return self.recorder }
var history: some History { return self.recorder }
}
@available(*, deprecated, message: "Testing deprecated functionality")
private struct OldSchoolLogHandler: LogHandler {
var label: String
let config: Config
let recorder: Recorder
func make(label: String) -> LogHandler {
func make(label: String) -> some LogHandler {
return TestLogHandler(label: label, config: self.config, recorder: self.recorder)
}
@@ -1,33 +0,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
//
//===----------------------------------------------------------------------===//
//
// GlobalLoggingTest+XCTest.swift
//
import XCTest
///
/// NOTE: This file was generated by generate_linux_tests.rb
///
/// Do NOT edit this file directly as it will be regenerated automatically when needed.
///
extension GlobalLoggerTest {
static var allTests: [(String, (GlobalLoggerTest) -> () throws -> Void)] {
return [
("test1", test1),
("test2", test2),
("test3", test3),
]
}
}
+8 -3
View File
@@ -13,12 +13,17 @@
//===----------------------------------------------------------------------===//
@testable import Logging
import XCTest
#if compiler(>=6.0) || canImport(Darwin)
import Dispatch
#else
@preconcurrency import Dispatch
#endif
class GlobalLoggerTest: XCTestCase {
func test1() throws {
// bootstrap with our test logging impl
let logging = TestLogging()
LoggingSystem.bootstrapInternal(logging.make)
LoggingSystem.bootstrapInternal { logging.make(label: $0) }
// change test logging config to log traces and above
logging.config.set(value: Logger.Level.debug)
@@ -45,7 +50,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: $0) }
// change test logging config to log errors and above
logging.config.set(value: Logger.Level.error)
@@ -72,7 +77,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: $0) }
// change test logging config
logging.config.set(value: .warning)
@@ -1,32 +0,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
//
//===----------------------------------------------------------------------===//
//
// LocalLoggingTest+XCTest.swift
//
import XCTest
///
/// NOTE: This file was generated by generate_linux_tests.rb
///
/// Do NOT edit this file directly as it will be regenerated automatically when needed.
///
extension LocalLoggerTest {
static var allTests: [(String, (LocalLoggerTest) -> () throws -> Void)] {
return [
("test1", test1),
("test2", test2),
]
}
}
+7 -2
View File
@@ -13,12 +13,17 @@
//===----------------------------------------------------------------------===//
@testable import Logging
import XCTest
#if compiler(>=6.0) || canImport(Darwin)
import Dispatch
#else
@preconcurrency import Dispatch
#endif
class LocalLoggerTest: XCTestCase {
func test1() throws {
// bootstrap with our test logging impl
let logging = TestLogging()
LoggingSystem.bootstrapInternal(logging.make)
LoggingSystem.bootstrapInternal { logging.make(label: $0) }
// change test logging config to log traces and above
logging.config.set(value: Logger.Level.debug)
@@ -46,7 +51,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: $0) }
// change test logging config to log errors and above
logging.config.set(value: Logger.Level.error)
@@ -1,68 +0,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
//
//===----------------------------------------------------------------------===//
//
// LoggingTest+XCTest.swift
//
import XCTest
///
/// NOTE: This file was generated by generate_linux_tests.rb
///
/// Do NOT edit this file directly as it will be regenerated automatically when needed.
///
extension LoggingTest {
static var allTests: [(String, (LoggingTest) -> () throws -> Void)] {
return [
("testAutoclosure", testAutoclosure),
("testMultiplex", testMultiplex),
("testMultiplexLogHandlerWithVariousLogLevels", testMultiplexLogHandlerWithVariousLogLevels),
("testMultiplexLogHandlerNeedNotMaterializeValuesMultipleTimes", testMultiplexLogHandlerNeedNotMaterializeValuesMultipleTimes),
("testMultiplexLogHandlerMetadata_settingMetadataThroughToUnderlyingHandlers", testMultiplexLogHandlerMetadata_settingMetadataThroughToUnderlyingHandlers),
("testMultiplexLogHandlerMetadata_readingHandlerMetadata", testMultiplexLogHandlerMetadata_readingHandlerMetadata),
("testMultiplexMetadataProviderSet", testMultiplexMetadataProviderSet),
("testMultiplexMetadataProviderExtract", testMultiplexMetadataProviderExtract),
("testDictionaryMetadata", testDictionaryMetadata),
("testListMetadata", testListMetadata),
("testStringConvertibleMetadata", testStringConvertibleMetadata),
("testAutoClosuresAreNotForcedUnlessNeeded", testAutoClosuresAreNotForcedUnlessNeeded),
("testLocalMetadata", testLocalMetadata),
("testCustomFactory", testCustomFactory),
("testAllLogLevelsExceptCriticalCanBeBlocked", testAllLogLevelsExceptCriticalCanBeBlocked),
("testAllLogLevelsWork", testAllLogLevelsWork),
("testAllLogLevelByFunctionRefWithSource", testAllLogLevelByFunctionRefWithSource),
("testAllLogLevelByFunctionRefWithoutSource", testAllLogLevelByFunctionRefWithoutSource),
("testLogsEmittedFromSubdirectoryGetCorrectModuleInNewerSwifts", testLogsEmittedFromSubdirectoryGetCorrectModuleInNewerSwifts),
("testLogMessageWithStringInterpolation", testLogMessageWithStringInterpolation),
("testLoggingAString", testLoggingAString),
("testMultiplexMetadataProviderMergesInSpecifiedOrder", testMultiplexMetadataProviderMergesInSpecifiedOrder),
("testLoggerWithoutFactoryOverrideDefaultsToUsingLoggingSystemMetadataProvider", testLoggerWithoutFactoryOverrideDefaultsToUsingLoggingSystemMetadataProvider),
("testLoggerWithPredefinedLibraryMetadataProvider", testLoggerWithPredefinedLibraryMetadataProvider),
("testLoggerWithFactoryOverrideDefaultsToUsingLoggingSystemMetadataProvider", testLoggerWithFactoryOverrideDefaultsToUsingLoggingSystemMetadataProvider),
("testMultiplexerIsValue", testMultiplexerIsValue),
("testLoggerWithGlobalOverride", testLoggerWithGlobalOverride),
("testLogLevelCases", testLogLevelCases),
("testLogLevelOrdering", testLogLevelOrdering),
("testStreamLogHandlerWritesToAStream", testStreamLogHandlerWritesToAStream),
("testStreamLogHandlerOutputFormat", testStreamLogHandlerOutputFormat),
("testStreamLogHandlerOutputFormatWithMetaData", testStreamLogHandlerOutputFormatWithMetaData),
("testStreamLogHandlerOutputFormatWithOrderedMetadata", testStreamLogHandlerOutputFormatWithOrderedMetadata),
("testStreamLogHandlerWritesIncludeMetadataProviderMetadata", testStreamLogHandlerWritesIncludeMetadataProviderMetadata),
("testStdioOutputStreamWrite", testStdioOutputStreamWrite),
("testStdioOutputStreamFlush", testStdioOutputStreamFlush),
("testOverloadingError", testOverloadingError),
("testCompileInitializeStandardStreamLogHandlersWithMetadataProviders", testCompileInitializeStandardStreamLogHandlersWithMetadataProviders),
]
}
}
+138 -105
View File
@@ -22,11 +22,25 @@ import WinSDK
import Glibc
#endif
private extension LogHandler {
func with(logLevel: Logger.Level) -> any LogHandler {
var result = self
result.logLevel = logLevel
return result
}
func withMetadata(_ key: String, _ value: Logger.MetadataValue) -> any LogHandler {
var result = self
result.metadata[key] = value
return result
}
}
class LoggingTest: XCTestCase {
func testAutoclosure() throws {
// bootstrap with our test logging impl
let logging = TestLogging()
LoggingSystem.bootstrapInternal(logging.make)
LoggingSystem.bootstrapInternal { logging.make(label: $0) }
var logger = Logger(label: "test")
logger.logLevel = .info
@@ -80,11 +94,8 @@ class LoggingTest: XCTestCase {
let logging1 = TestLogging()
let logging2 = TestLogging()
var logger1 = logging1.make(label: "1")
logger1.logLevel = .info
var logger2 = logging2.make(label: "2")
logger2.logLevel = .debug
let logger1 = logging1.make(label: "1").with(logLevel: .info)
let logger2 = logging2.make(label: "2").with(logLevel: .debug)
LoggingSystem.bootstrapInternal { _ in
MultiplexLogHandler([logger1, logger2])
@@ -111,11 +122,8 @@ class LoggingTest: XCTestCase {
let logging1 = TestLogging()
let logging2 = TestLogging()
var logger1 = logging1.make(label: "1")
logger1.logLevel = .info
var logger2 = logging2.make(label: "2")
logger2.logLevel = .info
let logger1 = logging1.make(label: "1").with(logLevel: .info)
let logger2 = logging2.make(label: "2").with(logLevel: .info)
LoggingSystem.bootstrapInternal { _ in
MultiplexLogHandler([logger1, logger2])
@@ -147,12 +155,12 @@ class LoggingTest: XCTestCase {
let logging1 = TestLogging()
let logging2 = TestLogging()
var logger1 = logging1.make(label: "1")
logger1.metadata["one"] = "111"
logger1.metadata["in"] = "in-1"
var logger2 = logging2.make(label: "2")
logger2.metadata["two"] = "222"
logger2.metadata["in"] = "in-2"
let logger1 = logging1.make(label: "1")
.withMetadata("one", "111")
.withMetadata("in", "in-1")
let logger2 = logging2.make(label: "2")
.withMetadata("two", "222")
.withMetadata("in", "in-2")
LoggingSystem.bootstrapInternal { _ in
MultiplexLogHandler([logger1, logger2])
@@ -204,12 +212,12 @@ class LoggingTest: XCTestCase {
let logging1 = TestLogging()
let logging2 = TestLogging()
var logger1 = logging1.make(label: "1")
logger1.metadata["one"] = "111"
logger1.metadata["in"] = "in-1"
var logger2 = logging2.make(label: "2")
logger2.metadata["two"] = "222"
logger2.metadata["in"] = "in-2"
let logger1 = logging1.make(label: "1")
.withMetadata("one", "111")
.withMetadata("in", "in-1")
let logger2 = logging2.make(label: "2")
.withMetadata("two", "222")
.withMetadata("in", "in-2")
LoggingSystem.bootstrapInternal { _ in
MultiplexLogHandler([logger1, logger2])
@@ -228,20 +236,26 @@ class LoggingTest: XCTestCase {
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",
])
let handler1 = {
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",
])
return handler1
}()
let handler2 = {
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",
])
return handler2
}()
LoggingSystem.bootstrapInternal { _ in
MultiplexLogHandler([handler1, handler2])
@@ -268,18 +282,24 @@ class LoggingTest: XCTestCase {
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",
])
let handler1 = {
var handler1 = logging1.make(label: "1")
handler1.metadataProvider = .constant([
"provider-1": "provided-111",
"provider-overlap": "provided-111",
])
return handler1
}()
let handler2 = {
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",
])
return handler2
}()
LoggingSystem.bootstrapInternal({ _, metadataProvider in
MultiplexLogHandler(
@@ -307,7 +327,7 @@ class LoggingTest: XCTestCase {
func testDictionaryMetadata() {
let testLogging = TestLogging()
LoggingSystem.bootstrapInternal(testLogging.make)
LoggingSystem.bootstrapInternal { testLogging.make(label: $0) }
var logger = Logger(label: "\(#function)")
logger[metadataKey: "foo"] = ["bar": "buz"]
@@ -323,7 +343,7 @@ class LoggingTest: XCTestCase {
func testListMetadata() {
let testLogging = TestLogging()
LoggingSystem.bootstrapInternal(testLogging.make)
LoggingSystem.bootstrapInternal { testLogging.make(label: $0) }
var logger = Logger(label: "\(#function)")
logger[metadataKey: "foo"] = ["bar", "buz"]
@@ -366,7 +386,7 @@ class LoggingTest: XCTestCase {
func testStringConvertibleMetadata() {
let testLogging = TestLogging()
LoggingSystem.bootstrapInternal(testLogging.make)
LoggingSystem.bootstrapInternal { testLogging.make(label: $0) }
var logger = Logger(label: "\(#function)")
logger[metadataKey: "foo"] = .stringConvertible("raw-string")
@@ -386,7 +406,7 @@ class LoggingTest: XCTestCase {
func testAutoClosuresAreNotForcedUnlessNeeded() {
let testLogging = TestLogging()
LoggingSystem.bootstrapInternal(testLogging.make)
LoggingSystem.bootstrapInternal { testLogging.make(label: $0) }
var logger = Logger(label: "\(#function)")
logger.logLevel = .error
@@ -400,7 +420,7 @@ class LoggingTest: XCTestCase {
func testLocalMetadata() {
let testLogging = TestLogging()
LoggingSystem.bootstrapInternal(testLogging.make)
LoggingSystem.bootstrapInternal { testLogging.make(label: $0) }
var logger = Logger(label: "\(#function)")
logger.info("hello world!", metadata: ["foo": "bar"])
@@ -441,7 +461,7 @@ class LoggingTest: XCTestCase {
func testAllLogLevelsExceptCriticalCanBeBlocked() {
let testLogging = TestLogging()
LoggingSystem.bootstrapInternal(testLogging.make)
LoggingSystem.bootstrapInternal { testLogging.make(label: $0) }
var logger = Logger(label: "\(#function)")
logger.logLevel = .critical
@@ -465,7 +485,7 @@ class LoggingTest: XCTestCase {
func testAllLogLevelsWork() {
let testLogging = TestLogging()
LoggingSystem.bootstrapInternal(testLogging.make)
LoggingSystem.bootstrapInternal { testLogging.make(label: $0) }
var logger = Logger(label: "\(#function)")
logger.logLevel = .trace
@@ -489,7 +509,7 @@ class LoggingTest: XCTestCase {
func testAllLogLevelByFunctionRefWithSource() {
let testLogging = TestLogging()
LoggingSystem.bootstrapInternal(testLogging.make)
LoggingSystem.bootstrapInternal { testLogging.make(label: $0) }
var logger = Logger(label: "\(#function)")
logger.logLevel = .trace
@@ -521,7 +541,7 @@ class LoggingTest: XCTestCase {
func testAllLogLevelByFunctionRefWithoutSource() {
let testLogging = TestLogging()
LoggingSystem.bootstrapInternal(testLogging.make)
LoggingSystem.bootstrapInternal { testLogging.make(label: $0) }
var logger = Logger(label: "\(#function)")
logger.logLevel = .trace
@@ -534,7 +554,6 @@ class LoggingTest: XCTestCase {
let error = logger.error(_:metadata:file:function:line:)
let critical = logger.critical(_:metadata:file:function:line:)
#if compiler(>=5.3)
trace("yes: trace", [:], #fileID, #function, #line)
debug("yes: debug", [:], #fileID, #function, #line)
info("yes: info", [:], #fileID, #function, #line)
@@ -542,15 +561,6 @@ class LoggingTest: XCTestCase {
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)
#endif
testLogging.history.assertExist(level: .trace, message: "yes: trace")
testLogging.history.assertExist(level: .debug, message: "yes: debug")
@@ -563,18 +573,14 @@ class LoggingTest: XCTestCase {
func testLogsEmittedFromSubdirectoryGetCorrectModuleInNewerSwifts() {
let testLogging = TestLogging()
LoggingSystem.bootstrapInternal(testLogging.make)
LoggingSystem.bootstrapInternal { testLogging.make(label: $0) }
var logger = Logger(label: "\(#function)")
logger.logLevel = .trace
emitLogMessage("hello", to: logger)
#if compiler(>=5.3)
let moduleName = "LoggingTests" // the actual name
#else
let moduleName = "SubDirectoryOfLoggingTests" // the last path component of `#file` showing the failure mode
#endif
testLogging.history.assertExist(level: .trace, message: "hello", source: moduleName)
testLogging.history.assertExist(level: .debug, message: "hello", source: moduleName)
@@ -587,7 +593,7 @@ class LoggingTest: XCTestCase {
func testLogMessageWithStringInterpolation() {
let testLogging = TestLogging()
LoggingSystem.bootstrapInternal(testLogging.make)
LoggingSystem.bootstrapInternal { testLogging.make(label: $0) }
var logger = Logger(label: "\(#function)")
logger.logLevel = .debug
@@ -600,7 +606,7 @@ class LoggingTest: XCTestCase {
func testLoggingAString() {
let testLogging = TestLogging()
LoggingSystem.bootstrapInternal(testLogging.make)
LoggingSystem.bootstrapInternal { testLogging.make(label: $0) }
var logger = Logger(label: "\(#function)")
logger.logLevel = .debug
@@ -633,9 +639,8 @@ class LoggingTest: XCTestCase {
func testLoggerWithoutFactoryOverrideDefaultsToUsingLoggingSystemMetadataProvider() {
let logging = TestLogging()
LoggingSystem.bootstrapInternal({ label, metadataProvider in
logging.makeWithMetadataProvider(label: label, metadataProvider: metadataProvider)
}, metadataProvider: .init { ["provider": "42"] })
LoggingSystem.bootstrapInternal({ logging.makeWithMetadataProvider(label: $0, metadataProvider: $1) },
metadataProvider: .init { ["provider": "42"] })
let logger = Logger(label: #function)
@@ -649,7 +654,7 @@ class LoggingTest: XCTestCase {
func testLoggerWithPredefinedLibraryMetadataProvider() {
let logging = TestLogging()
LoggingSystem.bootstrapInternal(
logging.makeWithMetadataProvider,
{ logging.makeWithMetadataProvider(label: $0, metadataProvider: $1) },
metadataProvider: .exampleMetadataProvider
)
@@ -664,7 +669,8 @@ class LoggingTest: XCTestCase {
func testLoggerWithFactoryOverrideDefaultsToUsingLoggingSystemMetadataProvider() {
let logging = TestLogging()
LoggingSystem.bootstrapInternal(logging.makeWithMetadataProvider, metadataProvider: .init { ["provider": "42"] })
LoggingSystem.bootstrapInternal({ logging.makeWithMetadataProvider(label: $0, metadataProvider: $1) },
metadataProvider: .init { ["provider": "42"] })
let logger = Logger(label: #function, factory: { label in
logging.makeWithMetadataProvider(label: label, metadataProvider: LoggingSystem.metadataProvider)
@@ -700,11 +706,37 @@ class LoggingTest: XCTestCase {
logger1.error("hey")
}
/// Protects an object such that it can only be accessed while holding a lock.
private final class LockedValueBox<Value: Sendable>: @unchecked Sendable {
private let lock = Lock()
private var storage: Value
init(initialValue: Value) {
self.storage = initialValue
}
func withLock<Result>(_ operation: (Value) -> Result) -> Result {
self.lock.withLock {
operation(self.storage)
}
}
func withLockMutating(_ operation: (inout Value) -> Void) {
self.lock.withLockVoid {
operation(&self.storage)
}
}
var underlying: Value {
get { self.withLock { $0 } }
set { self.withLockMutating { $0 = newValue } }
}
}
func testLoggerWithGlobalOverride() {
struct LogHandlerWithGlobalLogLevelOverride: LogHandler {
// the static properties hold the globally overridden log level (if overridden)
private static let overrideLock = Lock()
private static var overrideLogLevel: Logger.Level?
private static let overrideLogLevel = LockedValueBox<Logger.Level?>(initialValue: nil)
private let recorder: Recorder
// this holds the log level if not overridden
@@ -720,9 +752,7 @@ class LoggingTest: XCTestCase {
var logLevel: Logger.Level {
// when we get asked for the log level, we check if it was globally overridden or not
get {
return LogHandlerWithGlobalLogLevelOverride.overrideLock.withLock {
LogHandlerWithGlobalLogLevelOverride.overrideLogLevel
} ?? self._logLevel
return LogHandlerWithGlobalLogLevelOverride.overrideLogLevel.underlying ?? self._logLevel
}
// we set the log level whenever we're asked (note: this might not have an effect if globally
// overridden)
@@ -747,9 +777,7 @@ class LoggingTest: XCTestCase {
// this is the function to globally override the log level, it is not part of the `LogHandler` protocol
static func overrideGlobalLogLevel(_ logLevel: Logger.Level) {
LogHandlerWithGlobalLogLevelOverride.overrideLock.withLock {
LogHandlerWithGlobalLogLevelOverride.overrideLogLevel = logLevel
}
LogHandlerWithGlobalLogLevelOverride.overrideLogLevel.underlying = logLevel
}
}
@@ -1021,7 +1049,7 @@ class LoggingTest: XCTestCase {
}
// bootstrap with our test logging impl
let logging = TestLogging()
LoggingSystem.bootstrapInternal(logging.make)
LoggingSystem.bootstrapInternal { logging.make(label: $0) }
var logger = Logger(label: "test")
logger.logLevel = .error
@@ -1038,8 +1066,8 @@ class LoggingTest: XCTestCase {
}
// default usage
LoggingSystem.bootstrap(StreamLogHandler.standardOutput)
LoggingSystem.bootstrap(StreamLogHandler.standardError)
LoggingSystem.bootstrap { (label: String) in StreamLogHandler.standardOutput(label: label) }
LoggingSystem.bootstrap { (label: String) in StreamLogHandler.standardError(label: label) }
// with metadata handler, explicitly, public api
LoggingSystem.bootstrap({ label, metadataProvider in
@@ -1050,26 +1078,33 @@ class LoggingTest: XCTestCase {
}, metadataProvider: .exampleMetadataProvider)
// with metadata handler, still pretty
LoggingSystem.bootstrap(StreamLogHandler.standardOutput, metadataProvider: .exampleMetadataProvider)
LoggingSystem.bootstrap(StreamLogHandler.standardError, metadataProvider: .exampleMetadataProvider)
LoggingSystem.bootstrap({ (label: String, metadataProvider: Logger.MetadataProvider?) in StreamLogHandler.standardOutput(label: label, metadataProvider: metadataProvider) },
metadataProvider: .exampleMetadataProvider)
LoggingSystem.bootstrap({ (label: String, metadataProvider: Logger.MetadataProvider?) in StreamLogHandler.standardError(label: label, metadataProvider: metadataProvider) },
metadataProvider: .exampleMetadataProvider)
}
func testLoggerIsJustHoldingASinglePointer() {
let expectedSize = MemoryLayout<UnsafeRawPointer>.size
XCTAssertEqual(MemoryLayout<Logger>.size, expectedSize)
}
func testLoggerCopyOnWrite() {
var logger1 = Logger(label: "foo")
logger1.logLevel = .error
var logger2 = logger1
logger2.logLevel = .trace
XCTAssertEqual(.error, logger1.logLevel)
XCTAssertEqual(.trace, logger2.logLevel)
}
}
extension Logger {
#if compiler(>=5.3)
public func error(error: Error,
public func error(error: any Error,
metadata: @autoclosure () -> Logger.Metadata? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line) {
self.error("\(error.localizedDescription)", metadata: metadata(), file: file, function: function, line: line)
}
#else
public func error(error: Error,
metadata: @autoclosure () -> Logger.Metadata? = nil,
file: String = #file, function: String = #function, line: UInt = #line) {
self.error("\(error.localizedDescription)", metadata: metadata(), file: file, function: function, line: line)
}
#endif
}
extension Logger.MetadataProvider {
@@ -1084,7 +1119,6 @@ extension Logger.MetadataProvider {
// 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 {}
@@ -1092,4 +1126,3 @@ 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
-31
View File
@@ -1,31 +0,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
//
//===----------------------------------------------------------------------===//
//
// MDCTest+XCTest.swift
//
import XCTest
///
/// NOTE: This file was generated by generate_linux_tests.rb
///
/// Do NOT edit this file directly as it will be regenerated automatically when needed.
///
extension MDCTest {
static var allTests: [(String, (MDCTest) -> () throws -> Void)] {
return [
("test1", test1),
]
}
}
+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: $0) }
// run the program
MDC.global["foo"] = "bar"
@@ -1,33 +0,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
//
//===----------------------------------------------------------------------===//
//
// MetadataProviderTest+XCTest.swift
//
import XCTest
///
/// NOTE: This file was generated by generate_linux_tests.rb
///
/// Do NOT edit this file directly as it will be regenerated automatically when needed.
///
extension MetadataProviderTest {
static var allTests: [(String, (MetadataProviderTest) -> () throws -> Void)] {
return [
("testLoggingMergesOneOffMetadataWithProvidedMetadataFromExplicitlyPassed", testLoggingMergesOneOffMetadataWithProvidedMetadataFromExplicitlyPassed),
("testLogHandlerThatDidNotImplementProvidersButSomeoneAttemptsToSetOneOnIt", testLogHandlerThatDidNotImplementProvidersButSomeoneAttemptsToSetOneOnIt),
("testLogHandlerThatDidImplementProvidersButSomeoneAttemptsToSetOneOnIt", testLogHandlerThatDidImplementProvidersButSomeoneAttemptsToSetOneOnIt),
]
}
}
@@ -25,7 +25,7 @@ import Glibc
final class MetadataProviderTest: XCTestCase {
func testLoggingMergesOneOffMetadataWithProvidedMetadataFromExplicitlyPassed() throws {
let logging = TestLogging()
LoggingSystem.bootstrapInternal(logging.makeWithMetadataProvider,
LoggingSystem.bootstrapInternal({ logging.makeWithMetadataProvider(label: $0, metadataProvider: $1) },
metadataProvider: .init { ["common": "initial"]
})
+11 -35
View File
@@ -17,12 +17,17 @@ import XCTest
#if os(Windows)
import WinSDK
#endif
#if compiler(>=6.0) || canImport(Darwin)
import Dispatch
#else
@preconcurrency import Dispatch
#endif
internal struct TestLogging {
private let _config = Config() // shared among loggers
private let recorder = Recorder() // shared among loggers
func make(label: String) -> LogHandler {
func make(label: String) -> some LogHandler {
return TestLogHandler(
label: label,
config: self.config,
@@ -31,7 +36,7 @@ internal struct TestLogging {
)
}
func makeWithMetadataProvider(label: String, metadataProvider: Logger.MetadataProvider?) -> LogHandler {
func makeWithMetadataProvider(label: String, metadataProvider: Logger.MetadataProvider?) -> (some LogHandler) {
return TestLogHandler(
label: label,
config: self.config,
@@ -41,7 +46,7 @@ internal struct TestLogging {
}
var config: Config { return self._config }
var history: History { return self.recorder }
var history: some History { return self.recorder }
}
internal struct TestLogHandler: LogHandler {
@@ -210,7 +215,6 @@ internal struct LogEntry {
}
extension History {
#if compiler(>=5.3)
func assertExist(level: Logger.Level,
message: String,
metadata: Logger.Metadata? = nil,
@@ -237,32 +241,6 @@ extension History {
file: file, line: line)
}
#else
func assertExist(level: Logger.Level,
message: String,
metadata: Logger.Metadata? = nil,
source: String? = nil,
file: StaticString = #file,
line: UInt = #line) {
let source = source ?? Logger.currentModule(filePath: "\(file)")
let entry = self.find(level: level, message: message, metadata: metadata, source: source)
XCTAssertNotNil(entry, "entry not found: \(level), \(source), \(String(describing: metadata)), \(message)",
file: file, line: line)
}
func assertNotExist(level: Logger.Level,
message: String,
metadata: Logger.Metadata? = nil,
source: String? = nil,
file: StaticString = #file,
line: UInt = #line) {
let source = source ?? Logger.currentModule(filePath: "\(file)")
let entry = self.find(level: level, message: message, metadata: metadata, source: source)
XCTAssertNil(entry, "entry was found: \(level), \(source), \(String(describing: metadata)), \(message)",
file: file, line: line)
}
#endif
func find(level: Logger.Level, message: String, metadata: Logger.Metadata? = nil, source: String) -> LogEntry? {
return self.entries.first { entry in
if entry.level != level {
@@ -303,7 +281,7 @@ public class MDC {
private let lock = NSLock()
private var storage = [Int: Logger.Metadata]()
public static var global = MDC()
public static let global = MDC()
private init() {}
@@ -379,7 +357,7 @@ internal extension NSLock {
}
}
internal struct TestLibrary {
internal struct TestLibrary: Sendable {
private let logger = Logger(label: "TestLibrary")
private let queue = DispatchQueue(label: "TestLibrary")
@@ -389,7 +367,7 @@ internal struct TestLibrary {
self.logger.info("TestLibrary::doSomething")
}
public func doSomethingAsync(completion: @escaping () -> Void) {
public func doSomethingAsync(completion: @escaping @Sendable() -> Void) {
// libraries that use global loggers and async, need to make sure they propagate the
// logging metadata when creating a new thread
let metadata = MDC.global.metadata
@@ -404,9 +382,7 @@ 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
+1 -4
View File
@@ -11,15 +11,13 @@
// 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)
LoggingSystem.bootstrapInternal { testLogging.make(label: $0) }
let logger = Logger(label: "test")
let message1 = Logger.Message(stringLiteral: "critical 1")
@@ -39,5 +37,4 @@ class SendableTest: XCTestCase {
testLogging.history.assertExist(level: .critical, message: "critical 2", metadata: [:])
testLogging.history.assertExist(level: .warning, message: "warning", metadata: metadata)
}
#endif
}
+2 -5
View File
@@ -16,11 +16,8 @@ ENV LANGUAGE en_US.UTF-8
RUN apt-get update && apt-get install -y wget
RUN apt-get update && apt-get install -y lsof dnsutils netcat-openbsd net-tools curl jq # used by integration tests
# ruby and jazzy for docs generation
RUN apt-get update && apt-get install -y ruby ruby-dev libsqlite3-dev build-essential
# jazzy no longer works on xenial as ruby is too old.
RUN if [ "${ubuntu_version}" = "focal" ] ; then echo "gem: --no-document" > ~/.gemrc; fi
RUN if [ "${ubuntu_version}" = "focal" ] ; then gem install jazzy; fi
# ruby for scripts
RUN apt-get update && apt-get install -y ruby
# tools
RUN mkdir -p $HOME/.tools
-16
View File
@@ -1,16 +0,0 @@
version: "3"
services:
runtime-setup:
image: swift-log:18.04-5.0
build:
args:
ubuntu_version: "bionic"
swift_version: "5.0"
test:
image: swift-log:18.04-5.0
shell:
image: swift-log:18.04-5.0
-18
View File
@@ -1,18 +0,0 @@
version: "3"
services:
runtime-setup:
image: swift-log:18.04-5.1
build:
args:
ubuntu_version: "bionic"
swift_version: "5.1"
test:
image: swift-log:18.04-5.1
environment: []
#- SANITIZER_ARG=--sanitize=thread
shell:
image: swift-log:18.04-5.1
-18
View File
@@ -1,18 +0,0 @@
version: "3"
services:
runtime-setup:
image: swift-log:18.04-5.2
build:
args:
ubuntu_version: "bionic"
swift_version: "5.2"
test:
image: swift-log:18.04-5.2
environment: []
#- SANITIZER_ARG=--sanitize=thread
shell:
image: swift-log:18.04-5.2
-18
View File
@@ -1,18 +0,0 @@
version: "3"
services:
runtime-setup:
image: swift-log:18.04-5.3
build:
args:
ubuntu_version: "bionic"
swift_version: "5.3"
test:
image: swift-log:18.04-5.3
environment: []
#- SANITIZER_ARG=--sanitize=thread
shell:
image: swift-log:18.04-5.3
-18
View File
@@ -1,18 +0,0 @@
version: "3"
services:
runtime-setup:
image: swift-log:20.04-5.4
build:
args:
ubuntu_version: "focal"
swift_version: "5.4"
test:
image: swift-log:20.04-5.4
environment: []
#- SANITIZER_ARG=--sanitize=thread
shell:
image: swift-log:20.04-5.4
-19
View File
@@ -1,19 +0,0 @@
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
@@ -1,19 +0,0 @@
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
-19
View File
@@ -1,19 +0,0 @@
version: "3"
services:
runtime-setup:
image: swift-log:20.04-5.7
build:
args:
ubuntu_version: "focal"
swift_version: "5.7"
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
+1 -1
View File
@@ -12,7 +12,7 @@ services:
test:
image: swift-log:20.04-5.8
environment:
- FORCE_TEST_DISCOVERY=--enable-test-discovery
- WARN_AS_ERROR_ARG=-Xswiftc -warnings-as-errors
#- SANITIZER_ARG=--sanitize=thread
shell:
+18
View File
@@ -0,0 +1,18 @@
version: "3"
services:
runtime-setup:
image: swift-log:22.04-5.10
build:
args:
base_image: "swiftlang/swift:nightly-5.10-jammy"
test:
image: swift-log:22.04-5.10
environment:
- WARN_AS_ERROR_ARG=-Xswiftc -warnings-as-errors
#- SANITIZER_ARG=--sanitize=thread
shell:
image: swift-log:22.04-5.10
+3 -2
View File
@@ -6,12 +6,13 @@ services:
image: swift-log:22.04-5.9
build:
args:
base_image: "swiftlang/swift:nightly-5.9-jammy"
ubuntu_version: "jammy"
swift_version: "5.9"
test:
image: swift-log:22.04-5.9
environment:
- FORCE_TEST_DISCOVERY=--enable-test-discovery
- WARN_AS_ERROR_ARG=-Xswiftc -warnings-as-errors
#- SANITIZER_ARG=--sanitize=thread
shell:
+4 -1
View File
@@ -11,8 +11,11 @@ services:
test:
image: swift-log:22.04-main
environment:
- FORCE_TEST_DISCOVERY=--enable-test-discovery
- WARN_AS_ERROR_ARG=-Xswiftc -warnings-as-errors
#- SANITIZER_ARG=--sanitize=thread
- IMPORT_CHECK_ARG=--explicit-target-dependency-import-check error
- EXPLICIT_SENDABLE_ARG=-Xswiftc -require-explicit-sendable
- STRICT_CONCURRENCY_ARG=-Xswiftc -strict-concurrency=complete
shell:
image: swift-log:22.04-main
+1 -1
View File
@@ -28,7 +28,7 @@ services:
test:
<<: *common
command: /bin/bash -xcl "swift test -Xswiftc -warnings-as-errors $${FORCE_TEST_DISCOVERY-} $${SANITIZER_ARG-}"
command: /bin/bash -xcl "swift test $${WARN_AS_ERROR_ARG-} $${SANITIZER_ARG-} $${IMPORT_CHECK_ARG-} $${EXPLICIT_SENDABLE_ARG-} $${STRICT_CONCURRENCY_ARG-}"
# util
-94
View File
@@ -1,94 +0,0 @@
#!/bin/bash
##===----------------------------------------------------------------------===##
##
## This source file is part of the Swift Logging API open source project
##
## Copyright (c) 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
##
##===----------------------------------------------------------------------===##
##===----------------------------------------------------------------------===##
##
## This source file is part of the SwiftNIO open source project
##
## Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
## Licensed under Apache License v2.0
##
## See LICENSE.txt for license information
## See CONTRIBUTORS.txt for the list of SwiftNIO project authors
##
## SPDX-License-Identifier: Apache-2.0
##
##===----------------------------------------------------------------------===##
set -eu
function usage() {
echo "$0 [-u] version"
echo
echo "OPTIONS:"
echo " -u: Additionally upload the podspec"
}
upload=false
while getopts ":u" opt; do
case $opt in
u)
upload=true
;;
\?)
usage
exit 1
;;
esac
done
shift "$((OPTIND-1))"
if [[ $# -eq 0 ]]; then
echo "Must provide target version"
exit 1
fi
version=$1
podspec_name="Logging"
here="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
tmpdir=$(mktemp -d /tmp/.build_podspecsXXXXXX)
echo "Building podspec in $tmpdir"
cat > "${tmpdir}/${podspec_name}.podspec" <<- EOF
Pod::Spec.new do |s|
s.name = '$podspec_name'
s.version = '$version'
s.license = { :type => 'Apache 2.0', :file => 'LICENSE.txt' }
s.summary = 'A Logging API for Swift.'
s.homepage = 'https://github.com/apple/swift-log'
s.author = 'Apple Inc.'
s.source = { :git => 'https://github.com/apple/swift-log.git', :tag => s.version.to_s }
s.documentation_url = 'https://apple.github.io/swift-log'
s.module_name = 'Logging'
s.swift_version = '5.0'
s.cocoapods_version = '>=1.6.0'
s.ios.deployment_target = '8.0'
s.osx.deployment_target = '10.9'
s.tvos.deployment_target = '9.0'
s.watchos.deployment_target = '2.0'
s.source_files = 'Sources/Logging/**/*.swift'
end
EOF
if $upload; then
echo "Uploading ${tmpdir}/${podspec_name}.podspec"
pod trunk push "${tmpdir}/${podspec_name}.podspec"
else
echo "Linting ${tmpdir}/${podspec_name}.podspec"
pod spec lint "${tmpdir}/${podspec_name}.podspec"
fi
+7 -75
View File
@@ -17,7 +17,7 @@
##
## This source file is part of the SwiftNIO open source project
##
## Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
## Copyright (c) 2017-2020 Apple Inc. and the SwiftNIO project authors
## Licensed under Apache License v2.0
##
## See LICENSE.txt for license information
@@ -29,44 +29,15 @@
set -eu
# repodir
function all_modules() {
local repodir="$1"
(
set -eu
cd "$repodir"
swift package dump-package | jq '.products |
map(select(.type | has("library") )) |
map(.name) | .[]' | tr -d '"'
)
}
# repodir tag output
function build_and_do() {
local repodir=$1
local tag=$2
local output=$3
(
cd "$repodir"
git checkout -q "$tag"
swift build
while read -r module; do
swift api-digester -sdk "$sdk" -dump-sdk -module "$module" \
-o "$output/$module.json" -I "$repodir/.build/debug"
done < <(all_modules "$repodir")
)
}
function usage() {
echo >&2 "Usage: $0 REPO-GITHUB-URL NEW-VERSION OLD-VERSIONS..."
echo >&2
echo >&2 "This script requires a Swift 5.1+ toolchain."
echo >&2 "This script requires a Swift 5.2+ toolchain."
echo >&2
echo >&2 "Examples:"
echo >&2
echo >&2 "Check between master and tag 2.1.1 of swift-nio:"
echo >&2 " $0 https://github.com/apple/swift-nio master 2.1.1"
echo >&2 "Check between main and tag 2.1.1 of swift-nio:"
echo >&2 " $0 https://github.com/apple/swift-nio main 2.1.1"
echo >&2
echo >&2 "Check between HEAD and commit 64cf63d7 using the provided toolchain:"
echo >&2 " xcrun --toolchain org.swift.5120190702a $0 ../some-local-repo HEAD 64cf63d7"
@@ -77,12 +48,6 @@ if [[ $# -lt 3 ]]; then
exit 1
fi
sdk=/
if [[ "$(uname -s)" == Darwin ]]; then
sdk=$(xcrun --show-sdk-path)
fi
hash jq 2> /dev/null || { echo >&2 "ERROR: jq must be installed"; exit 1; }
tmpdir=$(mktemp -d /tmp/.check-api_XXXXXX)
repo_url=$1
new_tag=$2
@@ -91,46 +56,13 @@ shift 2
repodir="$tmpdir/repo"
git clone "$repo_url" "$repodir"
git -C "$repodir" fetch -q origin '+refs/pull/*:refs/remotes/origin/pr/*'
errors=0
cd "$repodir"
git checkout -q "$new_tag"
for old_tag in "$@"; do
mkdir "$tmpdir/api-old"
mkdir "$tmpdir/api-new"
echo "Checking public API breakages from $old_tag to $new_tag"
build_and_do "$repodir" "$new_tag" "$tmpdir/api-new/"
build_and_do "$repodir" "$old_tag" "$tmpdir/api-old/"
for f in "$tmpdir/api-new"/*; do
f=$(basename "$f")
report="$tmpdir/$f.report"
if [[ ! -f "$tmpdir/api-old/$f" ]]; then
echo "NOTICE: NEW MODULE $f"
continue
fi
echo -n "Checking $f... "
swift api-digester -sdk "$sdk" -diagnose-sdk \
--input-paths "$tmpdir/api-old/$f" -input-paths "$tmpdir/api-new/$f" 2>&1 \
> "$report" 2>&1
if ! shasum "$report" | grep -q cefc4ee5bb7bcdb7cb5a7747efa178dab3c794d5; then
echo ERROR
echo >&2 "=============================="
echo >&2 "ERROR: public API change in $f"
echo >&2 "=============================="
cat >&2 "$report"
errors=$(( errors + 1 ))
else
echo OK
fi
done
rm -rf "$tmpdir/api-new" "$tmpdir/api-old"
swift package diagnose-api-breaking-changes "$old_tag"
done
if [[ "$errors" == 0 ]]; then
echo "OK, all seems good"
fi
echo done
exit "$errors"
-112
View File
@@ -1,112 +0,0 @@
#!/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.txt for the list of Swift Logging API project authors
##
## SPDX-License-Identifier: Apache-2.0
##
##===----------------------------------------------------------------------===##
set -ex
my_path="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
root_path="$my_path/.."
version=$(git describe --abbrev=0 --tags || echo "0.0.0")
modules=(Logging)
if [[ "$(uname -s)" == "Linux" ]]; then
# build code if required
if [[ ! -d "$root_path/.build/x86_64-unknown-linux" ]]; then
swift build
fi
# setup source-kitten if required
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/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
for module in "${modules[@]}"; do
if [[ ! -f "$root_path/.build/sourcekitten/$module.json" ]]; then
"$source_kitten_path/sourcekitten" doc --spm --module-name $module > "$root_path/.build/sourcekitten/$module.json"
fi
done
fi
[[ -d docs/$version ]] || mkdir -p docs/$version
[[ -d swift-log.xcodeproj ]] || swift package generate-xcodeproj
# run jazzy
if ! command -v jazzy > /dev/null; then
gem install jazzy --no-ri --no-rdoc
fi
jazzy_dir="$root_path/.build/jazzy"
rm -rf "$jazzy_dir"
mkdir -p "$jazzy_dir"
module_switcher="$jazzy_dir/README.md"
jazzy_args=(--clean
--author 'SwiftLog team'
--readme "$module_switcher"
--author_url https://github.com/apple/swift-log
--github_url https://github.com/apple/swift-log
--github-file-prefix https://github.com/apple/swift-log/tree/$version
--theme fullwidth
--xcodebuild-arguments -scheme,swift-log-Package)
cat > "$module_switcher" <<"EOF"
# SwiftLog Docs
SwiftLog is a Swift logging API package.
To get started with SwiftLog, [`import Logging`](../Logging/index.html). The
most important type is [`Logger`](https://apple.github.io/swift-log/docs/current/Logging/Structs/Logger.html)
which you can use to emit log messages.
EOF
for module in "${modules[@]}"; do
args=("${jazzy_args[@]}" --output "$jazzy_dir/docs/$version/$module" --docset-path "$jazzy_dir/docset/$version/$module"
--module "$module" --module-version $version
--root-url "https://apple.github.io/swift-log/docs/$version/$module/")
if [[ -f "$root_path/.build/sourcekitten/$module.json" ]]; then
args+=(--sourcekitten-sourcefile "$root_path/.build/sourcekitten/$module.json")
fi
jazzy "${args[@]}"
done
# push to github pages
if [[ $PUSH == true ]]; then
BRANCH_NAME=$(git rev-parse --abbrev-ref HEAD)
GIT_AUTHOR=$(git --no-pager show -s --format='%an <%ae>' HEAD)
git fetch origin +gh-pages:gh-pages
git checkout gh-pages
rm -rf "docs/$version"
rm -rf "docs/current"
cp -r "$jazzy_dir/docs/$version" docs/
cp -r "docs/$version" docs/current
git add --all docs
echo '<html><head><meta http-equiv="refresh" content="0; url=docs/current/Logging/index.html" /></head></html>' > index.html
git add index.html
touch .nojekyll
git add .nojekyll
changes=$(git diff-index --name-only HEAD)
if [[ -n "$changes" ]]; then
echo -e "changes detected\n$changes"
git commit --author="$GIT_AUTHOR" -m "publish $version docs"
git push origin gh-pages
else
echo "no changes detected"
fi
git checkout -f $BRANCH_NAME
fi
-231
View File
@@ -1,231 +0,0 @@
#!/usr/bin/env ruby
#
# process_test_files.rb
#
# Copyright 2016 Tony Stone
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Created by Tony Stone on 5/4/16.
#
require 'getoptlong'
require 'fileutils'
require 'pathname'
include FileUtils
#
# This ruby script will auto generate LinuxMain.swift and the +XCTest.swift extension files for Swift Package Manager on Linux platforms.
#
# See https://github.com/apple/swift-corelibs-xctest/blob/master/Documentation/Linux.md
#
def header(fileName)
string = <<-eos
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// <FileName>
//
import XCTest
///
/// NOTE: This file was generated by generate_linux_tests.rb
///
/// Do NOT edit this file directly as it will be regenerated automatically when needed.
///
eos
string
.sub('<FileName>', File.basename(fileName))
.sub('<Date>', Time.now.to_s)
end
def createExtensionFile(fileName, classes)
extensionFile = fileName.sub! '.swift', '+XCTest.swift'
print 'Creating file: ' + extensionFile + "\n"
File.open(extensionFile, 'w') do |file|
file.write header(extensionFile)
file.write "\n"
for classArray in classes
file.write 'extension ' + classArray[0] + " {\n"
file.write ' static var allTests: [(String, (' + classArray[0] + ") -> () throws -> Void)] {\n"
file.write " return [\n"
for funcName in classArray[1]
file.write ' ("' + funcName + '", ' + funcName + "),\n"
end
file.write " ]\n"
file.write " }\n"
file.write "}\n"
end
end
end
def createLinuxMain(testsDirectory, allTestSubDirectories, files)
fileName = testsDirectory + '/LinuxMain.swift'
print 'Creating file: ' + fileName + "\n"
File.open(fileName, 'w') do |file|
file.write header(fileName)
file.write "\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
file.write "\n"
file.write "XCTMain([\n"
testCases = []
for classes in files
for classArray in classes
testCases << classArray[0]
end
end
for testCase in testCases.sort { |x, y| x <=> y }
file.write ' testCase(' + testCase + ".allTests),\n"
end
file.write "])\n"
file.write "#endif\n"
end
end
def parseSourceFile(fileName)
puts 'Parsing file: ' + fileName + "\n"
classes = []
currentClass = nil
inIfLinux = false
inElse = false
ignore = false
#
# Read the file line by line
# and parse to find the class
# names and func names
#
File.readlines(fileName).each do |line|
if inIfLinux
if /\#else/.match(line)
inElse = true
ignore = true
else
if /\#end/.match(line)
inElse = false
inIfLinux = false
ignore = false
end
end
else
if /\#if[ \t]+os\(Linux\)/.match(line)
inIfLinux = true
ignore = false
end
end
next if ignore
# Match class or func
match = line[/class[ \t]+[a-zA-Z0-9_]*(?=[ \t]*:[ \t]*XCTestCase)|func[ \t]+test[a-zA-Z0-9_]*(?=[ \t]*\(\))/, 0]
if match
if match[/class/, 0] == 'class'
className = match.sub(/^class[ \t]+/, '')
#
# Create a new class / func structure
# and add it to the classes array.
#
currentClass = [className, []]
classes << currentClass
else # Must be a func
funcName = match.sub(/^func[ \t]+/, '')
#
# Add each func name the the class / func
# structure created above.
#
currentClass[1] << funcName
end
end
end
classes
end
#
# Main routine
#
#
testsDirectory = 'Tests'
options = GetoptLong.new(['--tests-dir', GetoptLong::OPTIONAL_ARGUMENT])
options.quiet = true
begin
options.each do |option, value|
case option
when '--tests-dir'
testsDirectory = value
end
end
rescue GetoptLong::InvalidOption
end
allTestSubDirectories = []
allFiles = []
Dir[testsDirectory + '/*'].each do |subDirectory|
next unless File.directory?(subDirectory)
directoryHasClasses = false
Dir[subDirectory + '/*Test{s,}.swift'].each do |fileName|
next unless File.file? fileName
fileClasses = parseSourceFile(fileName)
#
# If there are classes in the
# test source file, create an extension
# file for it.
#
next unless fileClasses.count > 0
createExtensionFile(fileName, fileClasses)
directoryHasClasses = true
allFiles << fileClasses
end
if directoryHasClasses
allTestSubDirectories << Pathname.new(subDirectory).split.last.to_s
end
end
#
# Last step is the create a LinuxMain.swift file that
# references all the classes and funcs in the source files.
#
if allFiles.count > 0
createLinuxMain(testsDirectory, allTestSubDirectories, allFiles)
end
# eof
+1 -1
View File
@@ -7,7 +7,7 @@
## Licensed under Apache License v2.0
##
## See LICENSE.txt for license information
## See CONTRIBUTORS.md for the list of Swift Logging API project authors
## See CONTRIBUTORS.txt for the list of Swift Logging API project authors
##
## SPDX-License-Identifier: Apache-2.0
##
+1 -13
View File
@@ -35,18 +35,6 @@ function replace_acceptable_years() {
sed -e 's/20[12][789012]-20[12][89012]/YEARS/' -e 's/20[12][89012]/YEARS/'
}
printf "=> Checking linux tests... "
FIRST_OUT="$(git status --porcelain)"
ruby "$here/../scripts/generate_linux_tests.rb" > /dev/null
SECOND_OUT="$(git status --porcelain)"
if [[ "$FIRST_OUT" != "$SECOND_OUT" ]]; then
printf "\033[0;31mmissing changes!\033[0m\n"
git --no-pager diff
exit 1
else
printf "\033[0;32mokay.\033[0m\n"
fi
printf "=> Checking for unacceptable language... "
# This greps for unacceptable terminology. The square bracket[s] are so that
# "git grep" doesn't find the lines that greps :).
@@ -86,7 +74,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 Package-swift5.6.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 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"
//===----------------------------------------------------------------------===//