Compare commits

..
32 Commits
Author SHA1 Message Date
Johannes Weiss ce592ae52f remove superfluous whitespace (#366)
### Motivation:

`StreamLogHandler` has at some point in time acquired an extra
whitespace:

```
2025-07-18T10:09:12+0100 notice label : hello
                                     ^
                                     |
                                     this one is superfluous
```

but we don't typically put spaces in front of `:`s. This PR changes it
to

```
2025-07-18T10:09:12+0100 notice label: hello
                                     ^
                                     |
                                     no extra space
```

Additionally, if the label is empty (`""`), then we shouldn't print any
spaces there. So with an empty label, we go from

```
2025-07-18T10:09:12+0100 notice  : hello
                               ^^
                                |
                                two superfluous spaces
```

to

```
2025-07-18T10:09:12+0100 notice: hello
                               ^
                               |
                               no extra spaces
```



### Modifications:

- Remove superfluous space if label is not empty
- Remove two superfluous spaces if label is empty

### Result:

- Somewhat more compact output
- Nicer output
2025-07-18 09:27:45 +00:00
Si Beaumont e1600be8ec Fix broken link to documentation on README (#365) 2025-07-17 09:08:32 +00:00
Franz Busch cbd28c274b Add an article how to implement a log handler (#364)
# Motivation

In my previous PR, I overhauled the README and the DocC catalog. While
doing this I removed the guidance around how to implement a log handler.

# Modifications

This PR adds a DocC based guide containing the contents of the previous
README guidance.

# Result

Guidance around log handler implementation in a modern DocC format.
2025-07-09 19:06:26 +02:00
Franz Busch c05d67286c Overhaul README and documentation catalog to introduce best practices (#363)
# Motivation

`SwiftLog` was created before DocC existed which meant that most of the
documentation was part of the `README` and we had a pretty bare bones
documentation catalog. We also have a second source of guidelines from
the SSWG. This results in a currently unsatisfying developer experience
where everyone has to go around looking for the content in mostly
undocumented places.

# Modifications

This PR overhauls the `README` and moves most of the content into the
documentation catalog. It also introduces a new section called "Best
practices" that are intended to replace the logging guides on swift.org
so that the content moves closer to where it belongs. To showcase such a
best practice this PR brings over the log level recommendation of
swift.org. The recommendation is mostly the same except that after
recent discussions we wanted to allow libraries to log at `info` level
when they encounter problems which they can't communicate through other
channels e.g. by throwing from a method.

# Result

With this PR we provide a nicer experience to our developers making it
easier for them to get started and understand how to properly log. We
also set ourselves up for expanding on the best practices around
logging.
2025-07-09 16:48:56 +02:00
Gwynne RaskindandFranz Busch 2281e43060 Remove inaccurate code comment (#349)
Remove an inaccurate comment from the code.

### Motivation:

The removed comment incorrectly described the `flush()` method as not
having an effect when the flush mode is set to `.always`. Not only is
this the opposite of the actual behavior, in fact the method itself is
not affected by the flush mode at all; that check is made elsewhere.
Further, at the point where the check is made, the behavior is clearly
spelled out by the code making the check, so moving the comment there
seems redundant. As such, it seemed best to simply remove it altogether.

### Modifications:

Removed a comment.

### Result:

The inaccurate comment can no longer cause confusion.

Co-authored-by: Franz Busch <f.busch@apple.com>
2025-07-08 19:12:15 +00:00
Rick Newton-Rogers 81d3d07f14 Enable Swift 6.1 jobs in CI (#359)
Motivation:

Swift 6.1 has been released, we should add it to our CI coverage.

Modifications:

Add additional Swift 6.1 jobs where appropriate in main.yml,
pull_request.yml

Result:

Improved test coverage.
2025-04-14 12:15:58 +02:00
Rick Newton-Rogers 09c99dd25a Add static SDK CI workflow (#355)
Add static SDK CI workflow which runs on commits to PRs, merges to main
and daily on main.
2025-04-02 13:41:15 +00:00
Marc Prud'hommeaux 748d1eb5d9 Android test fixes (#356) 2025-04-01 10:35:06 +00:00
Rick Newton-Rogers 765db8bc47 Enable macOS CI on pull requests (#358)
Motivation:

* Improve test coverage

Modifications:

Enable macOS CI to be run on pull request commits and make the use of
the nightly runner pool for main.yml jobs explicit.

Result:

Improved test coverage.
2025-04-01 12:25:50 +02:00
Rick Newton-Rogers 222bf1b48b Enable macOS CI on merge to main and daily timer (#357)
Motivation:

* Improve test coverage
* Check test pass/fail status
* Monitor CI throughput

Modifications:

Enable macOS CI to be run on all merges to main and on a daily timer.

Result:

Improved test coverage run out-of-band at the moment so we can get a
feeling for if any changes need to be made in the repo or in the CI
pipelines to ensure timely and stable checks.
2025-03-31 13:29:37 +01:00
Honza Dvorsky 3d8596ed08 Fix building on Fedora 39 and Ubuntu 24.04 (#354)
### Motivation:

Fixes https://github.com/apple/swift-log/issues/278.

### Modifications:

Fixed tests to successfully compile on Fedora 39 and Ubuntu 24.04, which
they previously failed on.

### Result:

Ability to run tests on these two platforms again.
2025-03-12 11:48:26 +00:00
Rick Newton-Rogers 3a9d8c908f Only apply standard swift settings on valid targets (#353)
Only apply standard swift settings on valid targets. The current check
ignores plugins but that is not comprehensive enough.
2025-03-07 19:35:11 +01:00
Rick Newton-Rogers 2dd04b00f4 Rename nightly_6_1 params to nightly_next (#352)
Rename nightly_6_1 params to nightly_next; see
https://github.com/apple/swift-nio/pull/3122
2025-03-04 10:38:13 +00:00
Rick Newton-Rogers 770059c51d CI use 6.1 nightlies (#348)
CI use 6.1 nightlies now that Swift development is happening in the 6.1
branch
2025-01-31 09:58:02 +00:00
Luke Howard f82ce9631f Add swift-log-systemd has moved (#345) (#346)
swift-log-systemd has been merged into the umbrella swift-systemd
package
2025-01-12 11:59:36 +01:00
9576fd5710 fix: fix typo (#333)
Co-authored-by: Sunset Wan <sunset.wan@assaabloy.com>
Co-authored-by: Konrad `ktoso` Malawski <konrad_malawski@apple.com>
2025-01-07 11:06:00 +00:00
Luke Howard 8f746b0f16 Add swift-log-systemd.git to the list of available backends (#345) (#345)
systemd-based log integration

### Motivation:

Using native backend for storing log data

### Modifications:

Add swift-log-systemd to the list of available backends

### Result:

Another one option to use the package with
2025-01-07 10:45:11 +00:00
Franz Busch 6efb781a29 Update release.yml (#344)
Update the release.yml file with the latest label changes
2024-12-18 14:18:53 +01:00
Rick Newton-Rogers 9e1494a076 Enable MemberImportVisibility check on all targets (#343)
Enable MemberImportVisibility check on all targets. Use a standard
string header and footer to bracket the new block for ease of updating
in the future with scripts.
2024-12-11 10:51:35 +00:00
Honza Dvorsky 960b23e33f Enable strict concurrency (#342) 2024-11-29 23:27:51 +01:00
Luke Howard 18cc7907d6 Add AndroidLogging to the list of available backends (#340)
Add AndroidLogging to the list of available backends.
2024-11-29 11:46:44 +00:00
Franz Busch 9bc47c93fa Aligning semantic version label check name (#341) 2024-11-28 13:00:19 +01:00
Mikhail Kasianov 96a2f8a0fa Add Scout to the list of available backends (#337)
* Add Scout to the list of available backends

* Update README.md
2024-11-25 17:24:15 +00:00
Rick Newton-Rogers 0e75c43ee4 add .editorconfig file (#338) 2024-11-14 17:01:02 +01:00
LamTrinh.Dev 5f816304f9 Enhance swift codeblock at README.md (#327) 2024-11-13 13:38:45 +00:00
Franz Busch 1efe6f8129 Fix Windows warnings (#331)
# Motivation

Fixes https://github.com/apple/swift-log/issues/330.

We had a few warnings since we were using deprecated POSIX methods on Windows.

# Modification

Moves to the non-deprecated underscored methods.

# Result

Windows build is warning free.
2024-10-31 11:55:18 +01:00
Franz Busch ee1bfd3f47 [CI] Migrate to GHA (#328)
# Motivation

We want to modernize our CI.

# Modification

This PR migrates to GH actions and turns on all the right flags.

# Result

Modern CI.
2024-10-30 13:17:15 +00:00
LamTrinh.Dev da3fdd167f Correct the link of incubation-process at README.md (#326) 2024-10-09 00:22:10 -07:00
Alex Lorenz d03205626d add android support (#325) 2024-10-01 08:23:03 +09:00
LamTrinh.Dev 2cb03fa60e Correct the link of sswg-security at SECURITY.md (#318) 2024-09-19 02:00:49 -07:00
b1ackturtle db86ac725b Fix compile warnings for Swift 6 language mode (#313) 2024-06-25 11:53:51 -07:00
George Barnett 9cb486020e Disable existential any build setting (#312)
Motivation:

On 5.8, if the experiment existential any setting is enabled and a
consuming package holds an existential of a type from swift-log without
an explicit 'any' then the build will fail.

Modifications:

- Disable the setting

Result:

Users of 5.8 aren't broken
2024-06-24 18:21:21 +01:00
38 changed files with 1915 additions and 1173 deletions

No files matched your search

+8
View File
@@ -0,0 +1,8 @@
root = true
[*]
indent_style = space
indent_size = 4
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
+14
View File
@@ -0,0 +1,14 @@
changelog:
categories:
- title: SemVer Major
labels:
- ⚠️ semver/major
- title: SemVer Minor
labels:
- 🆕 semver/minor
- title: SemVer Patch
labels:
- 🔨 semver/patch
- title: Other Changes
labels:
- semver/none
+43
View File
@@ -0,0 +1,43 @@
name: Main
on:
push:
branches: [main]
schedule:
- cron: "0 8,20 * * *"
jobs:
unit-tests:
name: Unit tests
uses: apple/swift-nio/.github/workflows/unit_tests.yml@main
with:
linux_5_9_arguments_override: "--explicit-target-dependency-import-check error"
linux_5_10_arguments_override: "--explicit-target-dependency-import-check error"
linux_6_0_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
linux_6_1_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
linux_nightly_next_arguments_override: "--explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
linux_nightly_main_arguments_override: "--explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
windows_6_0_enabled: true
windows_6_1_enabled: true
windows_nightly_next_enabled: true
windows_nightly_main_enabled: true
windows_6_0_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
windows_6_1_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
windows_nightly_next_arguments_override: "--explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
windows_nightly_main_arguments_override: "--explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
cxx-interop:
name: Cxx interop
uses: apple/swift-nio/.github/workflows/cxx_interop.yml@main
static-sdk:
name: Static SDK
# Workaround https://github.com/nektos/act/issues/1875
uses: apple/swift-nio/.github/workflows/static_sdk.yml@main
macos-tests:
name: macOS tests
uses: apple/swift-nio/.github/workflows/macos_tests.yml@main
with:
runner_pool: nightly
build_scheme: swift-log
+47
View File
@@ -0,0 +1,47 @@
name: PR
on:
pull_request:
types: [opened, reopened, synchronize]
jobs:
soundness:
name: Soundness
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@main
with:
license_header_check_project_name: "Swift Logging API"
unit-tests:
name: Unit tests
uses: apple/swift-nio/.github/workflows/unit_tests.yml@main
with:
linux_5_9_arguments_override: "--explicit-target-dependency-import-check error"
linux_5_10_arguments_override: "--explicit-target-dependency-import-check error"
linux_6_0_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
linux_6_1_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
linux_nightly_next_arguments_override: "--explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
linux_nightly_main_arguments_override: "--explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
windows_6_0_enabled: true
windows_6_1_enabled: true
windows_nightly_next_enabled: true
windows_nightly_main_enabled: true
windows_6_0_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
windows_6_1_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
windows_nightly_next_arguments_override: "--explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
windows_nightly_main_arguments_override: "--explicit-target-dependency-import-check error -Xswiftc -require-explicit-sendable"
cxx-interop:
name: Cxx interop
uses: apple/swift-nio/.github/workflows/cxx_interop.yml@main
static-sdk:
name: Static SDK
# Workaround https://github.com/nektos/act/issues/1875
uses: apple/swift-nio/.github/workflows/static_sdk.yml@main
macos-tests:
name: macOS tests
uses: apple/swift-nio/.github/workflows/macos_tests.yml@main
with:
runner_pool: general
build_scheme: swift-log
+18
View File
@@ -0,0 +1,18 @@
name: PR label
on:
pull_request:
types: [labeled, unlabeled, opened, reopened, synchronize]
jobs:
semver-label-check:
name: Semantic version label check
runs-on: ubuntu-latest
timeout-minutes: 1
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
persist-credentials: false
- name: Check for Semantic Version label
uses: apple/swift-nio/.github/actions/pull_request_semver_label_checker@main
+42
View File
@@ -0,0 +1,42 @@
.gitignore
**/.gitignore
.licenseignore
.unacceptablelanguageignore
.gitattributes
.git-blame-ignore-revs
.mailfilter
.mailmap
.spi.yml
.swift-format
.editorconfig
.github/*
*.md
*.txt
*.yml
*.yaml
*.json
Package.swift
**/Package.swift
Package@-*.swift
**/Package@-*.swift
Package.resolved
**/Package.resolved
Makefile
*.modulemap
**/*.modulemap
**/*.docc/*
*.xcprivacy
**/*.xcprivacy
*.symlink
**/*.symlink
Dockerfile
**/Dockerfile
Snippets/*
dev/git.commit.template
dev/update-benchmark-thresholds
*.crt
**/*.crt
*.pem
**/*.pem
*.der
**/*.der
+62
View File
@@ -0,0 +1,62 @@
{
"version" : 1,
"indentation" : {
"spaces" : 4
},
"tabWidth" : 4,
"fileScopedDeclarationPrivacy" : {
"accessLevel" : "private"
},
"spacesAroundRangeFormationOperators" : false,
"indentConditionalCompilationBlocks" : false,
"indentSwitchCaseLabels" : false,
"lineBreakAroundMultilineExpressionChainComponents" : false,
"lineBreakBeforeControlFlowKeywords" : false,
"lineBreakBeforeEachArgument" : true,
"lineBreakBeforeEachGenericRequirement" : true,
"lineLength" : 120,
"maximumBlankLines" : 1,
"respectsExistingLineBreaks" : true,
"prioritizeKeepingFunctionOutputTogether" : true,
"rules" : {
"AllPublicDeclarationsHaveDocumentation" : false,
"AlwaysUseLiteralForEmptyCollectionInit" : false,
"AlwaysUseLowerCamelCase" : false,
"AmbiguousTrailingClosureOverload" : true,
"BeginDocumentationCommentWithOneLineSummary" : false,
"DoNotUseSemicolons" : true,
"DontRepeatTypeInStaticProperties" : true,
"FileScopedDeclarationPrivacy" : true,
"FullyIndirectEnum" : true,
"GroupNumericLiterals" : true,
"IdentifiersMustBeASCII" : true,
"NeverForceUnwrap" : false,
"NeverUseForceTry" : false,
"NeverUseImplicitlyUnwrappedOptionals" : false,
"NoAccessLevelOnExtensionDeclaration" : true,
"NoAssignmentInExpressions" : true,
"NoBlockComments" : true,
"NoCasesWithOnlyFallthrough" : true,
"NoEmptyTrailingClosureParentheses" : true,
"NoLabelsInCasePatterns" : true,
"NoLeadingUnderscores" : false,
"NoParensAroundConditions" : true,
"NoVoidReturnOnFunctionSignature" : true,
"OmitExplicitReturns" : true,
"OneCasePerLine" : true,
"OneVariableDeclarationPerLine" : true,
"OnlyOneTrailingClosureArgument" : true,
"OrderedImports" : true,
"ReplaceForEachWithForLoop" : true,
"ReturnVoidInsteadOfEmptyTuple" : true,
"UseEarlyExits" : false,
"UseExplicitNilCheckInConditions" : false,
"UseLetInEveryBoundCaseVariable" : false,
"UseShorthandTypeNames" : true,
"UseSingleLinePropertyGetter" : false,
"UseSynthesizedInitializer" : false,
"UseTripleSlashForDocumentationComments" : true,
"UseWhereClausesInForLoops" : false,
"ValidateDocumentationComments" : false
}
}
-15
View File
@@ -1,15 +0,0 @@
# file options
--swiftversion 5.0
--exclude .build
# format options
--self insert
--patternlet inline
--stripunusedargs unnamed-only
--ifdef no-indent
# rules
--disable redundantParens # https://github.com/nicklockwood/SwiftFormat/issues/638
+26 -10
View File
@@ -1,4 +1,4 @@
// swift-tools-version:5.8
// swift-tools-version:5.9
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Logging API open source project
@@ -15,25 +15,41 @@
import PackageDescription
let swiftSettings: [SwiftSetting] = [
.enableUpcomingFeature("ExistentialAny"),
]
let package = Package(
name: "swift-log",
products: [
.library(name: "Logging", targets: ["Logging"]),
.library(name: "Logging", targets: ["Logging"])
],
targets: [
.target(
name: "Logging",
dependencies: [],
swiftSettings: swiftSettings
dependencies: []
),
.testTarget(
name: "LoggingTests",
dependencies: ["Logging"],
swiftSettings: swiftSettings
dependencies: ["Logging"]
),
]
)
for target in package.targets {
var settings = target.swiftSettings ?? []
settings.append(.enableExperimentalFeature("StrictConcurrency=complete"))
target.swiftSettings = settings
}
// --- STANDARD CROSS-REPO SETTINGS DO NOT EDIT --- //
for target in package.targets {
switch target.type {
case .regular, .test, .executable:
var settings = target.swiftSettings ?? []
// https://github.com/swiftlang/swift-evolution/blob/main/proposals/0444-member-import-visibility.md
settings.append(.enableUpcomingFeature("MemberImportVisibility"))
target.swiftSettings = settings
case .macro, .plugin, .system, .binary:
() // not applicable
@unknown default:
() // we don't know what to do here, do nothing
}
}
// --- END: STANDARD CROSS-REPO SETTINGS DO NOT EDIT --- //
+46 -201
View File
@@ -1,219 +1,64 @@
# SwiftLog
First things first: This is the beginning of a community-driven open-source project actively seeking contributions, be it code, documentation, or ideas. Apart from contributing to `SwiftLog` itself, there's another huge gap at the moment: `SwiftLog` is an _API package_ which tries to establish a common API the ecosystem can use. To make logging really work for real-world workloads, we need `SwiftLog`-compatible _logging backends_ which then either persist the log messages in files, render them in nicer colors on the terminal, or send them over to Splunk or ELK.
This repository contains a logging API implementation for Swift.
SwiftLog provides a unified, performant, and ergonomic logging API that can be
adopted by libraries and applications across the Swift ecosystem.
What `SwiftLog` provides today can be found in the [API docs][api-docs].
- 📚 **Documentation** and **tutorials** are available on the [Swift Package Index](https://swiftpackageindex.com/apple/swift-log)
- 🚀 **Contributions** are welcome, please see [CONTRIBUTING.md](CONTRIBUTING.md)
- 🪪 **License** is Apache 2.0, repeated in [LICENSE.txt](LICENSE.txt)
- 🔒 **Security** issues should be reported via the process in [SECURITY.md](SECURITY.md)
- 🔀 **Available Logging Backends**: SwiftLog is an API package - you'll want to
choose from the many
[community-maintained logging backends](#available-log-handler-backends) for production use
## Getting started
## Quick Start
If you have a server-side Swift application, or maybe a cross-platform (for example Linux & macOS) app/library, and you would like to log, we think targeting this logging API package is a great idea. Below you'll find all you need to know to get started.
#### Adding the dependency
`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`:
The following snippet shows how to add SwiftLog to your Swift Package:
```swift
.package(url: "https://github.com/apple/swift-log.git", from: "1.0.0"),
// swift-tools-version: 6.1
import PackageDescription
let package = Package(
name: "YourApp",
dependencies: [
.package(url: "https://github.com/apple/swift-log", from: "1.6.0")
],
targets: [
.target(
name: "YourApp",
dependencies: [
.product(name: "Logging", package: "swift-log")
]
)
]
)
```
and to your application/library target, add `"Logging"` to your `dependencies`, e.g. like this:
Then start logging:
```swift
.target(name: "BestExampleApp", dependencies: [
.product(name: "Logging", package: "swift-log")
],
```
#### Let's log
```swift
// 1) let's import the logging API package
import Logging
// 2) we need to create a logger, the label works similarly to a DispatchQueue label
let logger = Logger(label: "com.example.BestExampleApp.main")
// Create a logger
let logger = Logger(label: "com.example.YourApp")
// 3) we're now ready to use it
logger.info("Hello World!")
// Log at different levels
logger.info("Application started")
logger.warning("This is a warning")
logger.error("Something went wrong", metadata: ["error": "\(error)"])
// Add metadata for context
var requestLogger = logger
requestLogger[metadataKey: "request-id"] = "\(UUID())"
requestLogger.info("Processing request")
```
#### Output
## Available log handler backends
```
2019-03-13T15:46:38+0000 info: Hello World!
```
The community has built numerous specialized logging backends.
#### Default `Logger` behavior
`SwiftLog` provides for very basic console logging out-of-the-box by way of `StreamLogHandler`. It is possible to switch the default output to `stderr` like so:
```swift
LoggingSystem.bootstrap(StreamLogHandler.standardError)
```
`StreamLogHandler` is primarily a convenience only and does not provide any substantial customization. Library maintainers who aim to build their own logging backends for integration and consumption should implement the `LogHandler` protocol directly as laid out in [the "On the implementation of a logging backend" section](#on-the-implementation-of-a-logging-backend-a-loghandler).
For further information, please check the [API documentation][api-docs].
<a name="backends"></a>
## Available Logging Backends For Applications
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|
| ----------- | ----------- |
| [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 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/) | 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). |
| [stevapple/swift-log-telegram](https://github.com/stevapple/swift-log-telegram) | a logging backend that sends log messages to any Telegram chat (Inspired by and forked from [wlisac/swift-log-slack](https://github.com/wlisac/swift-log-slack)) |
| [jagreenwood/swift-log-datadog](https://github.com/jagreenwood/swift-log-datadog) | a logging backend which sends log messages to the [Datadog](https://www.datadoghq.com/log-management/) log management service |
| [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 |
| [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?
Glad you asked. We believe that for the Swift on Server ecosystem, it's crucial to have a logging API that can be adopted by anybody so a multitude of libraries from different parties can all log to a shared destination. More concretely this means that we believe all the log messages from all libraries end up in the same file, database, Elastic Stack/Splunk instance, or whatever you may choose.
In the real-world however, there are so many opinions over how exactly a logging system should behave, what a log message should be formatted like, and where/how it should be persisted. We think it's not feasible to wait for one logging package to support everything that a specific deployment needs whilst still being easy enough to use and remain performant. That's why we decided to cut the problem in half:
1. a logging API
2. a logging backend implementation
This package only provides the logging API itself and therefore `SwiftLog` is a 'logging API package'. `SwiftLog` (using `LoggingSystem.bootstrap`) can be configured to choose any compatible logging backend implementation. This way packages can adopt the API and the _application_ can choose any compatible logging backend implementation without requiring any changes from any of the libraries.
Just for completeness sake: This API package does actually include an overly simplistic and non-configurable logging backend implementation which simply writes all log messages to `stdout`. The reason to include this overly simplistic logging backend implementation is to improve the first-time usage experience. Let's assume you start a project and try out `SwiftLog` for the first time, it's just a whole lot better to see something you logged appear on `stdout` in a simplistic format rather than nothing happening at all. For any real-world application, we advise configuring another logging backend implementation that logs in the style you like.
## The core concepts
### Loggers
`Logger`s are used to emit log messages and therefore the most important type in `SwiftLog`, so their use should be as simple as possible. Most commonly, they are used to emit log messages in a certain log level. For example:
```swift
// logging an informational message
logger.info("Hello World!")
// ouch, something went wrong
logger.error("Houston, we have a problem: \(problem)")
```
### Log levels
The following log levels are supported:
- `trace`
- `debug`
- `info`
- `notice`
- `warning`
- `error`
- `critical`
The log level of a given logger can be changed, but the change will only affect the specific logger you changed it on. You could say the `Logger` is a _value type_ regarding the log level.
### Logging metadata
Logging metadata is metadata that can be attached to loggers to add information that is crucial when debugging a problem. In servers, the usual example is attaching a request UUID to a logger that will then be present on all log messages logged with that logger. Example:
```swift
var logger = logger
logger[metadataKey: "request-uuid"] = "\(UUID())"
logger.info("hello world")
```
will print
```
2019-03-13T18:30:02+0000 info: request-uuid=F8633013-3DD8-481C-9256-B296E43443ED hello world
```
with the default logging backend implementation that ships with `SwiftLog`. Needless to say, the format is fully defined by the logging backend you choose.
## On the implementation of a logging backend (a `LogHandler`)
Note: If you don't want to implement a custom logging backend, everything in this section is probably not very relevant, so please feel free to skip.
To become a compatible logging backend that all `SwiftLog` consumers can use, you need to do two things: 1) Implement a type (usually a `struct`) that implements `LogHandler`, a protocol provided by `SwiftLog` and 2) instruct `SwiftLog` to use your logging backend implementation.
A `LogHandler` or logging backend implementation is anything that conforms to the following protocol
```swift
public protocol LogHandler {
func log(level: Logger.Level, message: Logger.Message, metadata: Logger.Metadata?, source: String, file: String, function: String, line: UInt)
subscript(metadataKey _: String) -> Logger.Metadata.Value? { get set }
var metadata: Logger.Metadata { get set }
var logLevel: Logger.Level { get set }
}
```
Instructing `SwiftLog` to use your logging backend as the one the whole application (including all libraries) should use is very simple:
LoggingSystem.bootstrap(MyLogHandler.init)
### Implementation considerations
`LogHandler`s control most parts of the logging system:
#### Under control of a `LogHandler`
##### Configuration
`LogHandler`s control the two crucial pieces of `Logger` configuration, namely:
- log level (`logger.logLevel` property)
- logging metadata (`logger[metadataKey:]` and `logger.metadata`)
For the system to work, however, it is important that `LogHandler` treat the configuration as _value types_. This means that `LogHandler`s should be `struct`s and a change in log level or logging metadata should only affect the very `LogHandler` it was changed on.
However, in special cases, it is acceptable that a `LogHandler` provides some global log level override that may affect all `LogHandler`s created.
##### Emitting
- emitting the log message itself
### Not under control of `LogHandler`s
`LogHandler`s do not control if a message should be logged or not. `Logger` will only invoke the `log` function of a `LogHandler` if `Logger` determines that a log message should be emitted given the configured log level.
## Source vs Label
A `Logger` carries an (immutable) `label` and each log message carries a `source` parameter (since SwiftLog 1.3.0). The `Logger`'s label
identifies the creator of the `Logger`. If you are using structured logging by preserving metadata across multiple modules, the `Logger`'s
`label` is not a good way to identify where a log message originated from as it identifies the creator of a `Logger` which is often passed
around between libraries to preserve metadata and the like.
If you want to filter all log messages originating from a certain subsystem, filter by `source` which defaults to the module that is emitting the
log message.
## Security
Please see [SECURITY.md](SECURITY.md) for SwiftLog's security process.
## Design
This logging API was designed with the contributors to the Swift on Server community and approved by the [SSWG (Swift Server Work Group)](https://swift.org/server/) to the 'sandbox level' of the SSWG's [incubation process](https://github.com/swift-server/sswg/blob/master/process/incubation.md).
- [pitch](https://forums.swift.org/t/logging/16027), [discussion](https://forums.swift.org/t/discussion-server-logging-api/18834), [feedback](https://forums.swift.org/t/feedback-server-logging-api-with-revisions/19375)
- [log levels](https://forums.swift.org/t/logging-levels-for-swifts-server-side-logging-apis-and-new-os-log-apis/20365)
[api-docs]: https://apple.github.io/swift-log/docs/current/Logging/Structs/Logger.html
A great way to discover available log backend implementations is searching the
[Swift Package Index](https://swiftpackageindex.com/search?query=swift-log)
for the `swift-log` keyword.
+1 -1
View File
@@ -38,6 +38,6 @@ with the all the required detail.
and in the Server → Security Updates category on the [Swift forums][swift-forums-sec].
[sswg]: https://github.com/swift-server/sswg
[sswg-security]: https://github.com/swift-server/sswg/blob/main/security/README.md
[sswg-security]: https://www.swift.org/sswg/security/
[swift-forums-sec]: https://forums.swift.org/c/server/security-updates/
[mitre]: https://cveform.mitre.org/
@@ -0,0 +1,138 @@
# 001: Choosing log levels
Best practice for selecting appropriate log levels in applications and
libraries.
## Overview
SwiftLog defines seven log levels, and choosing the right level is crucial for
creating well-behaved libraries that don't overwhelm logging systems or misuse
severity levels. This practice provides clear guidance on when to use each
level.
### Motivation
Libraries must be well-behaved across various use cases and cannot assume
specific logging backend configurations. Using inappropriate log levels can
flood production logs, trigger false alerts, or make debugging more difficult.
Following consistent log level guidelines ensures your library integrates well
with diverse application environments.
### Log levels
SwiftLog defines seven log levels via ``Logger/Level``, ordered from least to
most severe:
- ``Logger/Level/trace``
- ``Logger/Level/debug``
- ``Logger/Level/info``
- ``Logger/Level/notice``
- ``Logger/Level/warning``
- ``Logger/Level/error``
- ``Logger/Level/critical``
### Level guidelines
How you use log levels depends in large part if you are developing a library, or
an application which bootstraps its logging system and is in full control over
its logging environment.
#### For libraries
Libraries should use **info level or lower** (info, debug, trace). Each level
serves different purposes:
Libraries **should not** log information on **warning or more severe levels**,
unless it is a one-time (for example during startup) warning, that cannot lead
to overwhelming log outputs.
##### Trace Level
- **Usage**: Log everything needed to diagnose hard-to-reproduce bugs
- **Performance**: May impact performance; assume it won't be used in production
- **Content**: Internal state, detailed operation flows, diagnostic information
##### Debug Level
- **Usage**: May be enabled in some production deployments
- **Performance**: Should not significantly undermine production performance
- **Content**: High-level operation overview, connection events, major decisions
##### Info Level
- **Usage**: Reserved for things that went wrong but can't be communicated
through other means like throwing from a method
- **Examples**: Connection retry attempts, fallback mechanisms, recoverable
failures
- **Guideline**: Use sparingly - not for normal successful operations
#### For applications
Applications can use **any level** depending on the context and what they want
to achieve. Applications have full control over their logging strategy.
#### Configuring logger log levels
It depends on the use-case of your application which log level your logger
should use. For **console and other end-user-visible displays**: Consider using
**notice level** as the minimum visible level to avoid overwhelming users with
technical details.
### Example
#### Recommended: Libraries should use info level or lower
```swift
// ✅ Good: Trace level for detailed diagnostics
logger.trace("Connection pool state", metadata: [
"active": "\(activeConnections)",
"idle": "\(idleConnections)",
"pending": "\(pendingRequests)"
])
// ✅ Good: Debug level for high-value operational info
logger.debug("Database connection established", metadata: [
"host": "\(host)",
"database": "\(database)",
"connectionTime": "\(duration)"
])
// ✅ Good: Info level for issues that can't be communicated through other means
logger.info("Connection failed, retrying", metadata: [
"attempt": "\(attemptNumber)",
"maxRetries": "\(maxRetries)",
"host": "\(host)"
])
```
#### Use sparingly: Warning and error levels
```swift
// ✅ Good: One-time startup warning or error
logger.warning("Deprecated TLS version detected. Consider upgrading to TLS 1.3")
```
#### Avoid: Logging potentially intentional failures at info level
Some failures may be completely intentional from the high-level perspective of a
developer or system using your library. For example: failure to resolve a
domain, failure to make a request, or failure to complete some task;
Instead, log at debug or trace levels and offer alternative ways to observe
these behaviors, for example using `swift-metrics` to emit counts.
```swift
// ❌ Bad: Normal operations at info level flood production logs
logger.info("Request failed")
```
#### Avoid: Normal operations at info level
```swift
// ❌ Bad: Normal operations at info level flood production logs
logger.info("HTTP request received")
logger.info("Database query executed")
logger.info("Response sent")
// ✅ Good: Use appropriate levels instead
logger.debug("Processing request", metadata: ["path": "\(path)"])
logger.trace("Query", , metadata: ["path": "\(query)"])
logger.debug("Request completed", metadata: ["status": "\(status)"])
```
@@ -0,0 +1,213 @@
# Implementing a log handler
Create a custom logging backend that provides logging services for your apps
and libraries.
## Overview
To become a compatible logging backend that any `SwiftLog` consumer can use,
you need to fulfill a few requirements, primarily conforming to the
``LogHandler`` protocol.
### Implement with value type semantics
Your log handler **must be a `struct`** and exhibit value semantics. This
ensures that changes to one logger don't affect others.
To verify that your handler reflects value semantics ensure that it passes this
test:
```swift
@Test
func logHandlerValueSemantics() {
LoggingSystem.bootstrap(MyLogHandler.init)
var logger1 = Logger(label: "first logger")
logger1.logLevel = .debug
logger1[metadataKey: "only-on"] = "first"
var logger2 = logger1
logger2.logLevel = .error // Must not affect logger1
logger2[metadataKey: "only-on"] = "second" // Must not affect logger1
// These expectations must pass
#expect(logger1.logLevel == .debug)
#expect(logger2.logLevel == .error)
#expect(logger1[metadataKey: "only-on"] == "first")
#expect(logger2[metadataKey: "only-on"] == "second")
}
```
> Note: In special cases, it is acceptable for a log handler to provide
> global log level overrides that may affect all log handlers created.
### Example implementation
Here's a complete example of a simple print-based log handler:
```swift
import Foundation
import Logging
public struct PrintLogHandler: LogHandler {
private let label: String
public var logLevel: Logger.Level = .info
public var metadata: Logger.Metadata = [:]
public init(label: String) {
self.label = label
}
public func log(
level: Logger.Level,
message: Logger.Message,
metadata: Logger.Metadata?,
source: String,
file: String,
function: String,
line: UInt
) {
let timestamp = ISO8601DateFormatter().string(from: Date())
let levelString = level.rawValue.uppercased()
// Merge handler metadata with message metadata
let combinedMetadata = Self.prepareMetadata(
base: self.metadata
explicit: metadata
)
// Format metadata
let metadataString = combinedMetadata.map { "\($0.key)=\($0.value)" }.joined(separator: ",")
// Create log line and print to console
let logLine = "\(label) \(timestamp) \(levelString) [\(metadataString)]: \(message)"
print(logLine)
}
public subscript(metadataKey key: String) -> Logger.Metadata.Value? {
get {
return self.metadata[key]
}
set {
self.metadata[key] = newValue
}
}
static func prepareMetadata(
base: Logger.Metadata,
explicit: Logger.Metadata?
) -> Logger.Metadata? {
var metadata = base
guard let explicit else {
// all per-log-statement values are empty
return metadata
}
metadata.merge(explicit, uniquingKeysWith: { _, explicit in explicit })
return metadata
}
}
```
### Advanced features
#### Metadata providers
Metadata providers allow you to dynamically add contextual information to all
log messages without explicitly passing it each time. Common use cases include
request IDs, user sessions, or trace contexts that should be included in logs
throughout a request's lifecycle.
```swift
import Foundation
import Logging
public struct PrintLogHandler: LogHandler {
private let label: String
public var logLevel: Logger.Level = .info
public var metadata: Logger.Metadata = [:]
public var metadataProvider: Logger.MetadataProvider?
public init(label: String) {
self.label = label
}
public func log(
level: Logger.Level,
message: Logger.Message,
metadata: Logger.Metadata?,
source: String,
file: String,
function: String,
line: UInt
) {
let timestamp = ISO8601DateFormatter().string(from: Date())
let levelString = level.rawValue.uppercased()
// Get provider metadata
let providerMetadata = metadataProvider?.get() ?? [:]
// Merge handler metadata with message metadata
let combinedMetadata = Self.prepareMetadata(
base: self.metadata,
provider: self.metadataProvider,
explicit: metadata
)
// Format metadata
let metadataString = combinedMetadata.map { "\($0.key)=\($0.value)" }.joined(separator: ",")
// Create log line and print to console
let logLine = "\(label) \(timestamp) \(levelString) [\(metadataString)]: \(message)"
print(logLine)
}
public subscript(metadataKey key: String) -> Logger.Metadata.Value? {
get {
return self.metadata[key]
}
set {
self.metadata[key] = newValue
}
}
static func prepareMetadata(
base: Logger.Metadata,
provider: Logger.MetadataProvider?,
explicit: Logger.Metadata?
) -> Logger.Metadata? {
var metadata = base
let provided = provider?.get() ?? [:]
guard !provided.isEmpty || !((explicit ?? [:]).isEmpty) else {
// all per-log-statement values are empty
return metadata
}
if !provided.isEmpty {
metadata.merge(provided, uniquingKeysWith: { _, provided in provided })
}
if let explicit = explicit, !explicit.isEmpty {
metadata.merge(explicit, uniquingKeysWith: { _, explicit in explicit })
}
return metadata
}
}
```
### Performance considerations
1. **Avoid blocking**: Don't block the calling thread for I/O operations.
2. **Lazy evaluation**: Remember that messages and metadata are autoclosures.
3. **Memory efficiency**: Don't hold onto large amounts of messages.
## See Also
- ``LogHandler``
- ``StreamLogHandler``
- ``MultiplexLogHandler``
-13
View File
@@ -1,13 +0,0 @@
# ``Logging/Logger/Level``
## Topics
### Log levels
- ``trace``
- ``debug``
- ``info``
- ``notice``
- ``warning``
- ``error``
- ``critical``
@@ -0,0 +1,41 @@
# Logging best practices
Best practices for effective logging with SwiftLog.
## Overview
This collection of best practices helps library authors and application
developers create effective, maintainable logging that works well across diverse
environments. Each practice is designed to ensure your logs are useful for
debugging while being respectful of system resources and operational
requirements.
### Who Should Use These Practices
- **Library Authors**: Creating reusable components that log appropriately.
- **Application Developers**: Implementing logging strategies in applications.
### Philosophy
Good logging strikes a balance between providing useful information and avoiding
system overhead. These practices are based on real-world experience with
production systems and emphasize:
- **Predictable behavior** across different environments.
- **Performance consciousness** to avoid impacting application speed.
- **Operational awareness** to support production debugging and monitoring.
- **Developer experience** to make debugging efficient and pleasant.
### Contributing to these practices
These best practices evolve based on community experience and are maintained by
the Swift Server Working Group ([SSWG](https://www.swift.org/sswg/)). Each
practice includes:
- **Clear motivation** explaining why the practice matters
- **Concrete examples** showing good and bad patterns
- **Alternatives considered** documenting trade-offs and rejected approaches
## Topics
- <doc:001-ChoosingLogLevels>
+142 -6
View File
@@ -1,18 +1,149 @@
# ``Logging``
A Logging API for Swift.
A unified, performant, and ergonomic logging API for Swift.
## Overview
SwiftLog provides a logging API package designed to establish a common API the
ecosystem can use. It allows packages to emit log messages without tying them to
any specific logging implementation, while applications can choose any
compatible logging backend.
SwiftLog is an _API package_ which cuts the logging problem in half:
1. A logging API (this package)
2. Logging backend implementations (community-provided)
This separation allows libraries to adopt the API while applications choose any
compatible logging backend implementation without requiring changes from
libraries.
## Getting Started
If you have a server-side Swift application, or maybe a cross-platform (for example Linux & macOS) app/library, and you would like to log, we think targeting this logging API package is a great idea. Below you'll find all you need to know to get started.
Use this If you are writing a cross-platform application (for example, Linux and
macOS) or library, target this logging API.
### Log handler implementations
### Adding the Dependency
This package offers the common Logging API as well as a very simple stdout log handler.
Add the dependency to your `Package.swift`:
In a real system or application, you will want to use one of the many community maintained log handler implementations.
```swift
.package(url: "https://github.com/apple/swift-log", from: "1.6.0")
```
And to your target:
```swift
.target(
name: "YourTarget",
dependencies: [
.product(name: "Logging", package: "swift-log")
]
)
```
### Basic Usage
```swift
// Import the logging API
import Logging
// Create a logger with a label
let logger = Logger(label: "MyLogger")
// Use it to log messages
logger.info("Hello World!")
```
This outputs:
```
2019-03-13T15:46:38+0000 info: Hello World!
```
### Default Behavior
SwiftLog provides basic console logging via ``StreamLogHandler``. By default it
uses `stdout`, however, you can configure it to use `stderr` instead:
```swift
LoggingSystem.bootstrap(StreamLogHandler.standardError)
```
``StreamLogHandler`` is primarily for convenience. For production applications,
implement the ``LogHandler`` protocol directly or use a community-maintained
backend.
## Core Concepts
### Loggers
Loggers are used to emit log messages at different severity levels:
```swift
// Informational message
logger.info("Processing request")
// Something went wrong
logger.error("Houston, we have a problem")
```
``Logger`` is a value type with value semantics, meaning that when you modify a
logger's configuration (like its log level or metadata), it only affects that
specific logger instance:
```swift
let baseLogger = Logger(label: "MyApp")
// Create a new logger with different configuration.
var requestLogger = baseLogger
requestLogger.logLevel = .debug
requestLogger[metadataKey: "request-id"] = "\(UUID())"
// baseLogger is unchanged. It still has default log level and no metadata
// requestLogger has debug level and request-id metadata.
```
This value type behavior makes loggers safe to pass between functions and modify
without unexpected side effects.
### Log Levels
SwiftLog supports seven log levels (from least to most severe):
- ``Logger/Level/trace``
- ``Logger/Level/debug``
- ``Logger/Level/info``
- ``Logger/Level/notice``
- ``Logger/Level/warning``
- ``Logger/Level/error``
- ``Logger/Level/critical``
Log levels can be changed per logger without affecting others:
```swift
var logger = Logger(label: "MyLogger")
logger.logLevel = .debug
```
### Logging Metadata
Metadata provides contextual information crucial for debugging:
```swift
var logger = Logger(label: "com.example.server")
logger[metadataKey: "request-uuid"] = "\(UUID())"
logger.info("Processing request")
```
Output:
```
2019-03-13T18:30:02+0000 info: request-uuid=F8633013-3DD8-481C-9256-B296E43443ED Processing request
```
### Source vs Label
A ``Logger`` has an immutable `label` identifying its creator, while each log
message carries a `source` parameter identifying where the message originated.
Use `source` for filtering messages from specific subsystems.
Please refer to the [complete list of community maintained logging backend implementations](https://github.com/apple/swift-log#selecting-a-logging-backend-implementation-applications-only).
## Topics
@@ -28,3 +159,8 @@ Please refer to the [complete list of community maintained logging backend imple
- ``StreamLogHandler``
- ``SwiftLogNoOpLogHandler``
### Best Practices
- <doc:LoggingBestPractices>
- <doc:001-ChoosingLogLevels>
+2
View File
@@ -34,6 +34,8 @@ import Darwin
import WinSDK
#elseif canImport(Glibc)
import Glibc
#elseif canImport(Android)
import Android
#elseif canImport(Musl)
import Musl
#else
+68 -35
View File
@@ -31,19 +31,23 @@
/// When developing your `LogHandler`, please make sure the following test works.
///
/// ```swift
/// LoggingSystem.bootstrap(MyLogHandler.init) // your LogHandler might have a different bootstrapping step
/// var logger1 = Logger(label: "first logger")
/// logger1.logLevel = .debug
/// logger1[metadataKey: "only-on"] = "first"
/// @Test
/// func logHandlerValueSemantics() {
/// LoggingSystem.bootstrap(MyLogHandler.init)
/// var logger1 = Logger(label: "first logger")
/// logger1.logLevel = .debug
/// logger1[metadataKey: "only-on"] = "first"
///
/// var logger2 = logger1
/// logger2.logLevel = .error // this must not override `logger1`'s log level
/// logger2[metadataKey: "only-on"] = "second" // this must not override `logger1`'s metadata
/// var logger2 = logger1
/// logger2.logLevel = .error // Must not affect logger1
/// logger2[metadataKey: "only-on"] = "second" // Must not affect logger1
///
/// XCTAssertEqual(.debug, logger1.logLevel)
/// XCTAssertEqual(.error, logger2.logLevel)
/// XCTAssertEqual("first", logger1[metadataKey: "only-on"])
/// XCTAssertEqual("second", logger2[metadataKey: "only-on"])
/// // These expectations must pass
/// #expect(logger1.logLevel == .debug)
/// #expect(logger2.logLevel == .error)
/// #expect(logger1[metadataKey: "only-on"] == "first")
/// #expect(logger2[metadataKey: "only-on"] == "second")
/// }
/// ```
///
/// ### Special cases
@@ -132,18 +136,27 @@ public protocol LogHandler: _SwiftLogSendableLogHandler {
/// - file: The file the log message was emitted from.
/// - function: The function the log line was emitted from.
/// - line: The line the log message was emitted from.
func log(level: Logger.Level,
message: Logger.Message,
metadata: Logger.Metadata?,
source: String,
file: String,
function: String,
line: UInt)
func log(
level: Logger.Level,
message: Logger.Message,
metadata: Logger.Metadata?,
source: String,
file: String,
function: String,
line: UInt
)
/// SwiftLog 1.0 compatibility method. Please do _not_ implement, implement
/// `log(level:message:metadata:source:file:function:line:)` instead.
@available(*, deprecated, renamed: "log(level:message:metadata:source:file:function:line:)")
func log(level: Logging.Logger.Level, message: Logging.Logger.Message, metadata: Logging.Logger.Metadata?, file: String, function: String, line: UInt)
func log(
level: Logging.Logger.Level,
message: Logging.Logger.Message,
metadata: Logging.Logger.Metadata?,
file: String,
function: String,
line: UInt
)
/// Add, remove, or change the logging metadata.
///
@@ -179,7 +192,16 @@ extension LogHandler {
set {
#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)
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
}
@@ -188,25 +210,36 @@ extension LogHandler {
extension LogHandler {
@available(*, deprecated, message: "You should implement this method instead of using the default implementation")
public func log(level: Logger.Level,
message: Logger.Message,
metadata: Logger.Metadata?,
source: String,
file: String,
function: String,
line: UInt) {
public func log(
level: Logger.Level,
message: Logger.Message,
metadata: Logger.Metadata?,
source: String,
file: String,
function: String,
line: UInt
) {
self.log(level: level, message: message, metadata: metadata, file: file, function: function, line: line)
}
@available(*, deprecated, renamed: "log(level:message:metadata:source:file:function:line:)")
public func log(level: Logging.Logger.Level, message: Logging.Logger.Message, metadata: Logging.Logger.Metadata?, file: String, function: String, line: UInt) {
self.log(level: level,
message: message,
metadata: metadata,
source: Logger.currentModule(filePath: file),
file: file,
function: function,
line: line)
public func log(
level: Logging.Logger.Level,
message: Logging.Logger.Message,
metadata: Logging.Logger.Metadata?,
file: String,
function: String,
line: UInt
) {
self.log(
level: level,
message: message,
metadata: metadata,
source: Logger.currentModule(filePath: file),
file: file,
function: function,
line: line
)
}
}
+347 -148
View File
@@ -22,6 +22,8 @@ import CRT
#else
import Glibc
#endif
#elseif canImport(Android)
import Android
#elseif canImport(Musl)
import Musl
#elseif canImport(WASILibc)
@@ -33,7 +35,7 @@ import WASILibc
/// A `Logger` is the central type in `SwiftLog`. Its central function is to emit log messages using one of the methods
/// corresponding to a log level.
///
/// `Logger`s are value types with respect to the ``logLevel`` and the ``metadata`` (as well as the immutable `label`
/// `Logger`s are value types with respect to the ``Logger/Level`` and the ``Metadata`` (as well as the immutable `label`
/// and the selected ``LogHandler``). Therefore, `Logger`s are suitable to be passed around between libraries if you want
/// to preserve metadata across libraries.
///
@@ -44,8 +46,9 @@ import WASILibc
/// ```
public struct Logger {
/// Storage class to hold the label and log handler
// The storage implements CoW to become Sendable
@usableFromInline
internal final class Storage: @unchecked /* and not actually */ Sendable /* but safe if only used with CoW */ {
internal final class Storage: @unchecked Sendable {
@usableFromInline
var label: String
@@ -60,21 +63,21 @@ public struct Logger {
@inlinable
func copy() -> Storage {
return Storage(label: self.label, handler: self.handler)
Storage(label: self.label, handler: self.handler)
}
}
@usableFromInline
internal var _storage: Storage
public var label: String {
return self._storage.label
self._storage.label
}
/// A computed property to access the `LogHandler`.
@inlinable
public var handler: any LogHandler {
get {
return self._storage.handler
self._storage.handler
}
set {
if !isKnownUniquelyReferenced(&self._storage) {
@@ -87,7 +90,7 @@ public struct Logger {
/// The metadata provider this logger was created with.
@inlinable
public var metadataProvider: Logger.MetadataProvider? {
return self.handler.metadataProvider
self.handler.metadataProvider
}
@usableFromInline
@@ -115,17 +118,25 @@ extension Logger {
/// - line: The line this log message originates from (there's usually no need to pass it explicitly as it
/// defaults to `#line`).
@inlinable
public func log(level: Logger.Level,
_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
source: @autoclosure () -> String? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line) {
public func log(
level: Logger.Level,
_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
source: @autoclosure () -> String? = nil,
file: String = #fileID,
function: String = #function,
line: UInt = #line
) {
if self.logLevel <= level {
self.handler.log(level: level,
message: message(),
metadata: metadata(),
source: source() ?? Logger.currentModule(fileID: (file)),
file: file, function: function, line: line)
self.handler.log(
level: level,
message: message(),
metadata: metadata(),
source: source() ?? Logger.currentModule(fileID: (file)),
file: file,
function: function,
line: line
)
}
}
@@ -145,10 +156,14 @@ extension Logger {
/// - line: The line this log message originates from (there's usually no need to pass it explicitly as it
/// defaults to `#line`).
@inlinable
public func log(level: Logger.Level,
_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line) {
public func log(
level: Logger.Level,
_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
file: String = #fileID,
function: String = #function,
line: UInt = #line
) {
self.log(level: level, message(), metadata: metadata(), source: nil, file: file, function: function, line: line)
}
@@ -159,7 +174,7 @@ extension Logger {
@inlinable
public subscript(metadataKey metadataKey: String) -> Logger.Metadata.Value? {
get {
return self.handler[metadataKey: metadataKey]
self.handler[metadataKey: metadataKey]
}
set {
self.handler[metadataKey: metadataKey] = newValue
@@ -175,7 +190,7 @@ extension Logger {
@inlinable
public var logLevel: Logger.Level {
get {
return self.handler.logLevel
self.handler.logLevel
}
set {
self.handler.logLevel = newValue
@@ -201,11 +216,23 @@ extension Logger {
/// - line: The line this log message originates from (there's usually no need to pass it explicitly as it
/// defaults to `#line`).
@inlinable
public func trace(_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
source: @autoclosure () -> String? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line) {
self.log(level: .trace, message(), metadata: metadata(), source: source(), file: file, function: function, line: line)
public func trace(
_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
source: @autoclosure () -> String? = nil,
file: String = #fileID,
function: String = #function,
line: UInt = #line
) {
self.log(
level: .trace,
message(),
metadata: metadata(),
source: source(),
file: file,
function: function,
line: line
)
}
/// Log a message passing with the ``Logger/Level/trace`` log level.
@@ -223,9 +250,13 @@ extension Logger {
/// - line: The line this log message originates from (there's usually no need to pass it explicitly as it
/// defaults to `#line`).
@inlinable
public func trace(_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line) {
public func trace(
_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
file: String = #fileID,
function: String = #function,
line: UInt = #line
) {
self.trace(message(), metadata: metadata(), source: nil, file: file, function: function, line: line)
}
@@ -246,11 +277,23 @@ extension Logger {
/// - line: The line this log message originates from (there's usually no need to pass it explicitly as it
/// defaults to `#line`).
@inlinable
public func debug(_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
source: @autoclosure () -> String? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line) {
self.log(level: .debug, message(), metadata: metadata(), source: source(), file: file, function: function, line: line)
public func debug(
_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
source: @autoclosure () -> String? = nil,
file: String = #fileID,
function: String = #function,
line: UInt = #line
) {
self.log(
level: .debug,
message(),
metadata: metadata(),
source: source(),
file: file,
function: function,
line: line
)
}
/// Log a message passing with the ``Logger/Level/debug`` log level.
@@ -268,9 +311,13 @@ extension Logger {
/// - line: The line this log message originates from (there's usually no need to pass it explicitly as it
/// defaults to `#line`).
@inlinable
public func debug(_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line) {
public func debug(
_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
file: String = #fileID,
function: String = #function,
line: UInt = #line
) {
self.debug(message(), metadata: metadata(), source: nil, file: file, function: function, line: line)
}
@@ -291,11 +338,23 @@ extension Logger {
/// - line: The line this log message originates from (there's usually no need to pass it explicitly as it
/// defaults to `#line`).
@inlinable
public func info(_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
source: @autoclosure () -> String? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line) {
self.log(level: .info, message(), metadata: metadata(), source: source(), file: file, function: function, line: line)
public func info(
_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
source: @autoclosure () -> String? = nil,
file: String = #fileID,
function: String = #function,
line: UInt = #line
) {
self.log(
level: .info,
message(),
metadata: metadata(),
source: source(),
file: file,
function: function,
line: line
)
}
/// Log a message passing with the ``Logger/Level/info`` log level.
@@ -313,9 +372,13 @@ extension Logger {
/// - line: The line this log message originates from (there's usually no need to pass it explicitly as it
/// defaults to `#line`).
@inlinable
public func info(_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line) {
public func info(
_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
file: String = #fileID,
function: String = #function,
line: UInt = #line
) {
self.info(message(), metadata: metadata(), source: nil, file: file, function: function, line: line)
}
@@ -336,11 +399,23 @@ extension Logger {
/// - line: The line this log message originates from (there's usually no need to pass it explicitly as it
/// defaults to `#line`).
@inlinable
public func notice(_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
source: @autoclosure () -> String? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line) {
self.log(level: .notice, message(), metadata: metadata(), source: source(), file: file, function: function, line: line)
public func notice(
_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
source: @autoclosure () -> String? = nil,
file: String = #fileID,
function: String = #function,
line: UInt = #line
) {
self.log(
level: .notice,
message(),
metadata: metadata(),
source: source(),
file: file,
function: function,
line: line
)
}
/// Log a message passing with the ``Logger/Level/notice`` log level.
@@ -358,9 +433,13 @@ extension Logger {
/// - line: The line this log message originates from (there's usually no need to pass it explicitly as it
/// defaults to `#line`).
@inlinable
public func notice(_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line) {
public func notice(
_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
file: String = #fileID,
function: String = #function,
line: UInt = #line
) {
self.notice(message(), metadata: metadata(), source: nil, file: file, function: function, line: line)
}
@@ -381,11 +460,23 @@ extension Logger {
/// - line: The line this log message originates from (there's usually no need to pass it explicitly as it
/// defaults to `#line`).
@inlinable
public func warning(_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
source: @autoclosure () -> String? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line) {
self.log(level: .warning, message(), metadata: metadata(), source: source(), file: file, function: function, line: line)
public func warning(
_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
source: @autoclosure () -> String? = nil,
file: String = #fileID,
function: String = #function,
line: UInt = #line
) {
self.log(
level: .warning,
message(),
metadata: metadata(),
source: source(),
file: file,
function: function,
line: line
)
}
/// Log a message passing with the ``Logger/Level/warning`` log level.
@@ -403,9 +494,13 @@ extension Logger {
/// - line: The line this log message originates from (there's usually no need to pass it explicitly as it
/// defaults to `#line`).
@inlinable
public func warning(_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line) {
public func warning(
_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
file: String = #fileID,
function: String = #function,
line: UInt = #line
) {
self.warning(message(), metadata: metadata(), source: nil, file: file, function: function, line: line)
}
@@ -426,11 +521,23 @@ extension Logger {
/// - line: The line this log message originates from (there's usually no need to pass it explicitly as it
/// defaults to `#line`).
@inlinable
public func error(_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
source: @autoclosure () -> String? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line) {
self.log(level: .error, message(), metadata: metadata(), source: source(), file: file, function: function, line: line)
public func error(
_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
source: @autoclosure () -> String? = nil,
file: String = #fileID,
function: String = #function,
line: UInt = #line
) {
self.log(
level: .error,
message(),
metadata: metadata(),
source: source(),
file: file,
function: function,
line: line
)
}
/// Log a message passing with the ``Logger/Level/error`` log level.
@@ -448,9 +555,13 @@ extension Logger {
/// - line: The line this log message originates from (there's usually no need to pass it explicitly as it
/// defaults to `#line`).
@inlinable
public func error(_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line) {
public func error(
_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
file: String = #fileID,
function: String = #function,
line: UInt = #line
) {
self.error(message(), metadata: metadata(), source: nil, file: file, function: function, line: line)
}
@@ -470,11 +581,23 @@ extension Logger {
/// - line: The line this log message originates from (there's usually no need to pass it explicitly as it
/// defaults to `#line`).
@inlinable
public func critical(_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
source: @autoclosure () -> String? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line) {
self.log(level: .critical, message(), metadata: metadata(), source: source(), file: file, function: function, line: line)
public func critical(
_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
source: @autoclosure () -> String? = nil,
file: String = #fileID,
function: String = #function,
line: UInt = #line
) {
self.log(
level: .critical,
message(),
metadata: metadata(),
source: source(),
file: file,
function: function,
line: line
)
}
/// Log a message passing with the ``Logger/Level/critical`` log level.
@@ -491,9 +614,13 @@ extension Logger {
/// - line: The line this log message originates from (there's usually no need to pass it explicitly as it
/// defaults to `#line`).
@inlinable
public func critical(_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line) {
public func critical(
_ message: @autoclosure () -> Logger.Message,
metadata: @autoclosure () -> Logger.Metadata? = nil,
file: String = #fileID,
function: String = #function,
line: UInt = #line
) {
self.critical(message(), metadata: metadata(), source: nil, file: file, function: function, line: line)
}
}
@@ -502,9 +629,14 @@ extension Logger {
/// configured. `LoggingSystem` is set up just once in a given program to set up the desired logging backend
/// implementation.
public enum LoggingSystem {
private static let _factory = FactoryBox({ label, _ in StreamLogHandler.standardError(label: label) },
violationErrorMesage: "logging system can only be initialized once per process.")
private static let _metadataProviderFactory = MetadataProviderBox(nil, violationErrorMesage: "logging system can only be initialized once per process.")
private static let _factory = FactoryBox(
{ label, _ in StreamLogHandler.standardError(label: label) },
violationErrorMesage: "logging system can only be initialized once per process."
)
private static let _metadataProviderFactory = MetadataProviderBox(
nil,
violationErrorMesage: "logging system can only be initialized once per process."
)
#if DEBUG
private static let _warnOnceBox: WarnOnceBox = WarnOnceBox()
@@ -517,10 +649,13 @@ public enum LoggingSystem {
/// - parameters:
/// - factory: A closure that given a `Logger` identifier, produces an instance of the `LogHandler`.
@preconcurrency
public static func bootstrap(_ factory: @escaping @Sendable(String) -> any LogHandler) {
self._factory.replace({ label, _ in
factory(label)
}, validate: true)
public static func bootstrap(_ factory: @escaping @Sendable (String) -> any LogHandler) {
self._factory.replace(
{ label, _ in
factory(label)
},
validate: true
)
}
/// `bootstrap` is a one-time configuration function which globally selects the desired logging backend
@@ -534,29 +669,36 @@ public enum LoggingSystem {
/// - metadataProvider: The `MetadataProvider` used to inject runtime-generated metadata from the execution context.
/// - factory: A closure that given a `Logger` identifier, produces an instance of the `LogHandler`.
@preconcurrency
public static func bootstrap(_ factory: @escaping @Sendable(String, Logger.MetadataProvider?) -> any LogHandler,
metadataProvider: Logger.MetadataProvider?) {
public static func bootstrap(
_ factory: @escaping @Sendable (String, Logger.MetadataProvider?) -> any LogHandler,
metadataProvider: Logger.MetadataProvider?
) {
self._metadataProviderFactory.replace(metadataProvider, validate: true)
self._factory.replace(factory, validate: true)
}
// for our testing we want to allow multiple bootstrapping
internal static func bootstrapInternal(_ factory: @escaping @Sendable(String) -> any LogHandler) {
internal static func bootstrapInternal(_ factory: @escaping @Sendable (String) -> any LogHandler) {
self._metadataProviderFactory.replace(nil, validate: false)
self._factory.replace({ label, _ in
factory(label)
}, validate: false)
self._factory.replace(
{ label, _ in
factory(label)
},
validate: false
)
}
// for our testing we want to allow multiple bootstrapping
internal static func bootstrapInternal(_ factory: @escaping @Sendable(String, Logger.MetadataProvider?) -> any LogHandler,
metadataProvider: Logger.MetadataProvider?) {
internal static func bootstrapInternal(
_ factory: @escaping @Sendable (String, Logger.MetadataProvider?) -> any LogHandler,
metadataProvider: Logger.MetadataProvider?
) {
self._metadataProviderFactory.replace(metadataProvider, validate: false)
self._factory.replace(factory, validate: false)
}
fileprivate static var factory: (String, Logger.MetadataProvider?) -> any LogHandler {
return { label, metadataProvider in
{ label, metadataProvider in
self._factory.underlying(label, metadataProvider)
}
}
@@ -571,14 +713,16 @@ public enum LoggingSystem {
/// factory to avoid using the bootstrapped metadata provider may sometimes be useful, usually it will lead to
/// un-expected behavior, so make sure to always propagate it to your handlers.
public static var metadataProvider: Logger.MetadataProvider? {
return self._metadataProviderFactory.underlying
self._metadataProviderFactory.underlying
}
#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 {
internal static func warnOnceLogHandlerNotSupportedMetadataProvider<Handler: LogHandler>(
_ type: Handler.Type
) -> Bool {
self._warnOnceBox.warnOnceLogHandlerNotSupportedMetadataProvider(type: type)
}
#endif
@@ -606,7 +750,7 @@ public enum LoggingSystem {
}
/// Protects an object applying the constraints that it can only be accessed through a Reader-Writer lock
/// and can ony bre updated once from the initial value given.
/// and can only be updated once from the initial value given.
private struct ReplaceOnceBox<BoxedType: Sendable> {
private struct ReplaceOnce: Sendable {
private var initialized = false
@@ -620,7 +764,7 @@ public enum LoggingSystem {
}
var underlying: BoxedType {
return self._underlying
self._underlying
}
init(underlying: BoxedType, violationErrorMessage: String) {
@@ -632,8 +776,12 @@ public enum LoggingSystem {
private let storage: RWLockedValueBox<ReplaceOnce>
init(_ underlying: BoxedType, violationErrorMesage: String) {
self.storage = .init(initialValue: ReplaceOnce(underlying: underlying,
violationErrorMessage: violationErrorMesage))
self.storage = .init(
initialValue: ReplaceOnce(
underlying: underlying,
violationErrorMessage: violationErrorMesage
)
)
}
func replace(_ newUnderlying: BoxedType, validate: Bool) {
@@ -645,7 +793,9 @@ public enum LoggingSystem {
}
}
private typealias FactoryBox = ReplaceOnceBox< @Sendable(_ label: String, _ provider: Logger.MetadataProvider?) -> any LogHandler>
private typealias FactoryBox = ReplaceOnceBox<
@Sendable (_ label: String, _ provider: Logger.MetadataProvider?) -> any LogHandler
>
private typealias MetadataProviderBox = ReplaceOnceBox<Logger.MetadataProvider?>
}
@@ -780,11 +930,14 @@ extension Logger {
/// - metadataProvider: The custom metadata provider this logger should invoke,
/// 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
var handler = LoggingSystem.factory(label, metadataProvider)
handler.metadataProvider = metadataProvider
return handler
})
self = Logger(
label: label,
factory: { label in
var handler = LoggingSystem.factory(label, metadataProvider)
handler.metadataProvider = metadataProvider
return handler
}
)
}
}
@@ -811,7 +964,7 @@ extension Logger.Level {
extension Logger.Level: Comparable {
public static func < (lhs: Logger.Level, rhs: Logger.Level) -> Bool {
return lhs.naturalIntegralValue < rhs.naturalIntegralValue
lhs.naturalIntegralValue < rhs.naturalIntegralValue
}
}
@@ -848,7 +1001,9 @@ extension Logger {
///
/// logger.info("Hello \(world)")
///
public struct Message: ExpressibleByStringLiteral, Equatable, CustomStringConvertible, ExpressibleByStringInterpolation {
public struct Message: ExpressibleByStringLiteral, Equatable, CustomStringConvertible,
ExpressibleByStringInterpolation
{
public typealias StringLiteralType = String
private var value: String
@@ -858,7 +1013,7 @@ extension Logger {
}
public var description: String {
return self.value
self.value
}
}
}
@@ -934,7 +1089,7 @@ public struct MultiplexLogHandler: LogHandler {
public var logLevel: Logger.Level {
get {
return self.effectiveLogLevel
self.effectiveLogLevel
}
set {
self.mutatingForEachHandler { $0.logLevel = newValue }
@@ -979,15 +1134,25 @@ public struct MultiplexLogHandler: LogHandler {
}
}
public func log(level: Logger.Level,
message: Logger.Message,
metadata: Logger.Metadata?,
source: String,
file: String,
function: String,
line: UInt) {
public func log(
level: Logger.Level,
message: Logger.Message,
metadata: Logger.Metadata?,
source: String,
file: String,
function: String,
line: UInt
) {
for handler in self.handlers where handler.logLevel <= level {
handler.log(level: level, message: message, metadata: metadata, source: source, file: file, function: function, line: line)
handler.log(
level: level,
message: message,
metadata: metadata,
source: source,
file: file,
function: function,
line: line
)
}
}
@@ -996,7 +1161,9 @@ public struct MultiplexLogHandler: LogHandler {
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:
effective.reserveCapacity(self.handlers.first!.metadata.count) // !-safe, we always have at least one handler
// !-safe, we always have at least one handler
effective.reserveCapacity(self.handlers.first!.metadata.count)
for handler in self.handlers {
effective.merge(handler.metadata, uniquingKeysWith: { _, handlerMetadata in handlerMetadata })
@@ -1075,7 +1242,6 @@ internal struct StdioOutputStream: TextOutputStream, @unchecked Sendable {
}
/// Flush the underlying stream.
/// This has no effect when using the `.always` flush mode, which is the default
internal func flush() {
_ = fflush(self.file)
}
@@ -1094,6 +1260,8 @@ internal struct StdioOutputStream: TextOutputStream, @unchecked Sendable {
let systemStderr = CRT.stderr
#elseif canImport(Glibc)
let systemStderr = Glibc.stderr!
#elseif canImport(Android)
let systemStderr = Android.stderr
#elseif canImport(Musl)
let systemStderr = Musl.stderr!
#elseif canImport(WASILibc)
@@ -1112,6 +1280,8 @@ internal struct StdioOutputStream: TextOutputStream, @unchecked Sendable {
let systemStdout = CRT.stdout
#elseif canImport(Glibc)
let systemStdout = Glibc.stdout!
#elseif canImport(Android)
let systemStdout = Android.stdout
#elseif canImport(Musl)
let systemStdout = Musl.stdout!
#elseif canImport(WASILibc)
@@ -1141,22 +1311,30 @@ public struct StreamLogHandler: LogHandler {
/// Factory that makes a `StreamLogHandler` to directs its output to `stdout`
public static func standardOutput(label: String) -> StreamLogHandler {
return StreamLogHandler(label: label, stream: StdioOutputStream.stdout, metadataProvider: LoggingSystem.metadataProvider)
StreamLogHandler(
label: label,
stream: StdioOutputStream.stdout,
metadataProvider: LoggingSystem.metadataProvider
)
}
/// 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)
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)
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)
StreamLogHandler(label: label, stream: StdioOutputStream.stderr, metadataProvider: metadataProvider)
}
private let stream: any _SendableTextOutputStream
@@ -1175,7 +1353,7 @@ public struct StreamLogHandler: LogHandler {
public subscript(metadataKey metadataKey: String) -> Logger.Metadata.Value? {
get {
return self.metadata[metadataKey]
self.metadata[metadataKey]
}
set {
self.metadata[metadataKey] = newValue
@@ -1194,14 +1372,20 @@ public struct StreamLogHandler: LogHandler {
self.metadataProvider = metadataProvider
}
public func log(level: Logger.Level,
message: Logger.Message,
metadata explicitMetadata: Logger.Metadata?,
source: String,
file: String,
function: String,
line: UInt) {
let effectiveMetadata = StreamLogHandler.prepareMetadata(base: self.metadata, provider: self.metadataProvider, explicit: explicitMetadata)
public func log(
level: Logger.Level,
message: Logger.Message,
metadata explicitMetadata: Logger.Metadata?,
source: String,
file: String,
function: String,
line: UInt
) {
let effectiveMetadata = StreamLogHandler.prepareMetadata(
base: self.metadata,
provider: self.metadataProvider,
explicit: explicitMetadata
)
let prettyMetadata: String?
if let effectiveMetadata = effectiveMetadata {
@@ -1211,10 +1395,16 @@ public struct StreamLogHandler: LogHandler {
}
var stream = self.stream
stream.write("\(self.timestamp()) \(level) \(self.label) :\(prettyMetadata.map { " \($0)" } ?? "") [\(source)] \(message)\n")
stream.write(
"\(self.timestamp()) \(level)\(self.label.isEmpty ? "" : " ")\(self.label):\(prettyMetadata.map { " \($0)" } ?? "") [\(source)] \(message)\n"
)
}
internal static func prepareMetadata(base: Logger.Metadata, provider: Logger.MetadataProvider?, explicit: Logger.Metadata?) -> Logger.Metadata? {
internal static func prepareMetadata(
base: Logger.Metadata,
provider: Logger.MetadataProvider?,
explicit: Logger.Metadata?
) -> Logger.Metadata? {
var metadata = base
let provided = provider?.get() ?? [:]
@@ -1274,33 +1464,42 @@ public struct SwiftLogNoOpLogHandler: LogHandler {
public init(_: String) {}
@inlinable public func log(level: Logger.Level, message: Logger.Message, metadata: Logger.Metadata?, file: String, function: String, line: UInt) {}
@inlinable public func log(
level: Logger.Level,
message: Logger.Message,
metadata: Logger.Metadata?,
file: String,
function: String,
line: UInt
) {}
public func log(level: Logger.Level,
message: Logger.Message,
metadata: Logger.Metadata?,
source: String,
file: String,
function: String,
line: UInt) {}
public func log(
level: Logger.Level,
message: Logger.Message,
metadata: Logger.Metadata?,
source: String,
file: String,
function: String,
line: UInt
) {}
@inlinable public subscript(metadataKey _: String) -> Logger.Metadata.Value? {
get {
return nil
nil
}
set {}
}
@inlinable public var metadata: Logger.Metadata {
get {
return [:]
[:]
}
set {}
}
@inlinable public var logLevel: Logger.Level {
get {
return .critical
.critical
}
set {}
}
@@ -1312,7 +1511,7 @@ extension Logger {
let utf8All = filePath.utf8
return filePath.utf8.lastIndex(of: UInt8(ascii: "/")).flatMap { lastSlash -> Substring? in
utf8All[..<lastSlash].lastIndex(of: UInt8(ascii: "/")).map { secondLastSlash -> Substring in
filePath[utf8All.index(after: secondLastSlash) ..< lastSlash]
filePath[utf8All.index(after: secondLastSlash)..<lastSlash]
}
}.map {
String($0)
@@ -1394,7 +1593,7 @@ private final class WarnOnceBox: @unchecked Sendable {
self.lock.withLock {
let id = ObjectIdentifier(type)
let (inserted, _) = warnOnceLogHandlerNotSupportedMetadataProviderPerType.insert(id)
return inserted // warn about this handler type, it is the first time we encountered it
return inserted // warn about this handler type, it is the first time we encountered it
}
}
}
+5 -3
View File
@@ -18,6 +18,8 @@ import Darwin
import CRT
#elseif canImport(Glibc)
import Glibc
#elseif canImport(Android)
import Android
#elseif canImport(Musl)
import Musl
#elseif canImport(WASILibc)
@@ -58,18 +60,18 @@ extension Logger {
public struct MetadataProvider: _SwiftLogSendable {
/// Provide ``Logger.Metadata`` from current context.
@usableFromInline
internal let _provideMetadata: @Sendable() -> Metadata
internal let _provideMetadata: @Sendable () -> Metadata
/// Create a new `MetadataProvider`.
///
/// - Parameter provideMetadata: A closure extracting metadata from the current execution context.
public init(_ provideMetadata: @escaping @Sendable() -> Metadata) {
public init(_ provideMetadata: @escaping @Sendable () -> Metadata) {
self._provideMetadata = provideMetadata
}
/// Invoke the metadata provider and return the generated contextual ``Logger/Metadata``.
public func get() -> Metadata {
return self._provideMetadata()
self._provideMetadata()
}
}
}
+23 -13
View File
@@ -12,7 +12,8 @@
//
//===----------------------------------------------------------------------===//
/* NOT @testable */ import Logging
// Not testable
import Logging
import XCTest
final class CompatibilityTest: XCTestCase {
@@ -43,20 +44,22 @@ final class CompatibilityTest: XCTestCase {
}
private struct OldSchoolTestLogging {
private let _config = Config() // shared among loggers
private let recorder = Recorder() // shared among loggers
private let _config = Config() // shared among loggers
private let recorder = Recorder() // shared among loggers
@available(*, deprecated, message: "Testing deprecated functionality")
func make(label: String) -> any LogHandler {
return OldSchoolLogHandler(label: label,
config: self.config,
recorder: self.recorder,
metadata: [:],
logLevel: .info)
OldSchoolLogHandler(
label: label,
config: self.config,
recorder: self.recorder,
metadata: [:],
logLevel: .info
)
}
var config: Config { return self._config }
var history: some History { return self.recorder }
var config: Config { self._config }
var history: some History { self.recorder }
}
@available(*, deprecated, message: "Testing deprecated functionality")
@@ -66,16 +69,23 @@ private struct OldSchoolLogHandler: LogHandler {
let recorder: Recorder
func make(label: String) -> some LogHandler {
return TestLogHandler(label: label, config: self.config, recorder: self.recorder)
TestLogHandler(label: label, config: self.config, recorder: self.recorder)
}
func log(level: Logger.Level, message: Logger.Message, metadata: Logger.Metadata?, file: String, function: String, line: UInt) {
func log(
level: Logger.Level,
message: Logger.Message,
metadata: Logger.Metadata?,
file: String,
function: String,
line: UInt
) {
self.recorder.record(level: level, metadata: metadata, message: message, source: "no source")
}
subscript(metadataKey metadataKey: String) -> Logger.Metadata.Value? {
get {
return self.metadata[metadataKey]
self.metadata[metadataKey]
}
set {
self.metadata[metadataKey] = newValue
+19 -4
View File
@@ -11,8 +11,11 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
@testable import Logging
import XCTest
@testable import Logging
#if compiler(>=6.0) || canImport(Darwin)
import Dispatch
#else
@@ -63,10 +66,18 @@ class GlobalLoggerTest: XCTestCase {
logging.history.assertNotExist(level: .info, message: "Struct2::doSomethingElse")
logging.history.assertExist(level: .error, message: "Struct3::doSomething")
logging.history.assertExist(level: .error, message: "Struct3::doSomethingElse", metadata: ["foo": "bar"])
logging.history.assertNotExist(level: .warning, message: "Struct3::doSomethingElseAsync", metadata: ["foo": "bar"])
logging.history.assertNotExist(
level: .warning,
message: "Struct3::doSomethingElseAsync",
metadata: ["foo": "bar"]
)
logging.history.assertNotExist(level: .info, message: "TestLibrary::doSomething", metadata: ["foo": "bar"])
logging.history.assertNotExist(level: .info, message: "TestLibrary::doSomethingAsync", metadata: ["foo": "bar"])
logging.history.assertNotExist(level: .debug, message: "Struct3::doSomethingElse::Local", metadata: ["baz": "qux"])
logging.history.assertNotExist(
level: .debug,
message: "Struct3::doSomethingElse::Local",
metadata: ["baz": "qux"]
)
logging.history.assertNotExist(level: .debug, message: "Struct3::doSomethingElse::end")
logging.history.assertNotExist(level: .debug, message: "Struct3::doSomething::end")
logging.history.assertNotExist(level: .debug, message: "Struct2::doSomethingElse::end")
@@ -95,7 +106,11 @@ class GlobalLoggerTest: XCTestCase {
logging.history.assertExist(level: .warning, message: "Struct3::doSomethingElseAsync", metadata: ["foo": "bar"])
logging.history.assertExist(level: .info, message: "TestLibrary::doSomething", metadata: ["foo": "bar"])
logging.history.assertExist(level: .info, message: "TestLibrary::doSomethingAsync", metadata: ["foo": "bar"])
logging.history.assertNotExist(level: .debug, message: "Struct3::doSomethingElse::Local", metadata: ["baz": "qux"])
logging.history.assertNotExist(
level: .debug,
message: "Struct3::doSomethingElse::Local",
metadata: ["baz": "qux"]
)
logging.history.assertNotExist(level: .debug, message: "Struct3::doSomethingElse::end")
logging.history.assertNotExist(level: .debug, message: "Struct3::doSomething::end")
logging.history.assertNotExist(level: .debug, message: "Struct2::doSomethingElse::end")
+48 -22
View File
@@ -11,8 +11,11 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
@testable import Logging
import XCTest
@testable import Logging
#if compiler(>=6.0) || canImport(Darwin)
import Dispatch
#else
@@ -40,7 +43,11 @@ class LocalLoggerTest: XCTestCase {
logging.history.assertExist(level: .warning, message: "Struct3::doSomethingElseAsync", metadata: ["bar": "baz"])
logging.history.assertExist(level: .info, message: "TestLibrary::doSomething")
logging.history.assertExist(level: .info, message: "TestLibrary::doSomethingAsync")
logging.history.assertExist(level: .debug, message: "Struct3::doSomethingElse::Local", metadata: ["bar": "baz", "baz": "qux"])
logging.history.assertExist(
level: .debug,
message: "Struct3::doSomethingElse::Local",
metadata: ["bar": "baz", "baz": "qux"]
)
logging.history.assertExist(level: .debug, message: "Struct3::doSomethingElse::end", metadata: ["bar": "baz"])
logging.history.assertExist(level: .debug, message: "Struct3::doSomething::end", metadata: ["bar": "baz"])
logging.history.assertExist(level: .debug, message: "Struct2::doSomethingElse::end")
@@ -59,21 +66,40 @@ class LocalLoggerTest: XCTestCase {
let context = Context()
Struct1().doSomething(context: context)
// test results
logging.history.assertNotExist(level: .debug, message: "Struct1::doSomething") // global context
logging.history.assertNotExist(level: .debug, message: "Struct1::doSomethingElse") // global context
logging.history.assertExist(level: .info, message: "Struct2::doSomething") // local context
logging.history.assertExist(level: .info, message: "Struct2::doSomethingElse") // local context
logging.history.assertExist(level: .error, message: "Struct3::doSomething", metadata: ["bar": "baz"]) // local context
logging.history.assertExist(level: .error, message: "Struct3::doSomethingElse", metadata: ["bar": "baz"]) // local context
logging.history.assertExist(level: .warning, message: "Struct3::doSomethingElseAsync", metadata: ["bar": "baz"]) // local context
logging.history.assertNotExist(level: .info, message: "TestLibrary::doSomething") // global context
logging.history.assertNotExist(level: .info, message: "TestLibrary::doSomethingAsync") // global context
logging.history.assertExist(level: .debug, message: "Struct3::doSomethingElse::Local", metadata: ["bar": "baz", "baz": "qux"]) // hyper local context
logging.history.assertExist(level: .debug, message: "Struct3::doSomethingElse::end", metadata: ["bar": "baz"]) // local context
logging.history.assertExist(level: .debug, message: "Struct2::doSomethingElse::end") // local context
logging.history.assertExist(level: .debug, message: "Struct3::doSomething::end", metadata: ["bar": "baz"]) // local context
logging.history.assertNotExist(level: .debug, message: "Struct1::doSomethingElse::end") // global context
logging.history.assertNotExist(level: .debug, message: "Struct1::doSomething::end") // global context
// global context
logging.history.assertNotExist(level: .debug, message: "Struct1::doSomething")
// global context
logging.history.assertNotExist(level: .debug, message: "Struct1::doSomethingElse")
// local context
logging.history.assertExist(level: .info, message: "Struct2::doSomething")
// local context
logging.history.assertExist(level: .info, message: "Struct2::doSomethingElse")
// local context
logging.history.assertExist(level: .error, message: "Struct3::doSomething", metadata: ["bar": "baz"])
// local context
logging.history.assertExist(level: .error, message: "Struct3::doSomethingElse", metadata: ["bar": "baz"])
// local context
logging.history.assertExist(level: .warning, message: "Struct3::doSomethingElseAsync", metadata: ["bar": "baz"])
// global context
logging.history.assertNotExist(level: .info, message: "TestLibrary::doSomething")
// global context
logging.history.assertNotExist(level: .info, message: "TestLibrary::doSomethingAsync")
// hyper local context
logging.history.assertExist(
level: .debug,
message: "Struct3::doSomethingElse::Local",
metadata: ["bar": "baz", "baz": "qux"]
)
// local context
logging.history.assertExist(level: .debug, message: "Struct3::doSomethingElse::end", metadata: ["bar": "baz"])
// local context
logging.history.assertExist(level: .debug, message: "Struct2::doSomethingElse::end")
// local context
logging.history.assertExist(level: .debug, message: "Struct3::doSomething::end", metadata: ["bar": "baz"])
// global context
logging.history.assertNotExist(level: .debug, message: "Struct1::doSomethingElse::end")
// global context
logging.history.assertNotExist(level: .debug, message: "Struct1::doSomething::end")
}
}
@@ -83,13 +109,13 @@ private struct Context {
// since logger is a value type, we can reuse our copy to manage logLevel
var logLevel: Logger.Level {
get { return self.logger.logLevel }
get { self.logger.logLevel }
set { self.logger.logLevel = newValue }
}
// since logger is a value type, we can reuse our copy to manage metadata
subscript(metadataKey: String) -> Logger.Metadata.Value? {
get { return self.logger[metadataKey: metadataKey] }
get { self.logger[metadataKey: metadataKey] }
set { self.logger[metadataKey: metadataKey] = newValue }
}
}
@@ -114,7 +140,7 @@ private struct Struct1 {
private struct Struct2 {
func doSomething(context: Context) {
var c = context
c.logLevel = .info // only effects from this point on
c.logLevel = .info // only effects from this point on
c.logger.info("Struct2::doSomething")
self.doSomethingElse(context: c)
c.logger.debug("Struct2::doSomething::end")
@@ -122,7 +148,7 @@ private struct Struct2 {
private func doSomethingElse(context: Context) {
var c = context
c.logLevel = .debug // only effects from this point on
c.logLevel = .debug // only effects from this point on
c.logger.info("Struct2::doSomethingElse")
Struct3().doSomething(context: c)
c.logger.debug("Struct2::doSomethingElse::end")
@@ -134,7 +160,7 @@ private struct Struct3 {
func doSomething(context: Context) {
var c = context
c["bar"] = "baz" // only effects from this point on
c["bar"] = "baz" // only effects from this point on
c.logger.error("Struct3::doSomething")
self.doSomethingElse(context: c)
c.logger.debug("Struct3::doSomething::end")
+381 -178
View File
@@ -11,25 +11,29 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
@testable import Logging
import XCTest
@testable import Logging
#if canImport(Darwin)
import Darwin
#elseif os(Windows)
import WinSDK
#elseif canImport(Android)
import Android
#else
import Glibc
#endif
private extension LogHandler {
func with(logLevel: Logger.Level) -> any LogHandler {
extension LogHandler {
fileprivate func with(logLevel: Logger.Level) -> any LogHandler {
var result = self
result.logLevel = logLevel
return result
}
func withMetadata(_ key: String, _ value: Logger.MetadataValue) -> any LogHandler {
fileprivate func withMetadata(_ key: String, _ value: Logger.MetadataValue) -> any LogHandler {
var result = self
result.metadata[key] = value
return result
@@ -44,27 +48,40 @@ class LoggingTest: XCTestCase {
var logger = Logger(label: "test")
logger.logLevel = .info
logger.log(level: .debug, {
XCTFail("debug should not be called")
return "debug"
}())
logger.trace({
XCTFail("trace should not be called")
return "trace"
}())
logger.debug({
XCTFail("debug should not be called")
return "debug"
}())
logger.info({
"info"
}())
logger.warning({
"warning"
}())
logger.error({
"error"
}())
logger.log(
level: .debug,
{
XCTFail("debug should not be called")
return "debug"
}()
)
logger.trace(
{
XCTFail("trace should not be called")
return "trace"
}()
)
logger.debug(
{
XCTFail("debug should not be called")
return "debug"
}()
)
logger.info(
{
"info"
}()
)
logger.warning(
{
"warning"
}()
)
logger.error(
{
"error"
}()
)
XCTAssertEqual(3, logging.history.entries.count, "expected number of entries to match")
logging.history.assertNotExist(level: .debug, message: "trace")
logging.history.assertNotExist(level: .debug, message: "debug")
@@ -138,8 +155,8 @@ class LoggingTest: XCTestCase {
messageMaterializations += 1
return "info"
}(),
metadata: { () ->
Logger.Metadata in metadataMaterializations += 1
metadata: { () -> Logger.Metadata in
metadataMaterializations += 1
return [:]
}()
)
@@ -170,42 +187,66 @@ class LoggingTest: XCTestCase {
// each logs its own metadata
multiplexLogger.info("info")
logging1.history.assertExist(level: .info, message: "info", metadata: [
"one": "111",
"in": "in-1",
])
logging2.history.assertExist(level: .info, message: "info", metadata: [
"two": "222",
"in": "in-2",
])
logging1.history.assertExist(
level: .info,
message: "info",
metadata: [
"one": "111",
"in": "in-1",
]
)
logging2.history.assertExist(
level: .info,
message: "info",
metadata: [
"two": "222",
"in": "in-2",
]
)
// if modified, change applies to both underlying handlers
multiplexLogger[metadataKey: "new"] = "new"
multiplexLogger.info("info")
logging1.history.assertExist(level: .info, message: "info", metadata: [
"one": "111",
"in": "in-1",
"new": "new",
])
logging2.history.assertExist(level: .info, message: "info", metadata: [
"two": "222",
"in": "in-2",
"new": "new",
])
logging1.history.assertExist(
level: .info,
message: "info",
metadata: [
"one": "111",
"in": "in-1",
"new": "new",
]
)
logging2.history.assertExist(
level: .info,
message: "info",
metadata: [
"two": "222",
"in": "in-2",
"new": "new",
]
)
// overriding an existing value works the same way as adding a new one
multiplexLogger[metadataKey: "in"] = "multi"
multiplexLogger.info("info")
logging1.history.assertExist(level: .info, message: "info", metadata: [
"one": "111",
"in": "multi",
"new": "new",
])
logging2.history.assertExist(level: .info, message: "info", metadata: [
"two": "222",
"in": "multi",
"new": "new",
])
logging1.history.assertExist(
level: .info,
message: "info",
metadata: [
"one": "111",
"in": "multi",
"new": "new",
]
)
logging2.history.assertExist(
level: .info,
message: "info",
metadata: [
"two": "222",
"in": "multi",
"new": "new",
]
)
}
func testMultiplexLogHandlerMetadata_readingHandlerMetadata() {
@@ -225,11 +266,14 @@ class LoggingTest: XCTestCase {
let multiplexLogger = Logger(label: "test")
XCTAssertEqual(multiplexLogger.handler.metadata, [
"one": "111",
"two": "222",
"in": "in-2",
])
XCTAssertEqual(
multiplexLogger.handler.metadata,
[
"one": "111",
"two": "222",
"in": "in-2",
]
)
}
func testMultiplexMetadataProviderSet() {
@@ -263,19 +307,25 @@ class LoggingTest: XCTestCase {
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",
])
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() {
@@ -301,24 +351,30 @@ class LoggingTest: XCTestCase {
return handler2
}()
LoggingSystem.bootstrapInternal({ _, metadataProvider in
MultiplexLogHandler(
[handler1, handler2],
metadataProvider: metadataProvider
)
}, metadataProvider: .constant([
"provider-overlap": "provided-outer",
]))
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",
])
XCTAssertEqual(
provider.get(),
[
"provider-1": "provided-111",
"provider-2": "provided-222",
"provider-overlap": "provided-outer",
]
)
}
enum TestError: Error {
@@ -334,11 +390,15 @@ class LoggingTest: XCTestCase {
logger[metadataKey: "empty-dict"] = [:]
logger[metadataKey: "nested-dict"] = ["l1key": ["l2key": ["l3key": "l3value"]]]
logger.info("hello world!")
testLogging.history.assertExist(level: .info,
message: "hello world!",
metadata: ["foo": ["bar": "buz"],
"empty-dict": [:],
"nested-dict": ["l1key": ["l2key": ["l3key": "l3value"]]]])
testLogging.history.assertExist(
level: .info,
message: "hello world!",
metadata: [
"foo": ["bar": "buz"],
"empty-dict": [:],
"nested-dict": ["l1key": ["l2key": ["l3key": "l3value"]]],
]
)
}
func testListMetadata() {
@@ -350,11 +410,15 @@ class LoggingTest: XCTestCase {
logger[metadataKey: "empty-list"] = []
logger[metadataKey: "nested-list"] = ["l1str", ["l2str1", "l2str2"]]
logger.info("hello world!")
testLogging.history.assertExist(level: .info,
message: "hello world!",
metadata: ["foo": ["bar", "buz"],
"empty-list": [],
"nested-list": ["l1str", ["l2str1", "l2str2"]]])
testLogging.history.assertExist(
level: .info,
message: "hello world!",
metadata: [
"foo": ["bar", "buz"],
"empty-list": [],
"nested-list": ["l1str", ["l2str1", "l2str2"]],
]
)
}
// Example of custom "box" which may be used to implement "render at most once" semantics
@@ -380,7 +444,7 @@ class LoggingTest: XCTestCase {
}
public var description: String {
return "\(self.value)"
"\(self.value)"
}
}
@@ -393,13 +457,17 @@ class LoggingTest: XCTestCase {
let lazyBox = LazyMetadataBox { "rendered-at-first-use" }
logger[metadataKey: "lazy"] = .stringConvertible(lazyBox)
logger.info("hello world!")
testLogging.history.assertExist(level: .info,
message: "hello world!",
metadata: ["foo": .stringConvertible("raw-string"),
"lazy": .stringConvertible(LazyMetadataBox { "rendered-at-first-use" })])
testLogging.history.assertExist(
level: .info,
message: "hello world!",
metadata: [
"foo": .stringConvertible("raw-string"),
"lazy": .stringConvertible(LazyMetadataBox { "rendered-at-first-use" }),
]
)
}
private func dontEvaluateThisString(file: StaticString = #file, line: UInt = #line) -> Logger.Message {
private func dontEvaluateThisString(file: StaticString = #filePath, line: UInt = #line) -> Logger.Message {
XCTFail("should not have been evaluated", file: file, line: line)
return "should not have been evaluated"
}
@@ -429,26 +497,38 @@ class LoggingTest: XCTestCase {
logger.warning("hello world!")
logger.error("hello world!", metadata: ["baz": "quc"])
testLogging.history.assertExist(level: .info, message: "hello world!", metadata: ["foo": "bar"])
testLogging.history.assertExist(level: .warning, message: "hello world!", metadata: ["bar": "baz", "baz": "qux"])
testLogging.history.assertExist(
level: .warning,
message: "hello world!",
metadata: ["bar": "baz", "baz": "qux"]
)
testLogging.history.assertExist(level: .error, message: "hello world!", metadata: ["bar": "baz", "baz": "quc"])
}
func testCustomFactory() {
struct CustomHandler: LogHandler {
func log(level: Logger.Level, message: Logger.Message, metadata: Logger.Metadata?, source: String, file: String, function: String, line: UInt) {}
func log(
level: Logger.Level,
message: Logger.Message,
metadata: Logger.Metadata?,
source: String,
file: String,
function: String,
line: UInt
) {}
subscript(metadataKey _: String) -> Logger.Metadata.Value? {
get { return nil }
get { nil }
set {}
}
var metadata: Logger.Metadata {
get { return Logger.Metadata() }
get { Logger.Metadata() }
set {}
}
var logLevel: Logger.Level {
get { return .info }
get { .info }
set {}
}
}
@@ -580,7 +660,7 @@ class LoggingTest: XCTestCase {
emitLogMessage("hello", to: logger)
let moduleName = "LoggingTests" // the actual name
let moduleName = "LoggingTests" // the actual name
testLogging.history.assertExist(level: .trace, message: "hello", source: moduleName)
testLogging.history.assertExist(level: .debug, message: "hello", source: moduleName)
@@ -598,10 +678,12 @@ class LoggingTest: XCTestCase {
var logger = Logger(label: "\(#function)")
logger.logLevel = .debug
let someInt = Int.random(in: 23 ..< 42)
let someInt = Int.random(in: 23..<42)
logger.debug("My favourite number is \(someInt) and not \(someInt - 1)")
testLogging.history.assertExist(level: .debug,
message: "My favourite number is \(someInt) and not \(someInt - 1)" as String)
testLogging.history.assertExist(
level: .debug,
message: "My favourite number is \(someInt) and not \(someInt - 1)" as String
)
}
func testLoggingAString() {
@@ -625,66 +707,85 @@ class LoggingTest: XCTestCase {
let providerA = Logger.MetadataProvider { ["provider": "a", "a": "foo"] }
let providerB = Logger.MetadataProvider { ["provider": "b", "b": "bar"] }
let logger = Logger(label: #function,
factory: { label in
logging.makeWithMetadataProvider(label: label, metadataProvider: .multiplex([providerA, providerB]))
})
let logger = Logger(
label: #function,
factory: { label in
logging.makeWithMetadataProvider(label: label, metadataProvider: .multiplex([providerA, providerB]))
}
)
logger.log(level: .info, "test", metadata: ["one-off": "42"])
logging.history.assertExist(level: .info,
message: "test",
metadata: ["provider": "b", "a": "foo", "b": "bar", "one-off": "42"])
logging.history.assertExist(
level: .info,
message: "test",
metadata: ["provider": "b", "a": "foo", "b": "bar", "one-off": "42"]
)
}
func testLoggerWithoutFactoryOverrideDefaultsToUsingLoggingSystemMetadataProvider() {
let logging = TestLogging()
LoggingSystem.bootstrapInternal({ logging.makeWithMetadataProvider(label: $0, metadataProvider: $1) },
metadataProvider: .init { ["provider": "42"] })
let logger = Logger(label: #function)
logger.log(level: .info, "test", metadata: ["one-off": "42"])
logging.history.assertExist(level: .info,
message: "test",
metadata: ["provider": "42", "one-off": "42"])
}
func testLoggerWithPredefinedLibraryMetadataProvider() {
let logging = TestLogging()
LoggingSystem.bootstrapInternal(
{ logging.makeWithMetadataProvider(label: $0, metadataProvider: $1) },
metadataProvider: .exampleMetadataProvider
metadataProvider: .init { ["provider": "42"] }
)
let logger = Logger(label: #function)
logger.log(level: .info, "test", metadata: ["one-off": "42"])
logging.history.assertExist(level: .info,
message: "test",
metadata: ["example": "example-value", "one-off": "42"])
logging.history.assertExist(
level: .info,
message: "test",
metadata: ["provider": "42", "one-off": "42"]
)
}
func testLoggerWithPredefinedLibraryMetadataProvider() {
let logging = TestLogging()
LoggingSystem.bootstrapInternal(
{ logging.makeWithMetadataProvider(label: $0, metadataProvider: $1) },
metadataProvider: .exampleProvider
)
let logger = Logger(label: #function)
logger.log(level: .info, "test", metadata: ["one-off": "42"])
logging.history.assertExist(
level: .info,
message: "test",
metadata: ["example": "example-value", "one-off": "42"]
)
}
func testLoggerWithFactoryOverrideDefaultsToUsingLoggingSystemMetadataProvider() {
let logging = TestLogging()
LoggingSystem.bootstrapInternal({ logging.makeWithMetadataProvider(label: $0, metadataProvider: $1) },
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)
})
let logger = Logger(
label: #function,
factory: { label in
logging.makeWithMetadataProvider(label: label, metadataProvider: LoggingSystem.metadataProvider)
}
)
logger.log(level: .info, "test", metadata: ["one-off": "42"])
logging.history.assertExist(level: .info,
message: "test",
metadata: ["provider": "42", "one-off": "42"])
logging.history.assertExist(
level: .info,
message: "test",
metadata: ["provider": "42", "one-off": "42"]
)
}
func testMultiplexerIsValue() {
let multi = MultiplexLogHandler([StreamLogHandler.standardOutput(label: "x"), StreamLogHandler.standardOutput(label: "y")])
let multi = MultiplexLogHandler([
StreamLogHandler.standardOutput(label: "x"), StreamLogHandler.standardOutput(label: "y"),
])
LoggingSystem.bootstrapInternal { _ in
print("new multi")
return multi
@@ -752,7 +853,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.overrideLogLevel.underlying ?? self._logLevel
LogHandlerWithGlobalLogLevelOverride.overrideLogLevel.underlying ?? self._logLevel
}
// we set the log level whenever we're asked (note: this might not have an effect if globally
// overridden)
@@ -761,14 +862,21 @@ class LoggingTest: XCTestCase {
}
}
func log(level: Logger.Level, message: Logger.Message, metadata: Logger.Metadata?,
source: String, file: String, function: String, line: UInt) {
func log(
level: Logger.Level,
message: Logger.Message,
metadata: Logger.Metadata?,
source: String,
file: String,
function: String,
line: UInt
) {
self.recorder.record(level: level, metadata: metadata, message: message, source: source)
}
subscript(metadataKey metadataKey: String) -> Logger.Metadata.Value? {
get {
return self.metadata[metadataKey]
self.metadata[metadataKey]
}
set(newValue) {
self.metadata[metadataKey] = newValue
@@ -861,7 +969,8 @@ class LoggingTest: XCTestCase {
let testString = "my message is better than yours"
log.critical("\(testString)")
let messageSucceeded = interceptStream.interceptedText?.trimmingCharacters(in: .whitespacesAndNewlines).hasSuffix(testString)
let messageSucceeded = interceptStream.interceptedText?.trimmingCharacters(in: .whitespacesAndNewlines)
.hasSuffix(testString)
XCTAssertTrue(messageSucceeded ?? false)
XCTAssertEqual(interceptStream.strings.count, 1)
@@ -879,9 +988,38 @@ class LoggingTest: XCTestCase {
let testString = "my message is better than yours"
log.critical("\(testString)", source: source)
let pattern = "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\+|-)\\d{4}\\s\(Logger.Level.critical)\\s\(label)\\s:\\s\\[\(source)\\]\\s\(testString)$"
let pattern =
"^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\+|-)\\d{4}\\s\(Logger.Level.critical)\\s\(label):\\s\\[\(source)\\]\\s\(testString)$"
let messageSucceeded = interceptStream.interceptedText?.trimmingCharacters(in: .whitespacesAndNewlines).range(of: pattern, options: .regularExpression) != nil
let messageSucceeded =
interceptStream.interceptedText?.trimmingCharacters(in: .whitespacesAndNewlines).range(
of: pattern,
options: .regularExpression
) != nil
XCTAssertTrue(messageSucceeded)
XCTAssertEqual(interceptStream.strings.count, 1)
}
func testStreamLogHandlerOutputFormatWithEmptyLabel() {
let interceptStream = InterceptStream()
LoggingSystem.bootstrapInternal { label in
StreamLogHandler(label: label, stream: interceptStream)
}
let source = "testSource"
let log = Logger(label: "")
let testString = "my message is better than yours"
log.critical("\(testString)", source: source)
let pattern =
"^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\+|-)\\d{4}\\s\(Logger.Level.critical):\\s\\[\(source)\\]\\s\(testString)$"
let messageSucceeded =
interceptStream.interceptedText?.trimmingCharacters(in: .whitespacesAndNewlines).range(
of: pattern,
options: .regularExpression
) != nil
XCTAssertTrue(messageSucceeded)
XCTAssertEqual(interceptStream.strings.count, 1)
@@ -899,9 +1037,14 @@ class LoggingTest: XCTestCase {
let testString = "my message is better than yours"
log.critical("\(testString)", metadata: ["test": "test"], source: source)
let pattern = "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\+|-)\\d{4}\\s\(Logger.Level.critical)\\s\(label)\\s:\\stest=test\\s\\[\(source)\\]\\s\(testString)$"
let pattern =
"^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\+|-)\\d{4}\\s\(Logger.Level.critical)\\s\(label):\\stest=test\\s\\[\(source)\\]\\s\(testString)$"
let messageSucceeded = interceptStream.interceptedText?.trimmingCharacters(in: .whitespacesAndNewlines).range(of: pattern, options: .regularExpression) != nil
let messageSucceeded =
interceptStream.interceptedText?.trimmingCharacters(in: .whitespacesAndNewlines).range(
of: pattern,
options: .regularExpression
) != nil
XCTAssertTrue(messageSucceeded)
XCTAssertEqual(interceptStream.strings.count, 1)
@@ -931,15 +1074,19 @@ class LoggingTest: XCTestCase {
func testStreamLogHandlerWritesIncludeMetadataProviderMetadata() {
let interceptStream = InterceptStream()
LoggingSystem.bootstrapInternal({ _, metadataProvider in
StreamLogHandler(label: "test", stream: interceptStream, metadataProvider: metadataProvider)
}, metadataProvider: .exampleMetadataProvider)
LoggingSystem.bootstrapInternal(
{ _, metadataProvider in
StreamLogHandler(label: "test", stream: interceptStream, metadataProvider: metadataProvider)
},
metadataProvider: .exampleProvider
)
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)
let messageSucceeded = interceptStream.interceptedText?.trimmingCharacters(in: .whitespacesAndNewlines)
.hasSuffix(testString)
XCTAssertTrue(messageSucceeded ?? false)
XCTAssertEqual(interceptStream.strings.count, 1)
@@ -955,9 +1102,16 @@ class LoggingTest: XCTestCase {
let testString = "hello\u{0} world"
log.critical("\(testString)")
#if os(Windows)
let size = _read(readFD, readBuffer, 256)
#else
let size = read(readFD, readBuffer, 256)
#endif
let output = String(decoding: UnsafeRawBufferPointer(start: UnsafeRawPointer(readBuffer), count: numericCast(size)), as: UTF8.self)
let output = String(
decoding: UnsafeRawBufferPointer(start: UnsafeRawPointer(readBuffer), count: numericCast(size)),
as: UTF8.self
)
let messageSucceeded = output.trimmingCharacters(in: .whitespacesAndNewlines).hasSuffix(testString)
XCTAssertTrue(messageSucceeded)
}
@@ -970,11 +1124,20 @@ class LoggingTest: XCTestCase {
LoggingSystem.bootstrapInternal { StreamLogHandler(label: $0, stream: logStream) }
Logger(label: "test").critical("test")
#if os(Windows)
let size = _read(readFD, readBuffer, 256)
#else
let size = read(readFD, readBuffer, 256)
#endif
XCTAssertGreaterThan(size, -1, "expected flush")
logStream.flush()
#if os(Windows)
let size2 = _read(readFD, readBuffer, 256)
#else
let size2 = read(readFD, readBuffer, 256)
#endif
XCTAssertEqual(size2, -1, "expected no flush")
}
// default flushing
@@ -983,11 +1146,20 @@ class LoggingTest: XCTestCase {
LoggingSystem.bootstrapInternal { StreamLogHandler(label: $0, stream: logStream) }
Logger(label: "test").critical("test")
#if os(Windows)
let size = _read(readFD, readBuffer, 256)
#else
let size = read(readFD, readBuffer, 256)
#endif
XCTAssertEqual(size, -1, "expected no flush")
logStream.flush()
#if os(Windows)
let size2 = _read(readFD, readBuffer, 256)
#else
let size2 = read(readFD, readBuffer, 256)
#endif
XCTAssertGreaterThan(size2, -1, "expected flush")
}
}
@@ -999,14 +1171,21 @@ class LoggingTest: XCTestCase {
let err = _pipe($0.baseAddress, 256, _O_BINARY)
XCTAssertEqual(err, 0, "_pipe failed \(err)")
}
guard let writeFD = _fdopen(fds[1], "w") else {
XCTFail("Failed to open file")
return
}
#else
fds.withUnsafeMutableBufferPointer { ptr in
let err = pipe(ptr.baseAddress!)
XCTAssertEqual(err, 0, "pipe failed \(err)")
}
guard let writeFD = fdopen(fds[1], "w") else {
XCTFail("Failed to open file")
return
}
#endif
let writeFD = fdopen(fds[1], "w")
let writeBuffer = UnsafeMutablePointer<Int8>.allocate(capacity: 256)
defer {
writeBuffer.deinitialize(count: 256)
@@ -1036,15 +1215,21 @@ class LoggingTest: XCTestCase {
}
// the actual test
body(writeFD!, readFD, readBuffer)
body(writeFD, readFD, readBuffer)
fds.forEach { close($0) }
for fd in fds {
#if os(Windows)
_close(fd)
#else
close(fd)
#endif
}
}
func testOverloadingError() {
struct Dummy: Error, LocalizedError {
var errorDescription: String? {
return "errorDescription"
"errorDescription"
}
}
// bootstrap with our test logging impl
@@ -1060,7 +1245,7 @@ class LoggingTest: XCTestCase {
func testCompileInitializeStandardStreamLogHandlersWithMetadataProviders() {
// avoid "unreachable code" warnings
let dontExecute = Int.random(in: 100 ... 200) == 1
let dontExecute = Int.random(in: 100...200) == 1
guard dontExecute else {
return
}
@@ -1070,18 +1255,32 @@ class LoggingTest: XCTestCase {
LoggingSystem.bootstrap { (label: String) in StreamLogHandler.standardError(label: label) }
// 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)
LoggingSystem.bootstrap(
{ label, metadataProvider in
StreamLogHandler.standardOutput(label: label, metadataProvider: metadataProvider)
},
metadataProvider: .exampleProvider
)
LoggingSystem.bootstrap(
{ label, metadataProvider in
StreamLogHandler.standardError(label: label, metadataProvider: metadataProvider)
},
metadataProvider: .exampleProvider
)
// with metadata handler, still pretty
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)
LoggingSystem.bootstrap(
{ (label: String, metadataProvider: Logger.MetadataProvider?) in
StreamLogHandler.standardOutput(label: label, metadataProvider: metadataProvider)
},
metadataProvider: .exampleProvider
)
LoggingSystem.bootstrap(
{ (label: String, metadataProvider: Logger.MetadataProvider?) in
StreamLogHandler.standardError(label: label, metadataProvider: metadataProvider)
},
metadataProvider: .exampleProvider
)
}
func testLoggerIsJustHoldingASinglePointer() {
@@ -1100,15 +1299,19 @@ class LoggingTest: XCTestCase {
}
extension Logger {
public func error(error: any Error,
metadata: @autoclosure () -> Logger.Metadata? = nil,
file: String = #fileID, function: String = #function, line: UInt = #line) {
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)
}
}
extension Logger.MetadataProvider {
static var exampleMetadataProvider: Self {
static var exampleProvider: Self {
.init { ["example": .string("example-value")] }
}
+9 -8
View File
@@ -12,9 +12,10 @@
//
//===----------------------------------------------------------------------===//
import Dispatch
@testable import Logging
import XCTest
@testable import Logging
class MDCTest: XCTestCase {
func test1() throws {
// bootstrap with our test logger
@@ -24,22 +25,22 @@ class MDCTest: XCTestCase {
// run the program
MDC.global["foo"] = "bar"
let group = DispatchGroup()
for r in 5 ... 10 {
for r in 5...10 {
group.enter()
DispatchQueue(label: "mdc-test-queue-\(r)").async {
let add = Int.random(in: 10 ... 1000)
let remove = Int.random(in: 0 ... add - 1)
for i in 0 ... add {
let add = Int.random(in: 10...1000)
let remove = Int.random(in: 0...add - 1)
for i in 0...add {
MDC.global["key-\(i)"] = "value-\(i)"
}
for i in 0 ... remove {
for i in 0...remove {
MDC.global["key-\(i)"] = nil
}
XCTAssertEqual(add - remove, MDC.global.metadata.count, "expected number of entries to match")
for i in remove + 1 ... add {
for i in remove + 1...add {
XCTAssertNotNil(MDC.global["key-\(i)"], "expecting value for key-\(i)")
}
for i in 0 ... remove {
for i in 0...remove {
XCTAssertNil(MDC.global["key-\(i)"], "not expecting value for key-\(i)")
}
MDC.global.clear()
+77 -35
View File
@@ -11,13 +11,17 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
@testable import Logging
import XCTest
@testable import Logging
#if canImport(Darwin)
import Darwin
#elseif os(Windows)
import WinSDK
#elseif canImport(Android)
import Android
#else
import Glibc
#endif
@@ -25,22 +29,30 @@ import Glibc
final class MetadataProviderTest: XCTestCase {
func testLoggingMergesOneOffMetadataWithProvidedMetadataFromExplicitlyPassed() throws {
let logging = TestLogging()
LoggingSystem.bootstrapInternal({ logging.makeWithMetadataProvider(label: $0, metadataProvider: $1) },
metadataProvider: .init { ["common": "initial"]
})
LoggingSystem.bootstrapInternal(
{ logging.makeWithMetadataProvider(label: $0, metadataProvider: $1) },
metadataProvider: .init {
["common": "initial"]
}
)
let logger = Logger(label: #function, metadataProvider: .init {
[
"common": "provider",
"provider": "42",
]
})
let logger = Logger(
label: #function,
metadataProvider: .init {
[
"common": "provider",
"provider": "42",
]
}
)
logger.log(level: .info, "test", metadata: ["one-off": "42", "common": "one-off"])
logging.history.assertExist(level: .info,
message: "test",
metadata: ["common": "one-off", "one-off": "42", "provider": "42"])
logging.history.assertExist(
level: .info,
message: "test",
metadata: ["common": "one-off", "one-off": "42", "provider": "42"]
)
}
func testLogHandlerThatDidNotImplementProvidersButSomeoneAttemptsToSetOneOnIt() {
@@ -51,7 +63,12 @@ final class MetadataProviderTest: XCTestCase {
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")
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
@@ -67,15 +84,20 @@ final class MetadataProviderTest: XCTestCase {
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")
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
}
}
extension Logger.MetadataProvider {
static var simpleTestProvider: Logger.MetadataProvider {
return Logger.MetadataProvider {
return ["test": "provided"]
Logger.MetadataProvider {
["test": "provided"]
}
}
}
@@ -88,7 +110,7 @@ public struct LogHandlerThatDidNotImplementMetadataProviders: LogHandler {
public subscript(metadataKey _: String) -> Logging.Logger.Metadata.Value? {
get {
return nil
nil
}
set(newValue) {
// ignore
@@ -99,14 +121,24 @@ public struct LogHandlerThatDidNotImplementMetadataProviders: LogHandler {
public var logLevel: Logging.Logger.Level = .trace
public func log(level: Logger.Level,
message: Logger.Message,
metadata: Logger.Metadata?,
source: String,
file: String,
function: String,
line: UInt) {
self.testLogging.make(label: "fake").log(level: level, message: message, metadata: metadata, source: source, file: file, function: function, line: line)
public func log(
level: Logger.Level,
message: Logger.Message,
metadata: Logger.Metadata?,
source: String,
file: String,
function: String,
line: UInt
) {
self.testLogging.make(label: "fake").log(
level: level,
message: message,
metadata: metadata,
source: source,
file: file,
function: function,
line: line
)
}
}
@@ -118,7 +150,7 @@ public struct LogHandlerThatDidImplementMetadataProviders: LogHandler {
public subscript(metadataKey _: String) -> Logging.Logger.Metadata.Value? {
get {
return nil
nil
}
set(newValue) {
// ignore
@@ -131,13 +163,23 @@ public struct LogHandlerThatDidImplementMetadataProviders: LogHandler {
public var metadataProvider: Logger.MetadataProvider?
public func log(level: Logger.Level,
message: Logger.Message,
metadata: Logger.Metadata?,
source: String,
file: String,
function: String,
line: UInt) {
self.testLogging.make(label: "fake").log(level: level, message: message, metadata: metadata, source: source, file: file, function: function, line: line)
public func log(
level: Logger.Level,
message: Logger.Message,
metadata: Logger.Metadata?,
source: String,
file: String,
function: String,
line: UInt
) {
self.testLogging.make(label: "fake").log(
level: level,
message: message,
metadata: metadata,
source: source,
file: file,
function: function,
line: line
)
}
}
+92 -55
View File
@@ -11,9 +11,12 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Foundation
@testable import Logging
import XCTest
@testable import Logging
#if os(Windows)
import WinSDK
#endif
@@ -24,11 +27,11 @@ import Dispatch
#endif
internal struct TestLogging {
private let _config = Config() // shared among loggers
private let recorder = Recorder() // shared among loggers
private let _config = Config() // shared among loggers
private let recorder = Recorder() // shared among loggers
func make(label: String) -> some LogHandler {
return TestLogHandler(
TestLogHandler(
label: label,
config: self.config,
recorder: self.recorder,
@@ -37,7 +40,7 @@ internal struct TestLogging {
}
func makeWithMetadataProvider(label: String, metadataProvider: Logger.MetadataProvider?) -> (some LogHandler) {
return TestLogHandler(
TestLogHandler(
label: label,
config: self.config,
recorder: self.recorder,
@@ -45,14 +48,14 @@ internal struct TestLogging {
)
}
var config: Config { return self._config }
var history: some History { return self.recorder }
var config: Config { self._config }
var history: some History { self.recorder }
}
internal struct TestLogHandler: LogHandler {
private let recorder: Recorder
private let config: Config
private var logger: Logger // the actual logger
private var logger: Logger // the actual logger
let label: String
public var metadataProvider: Logger.MetadataProvider?
@@ -75,11 +78,15 @@ internal struct TestLogHandler: LogHandler {
self.metadataProvider = LoggingSystem.metadataProvider
}
func log(level: Logger.Level,
message: Logger.Message,
metadata explicitMetadata: Logger.Metadata?,
source: String,
file: String, function: String, line: UInt) {
func log(
level: Logger.Level,
message: Logger.Message,
metadata explicitMetadata: Logger.Metadata?,
source: String,
file: String,
function: String,
line: UInt
) {
// baseline metadata, that was set on handler:
var metadata = self._metadataSet ? self.metadata : MDC.global.metadata
// contextual metadata, e.g. from task-locals:
@@ -92,7 +99,15 @@ internal struct TestLogHandler: LogHandler {
metadata.merge(explicitMetadata, uniquingKeysWith: { _, explicit in explicit })
}
self.logger.log(level: level, message, metadata: metadata, source: source, file: file, function: function, line: line)
self.logger.log(
level: level,
message,
metadata: metadata,
source: source,
file: file,
function: function,
line: line
)
self.recorder.record(level: level, metadata: metadata, message: message, source: source)
}
@@ -100,7 +115,7 @@ internal struct TestLogHandler: LogHandler {
var logLevel: Logger.Level {
get {
// get from config unless set
return self._logLevel ?? self.config.get(key: self.label)
self._logLevel ?? self.config.get(key: self.label)
}
set {
self._logLevel = newValue
@@ -116,7 +131,7 @@ internal struct TestLogHandler: LogHandler {
public var metadata: Logger.Metadata {
get {
return self._metadata
self._metadata
}
set {
self._metadata = newValue
@@ -126,7 +141,7 @@ internal struct TestLogHandler: LogHandler {
// TODO: would be nice to delegate to local copy of logger but StdoutLogger is a reference type. why?
subscript(metadataKey metadataKey: Logger.Metadata.Key) -> Logger.Metadata.Value? {
get {
return self._metadata[metadataKey]
self._metadata[metadataKey]
}
set {
self._metadata[metadataKey] = newValue
@@ -141,7 +156,7 @@ internal class Config {
private var storage = [String: Logger.Level]()
func get(key: String) -> Logger.Level {
return self.get(key) ?? self.get(Config.ALL) ?? Logger.Level.debug
self.get(key) ?? self.get(Config.ALL) ?? Logger.Level.debug
}
func get(_ key: String) -> Logger.Level? {
@@ -165,13 +180,15 @@ internal class Recorder: History {
private var _entries = [LogEntry]()
func record(level: Logger.Level, metadata: Logger.Metadata?, message: Logger.Message, source: String) {
return self.lock.withLock {
self._entries.append(LogEntry(level: level, metadata: metadata, message: message.description, source: source))
self.lock.withLock {
self._entries.append(
LogEntry(level: level, metadata: metadata, message: message.description, source: source)
)
}
}
var entries: [LogEntry] {
return self.lock.withLock { self._entries }
self.lock.withLock { self._entries }
}
}
@@ -179,31 +196,31 @@ internal protocol History {
var entries: [LogEntry] { get }
}
internal extension History {
extension History {
func atLevel(level: Logger.Level) -> [LogEntry] {
return self.entries.filter { entry in
self.entries.filter { entry in
level == entry.level
}
}
var trace: [LogEntry] {
return self.atLevel(level: .debug)
self.atLevel(level: .debug)
}
var debug: [LogEntry] {
return self.atLevel(level: .debug)
self.atLevel(level: .debug)
}
var info: [LogEntry] {
return self.atLevel(level: .info)
self.atLevel(level: .info)
}
var warning: [LogEntry] {
return self.atLevel(level: .warning)
self.atLevel(level: .warning)
}
var error: [LogEntry] {
return self.atLevel(level: .error)
self.atLevel(level: .error)
}
}
@@ -215,34 +232,46 @@ internal struct LogEntry {
}
extension History {
func assertExist(level: Logger.Level,
message: String,
metadata: Logger.Metadata? = nil,
source: String? = nil,
file: StaticString = #file,
fileID: String = #fileID,
line: UInt = #line) {
func assertExist(
level: Logger.Level,
message: String,
metadata: Logger.Metadata? = nil,
source: String? = nil,
file: StaticString = #filePath,
fileID: String = #fileID,
line: UInt = #line
) {
let source = source ?? Logger.currentModule(fileID: "\(fileID)")
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)
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,
fileID: String = #file,
line: UInt = #line) {
func assertNotExist(
level: Logger.Level,
message: String,
metadata: Logger.Metadata? = nil,
source: String? = nil,
file: StaticString = #filePath,
fileID: String = #file,
line: UInt = #line
) {
let source = source ?? Logger.currentModule(fileID: "\(fileID)")
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)
XCTAssertNil(
entry,
"entry was found: \(level), \(source), \(String(describing: metadata)), \(message)",
file: file,
line: line
)
}
func find(level: Logger.Level, message: String, metadata: Logger.Metadata? = nil, source: String) -> LogEntry? {
return self.entries.first { entry in
self.entries.first { entry in
if entry.level != level {
return false
}
@@ -287,7 +316,7 @@ public class MDC {
public subscript(metadataKey: String) -> Logger.Metadata.Value? {
get {
return self.lock.withLock {
self.lock.withLock {
self.storage[self.threadId]?[metadataKey]
}
}
@@ -302,7 +331,7 @@ public class MDC {
}
public var metadata: Logger.Metadata {
return self.lock.withLock {
self.lock.withLock {
self.storage[self.threadId] ?? [:]
}
}
@@ -314,17 +343,25 @@ public class MDC {
}
public func with(metadata: Logger.Metadata, _ body: () throws -> Void) rethrows {
metadata.forEach { self[$0] = $1 }
for (key, value) in metadata {
self[key] = value
}
defer {
metadata.keys.forEach { self[$0] = nil }
for (key, _) in metadata {
self[key] = nil
}
}
try body()
}
public func with<T>(metadata: Logger.Metadata, _ body: () throws -> T) rethrows -> T {
metadata.forEach { self[$0] = $1 }
for (key, value) in metadata {
self[key] = value
}
defer {
metadata.keys.forEach { self[$0] = nil }
for (key, _) in metadata {
self[key] = nil
}
}
return try body()
}
@@ -347,7 +384,7 @@ public class MDC {
}
}
internal extension NSLock {
extension NSLock {
func withLock<T>(_ body: () -> T) -> T {
self.lock()
defer {
@@ -367,7 +404,7 @@ internal struct TestLibrary: Sendable {
self.logger.info("TestLibrary::doSomething")
}
public func doSomethingAsync(completion: @escaping @Sendable() -> 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
+3 -1
View File
@@ -11,9 +11,11 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
@testable import Logging
import XCTest
@testable import Logging
class SendableTest: XCTestCase {
func testSendableLogger() async {
let testLogging = TestLogging()
-31
View File
@@ -1,31 +0,0 @@
ARG swift_version=5.0
ARG ubuntu_version=bionic
ARG base_image=swift:$swift_version-$ubuntu_version
FROM $base_image
# needed to do again after FROM due to docker limitation
ARG swift_version
ARG ubuntu_version
# set as UTF-8
RUN apt-get update && apt-get install -y locales locales-all
ENV LC_ALL en_US.UTF-8
ENV LANG en_US.UTF-8
ENV LANGUAGE en_US.UTF-8
# dependencies
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 for scripts
RUN apt-get update && apt-get install -y ruby
# tools
RUN mkdir -p $HOME/.tools
RUN echo 'export PATH="$HOME/.tools:$PATH"' >> $HOME/.profile
# swiftformat (until part of the toolchain)
ARG swiftformat_version=0.44.6
RUN git clone --branch $swiftformat_version --depth 1 https://github.com/nicklockwood/SwiftFormat $HOME/.tools/swift-format
RUN cd $HOME/.tools/swift-format && swift build -c release
RUN ln -s $HOME/.tools/swift-format/.build/release/swiftformat $HOME/.tools/swiftformat
-19
View File
@@ -1,19 +0,0 @@
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:
- WARN_AS_ERROR_ARG=-Xswiftc -warnings-as-errors
#- SANITIZER_ARG=--sanitize=thread
shell:
image: swift-log:20.04-5.8
-18
View File
@@ -1,18 +0,0 @@
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
-19
View File
@@ -1,19 +0,0 @@
version: "3"
services:
runtime-setup:
image: swift-log:22.04-5.9
build:
args:
ubuntu_version: "jammy"
swift_version: "5.9"
test:
image: swift-log:22.04-5.9
environment:
- WARN_AS_ERROR_ARG=-Xswiftc -warnings-as-errors
#- SANITIZER_ARG=--sanitize=thread
shell:
image: swift-log:22.04-5.9
-21
View File
@@ -1,21 +0,0 @@
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:
- 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
-37
View File
@@ -1,37 +0,0 @@
# this file is not designed to be run directly
# instead, use the docker-compose.<os>.<swift> files
# eg docker-compose -f docker/docker-compose.yaml -f docker/docker-compose.1804.50.yaml run test
version: "3"
services:
runtime-setup:
image: swift-log:default
build:
context: .
dockerfile: Dockerfile
common: &common
image: swift-log:default
depends_on: [runtime-setup]
volumes:
- ~/.ssh:/root/.ssh
- ..:/code:z
working_dir: /code
cap_drop:
- CAP_NET_RAW
- CAP_NET_BIND_SERVICE
soundness:
<<: *common
command: /bin/bash -xcl "./scripts/soundness.sh"
test:
<<: *common
command: /bin/bash -xcl "swift test $${WARN_AS_ERROR_ARG-} $${SANITIZER_ARG-} $${IMPORT_CHECK_ARG-} $${EXPLICIT_SENDABLE_ARG-} $${STRICT_CONCURRENCY_ARG-}"
# util
shell:
<<: *common
entrypoint: /bin/bash -l
-68
View File
@@ -1,68 +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-2020 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 >&2 "Usage: $0 REPO-GITHUB-URL NEW-VERSION OLD-VERSIONS..."
echo >&2
echo >&2 "This script requires a Swift 5.2+ toolchain."
echo >&2
echo >&2 "Examples:"
echo >&2
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"
}
if [[ $# -lt 3 ]]; then
usage
exit 1
fi
tmpdir=$(mktemp -d /tmp/.check-api_XXXXXX)
repo_url=$1
new_tag=$2
shift 2
repodir="$tmpdir/repo"
git clone "$repo_url" "$repodir"
git -C "$repodir" fetch -q origin '+refs/pull/*:refs/remotes/origin/pr/*'
cd "$repodir"
git checkout -q "$new_tag"
for old_tag in "$@"; do
echo "Checking public API breakages from $old_tag to $new_tag"
swift package diagnose-api-breaking-changes "$old_tag"
done
echo done
-39
View File
@@ -1,39 +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 -eu
here="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
contributors=$( cd "$here"/.. && git shortlog -es | cut -f2 | sed 's/^/- /' )
cat > "$here/../CONTRIBUTORS.txt" <<- EOF
For the purpose of tracking copyright, this is the list of individuals and
organizations who have contributed source code to the Swift Logging API.
For employees of an organization/company where the copyright of work done
by employees of that company is held by the company itself, only the company
needs to be listed here.
## COPYRIGHT HOLDERS
- Apple Inc. (all contributors with '@apple.com')
### Contributors
$contributors
**Updating this list**
Please do not edit this file manually. It is generated using \`./scripts/generate_contributors_list.sh\`. If a name is misspelled or appearing multiple times: add an entry in \`./.mailmap\`
EOF
-16
View File
@@ -1,16 +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
##
##===----------------------------------------------------------------------===##
swift package --disable-sandbox preview-documentation --target Logging
-157
View File
@@ -1,157 +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
##
##===----------------------------------------------------------------------===##
##===----------------------------------------------------------------------===##
##
## This source file is part of the SwiftNIO open source project
##
## Copyright (c) 2017-2019 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
here="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
function replace_acceptable_years() {
# this needs to replace all acceptable forms with 'YEARS'
sed -e 's/20[12][789012]-20[12][89012]/YEARS/' -e 's/20[12][89012]/YEARS/'
}
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 :).
unacceptable_terms=(
-e blacklis[t]
-e whitelis[t]
-e slav[e]
-e sanit[y]
)
if git grep --color=never -i "${unacceptable_terms[@]}" > /dev/null; then
printf "\033[0;31mUnacceptable language found.\033[0m\n"
git grep -i "${unacceptable_terms[@]}"
exit 1
fi
printf "\033[0;32mokay.\033[0m\n"
printf "=> Checking format... "
FIRST_OUT="$(git status --porcelain)"
swiftformat . > /dev/null 2>&1
SECOND_OUT="$(git status --porcelain)"
if [[ "$FIRST_OUT" != "$SECOND_OUT" ]]; then
printf "\033[0;31mformatting issues!\033[0m\n"
git --no-pager diff
exit 1
else
printf "\033[0;32mokay.\033[0m\n"
fi
printf "=> Checking license headers\n"
tmp=$(mktemp /tmp/.swift-log-soundness_XXXXXX)
for language in swift-or-c bash dtrace; do
printf " * $language... "
declare -a matching_files
declare -a exceptions
expections=( )
matching_files=( -name '*' )
case "$language" in
swift-or-c)
exceptions=( -name c_nio_http_parser.c -o -name c_nio_http_parser.h -o -name cpp_magic.h -o -name Package.swift -o -name CNIOSHA1.h -o -name c_nio_sha1.c -o -name ifaddrs-android.c -o -name ifaddrs-android.h)
matching_files=( -name '*.swift' -o -name '*.c' -o -name '*.h' )
cat > "$tmp" <<"EOF"
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Logging API open source project
//
// Copyright (c) YEARS 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
//
//===----------------------------------------------------------------------===//
EOF
;;
bash)
matching_files=( -name '*.sh' )
cat > "$tmp" <<"EOF"
#!/bin/bash
##===----------------------------------------------------------------------===##
##
## This source file is part of the Swift Logging API open source project
##
## Copyright (c) YEARS 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
##
##===----------------------------------------------------------------------===##
EOF
;;
dtrace)
matching_files=( -name '*.d' )
cat > "$tmp" <<"EOF"
#!/usr/sbin/dtrace -q -s
/*===----------------------------------------------------------------------===*
*
* This source file is part of the Swift Logging API open source project
*
* Copyright (c) YEARS 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
*
*===----------------------------------------------------------------------===*/
EOF
;;
*)
echo >&2 "ERROR: unknown language '$language'"
;;
esac
expected_lines=$(cat "$tmp" | wc -l)
expected_sha=$(cat "$tmp" | shasum)
(
cd "$here/.."
find . \
\( \! -path './.build/*' -a \
\( "${matching_files[@]}" \) -a \
\( \! \( "${exceptions[@]}" \) \) \) | while read line; do
if [[ "$(cat "$line" | replace_acceptable_years | head -n $expected_lines | shasum)" != "$expected_sha" ]]; then
printf "\033[0;31mmissing headers in file '$line'!\033[0m\n"
diff -u <(cat "$line" | replace_acceptable_years | head -n $expected_lines) "$tmp"
exit 1
fi
done
printf "\033[0;32mokay.\033[0m\n"
)
done
rm "$tmp"