Compare commits

...
9 Commits
Author SHA1 Message Date
Johannes Weiss eba9b323b5 only use shims on swift 4 (#70) 2019-04-26 18:49:53 +01:00
Johannes Weiss 2f65697362 [0.0] refer to docs on master branch. (#68) 2019-04-26 09:47:00 +09:00
tomer doron 9533e02d79 add docker compose setup for swift 4.0 (#47)
motivation: enable ci for swift 4.0 version

changes: add docker compose fil for swift 4.0, ubuntu 16.04
2019-04-15 11:21:15 +01:00
Johannes Weiss d1af77eebd Swift 4 support for a 0.x release
[contains work from @ianpartridge and @weissi]

Motivation:

For an easier migration path, it is probably useful to ship a `0.x`
version of `swift-log` that is compatible with Swift 4. It can't use
any of the features that Swift 5 brings and therefore the Swift 4
version will have a slightly reduced feature set:

- log messages will be `String`
- logging metadata values will be `String` only (no dictionaries,
  arrays, ...)

That means, if you use the Swift 4 version of swift-log carefully
(only use string literals), your migration to the Swift 5 version should
only be a matter of changing your `Package.swift`.

Modifications:

- remove all string interpolation and use `String` directly

Result:

- we can release a 0.x version that supports Swift 4

Support Swift 4.1 (#40)

* Support Swift 4.1

* Set swift-tools-version to 4.0
2019-04-12 15:24:21 +01:00
David Okun a4828d9184 Added CaseIterable to Logger.Level enum (#46)
* Added CaseIterable to Logger.Level enum
2019-04-12 14:49:25 +01:00
tomer doron 9a393a5d35 retain SwiftNIO copyright header (#44)
motivation: retain copyrights

changes:
* add notice file with references to derived work
* add swift-nio license header to lock
2019-04-11 14:12:41 +01:00
Johannes Weiss 3924b3b96e readme: fix log levels (#43) 2019-04-10 10:04:51 -07:00
tomer doron 23f0f6ee6e fix typo in API docs (#42)
motivation: better docs

changes: swidft-log -> SwiftLog in an API doc that got it wrong
2019-04-10 18:02:11 +01:00
tomer doron f6a420460d use consistent, swifty naming convention (#41)
motivation: prepare to release

changes: refer to package as SwiftLog across the board isntead of swift-log
2019-04-10 17:45:54 +01:00
14 changed files with 346 additions and 287 deletions

No files matched your search

+43
View File
@@ -0,0 +1,43 @@
The SwiftLog Project
========================
Please visit the SwiftLog web site for more information:
* https://github.com/apple/swift-log
Copyright 2018, 2019 The SwiftLog Project
The SwiftLog Project licenses this file to you under the Apache License,
version 2.0 (the "License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at:
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations
under the License.
Also, please refer to each LICENSE.<component>.txt file, which is located in
the 'license' directory of the distribution file, for the license terms of the
components that this product depends on.
-------------------------------------------------------------------------------
This product contains a derivation of the Tony Stone's 'process_test_files.rb'.
* LICENSE (Apache License 2.0):
* https://www.apache.org/licenses/LICENSE-2.0
* HOMEPAGE:
* https://codegists.com/snippet/ruby/generate_xctest_linux_runnerrb_tonystone_ruby
---
This product contains a derivation of SwiftNIO locks.
* LICENSE (Apache License 2.0):
* https://www.apache.org/licenses/LICENSE-2.0
* HOMEPAGE:
* https://github.com/apple/swift-nio
+1 -1
View File
@@ -1,4 +1,4 @@
// swift-tools-version:5.0
// swift-tools-version:4.0
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Logging API open source project
+2 -163
View File
@@ -1,164 +1,3 @@
# swift-log
# SwiftLog for Swift 4
A Logging API package for Swift. Version `1.0.0` requires Swift 5.0 but in due course we will also tag a mostly compatible version for Swift 4 (which will be tagged `0.x`) to ease your transition towards Swift 5.
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 `swift-log` itself, there's another huge gap at the moment: `swift-log` 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 `swift-log`-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.
What `swift-log` provides today can be found in the [API docs][api-docs].
## Great, what's the tl;dr
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
`swift-log` is designed for Swift 5, the `1.0.0` release requires Swift 5 (however we will soon tag a `0.x` version that will work with Swift 4 for the transition period). To depend on the logging API package, you need to declare your dependency in your `Package.swift`:
```swift
.package(url: "https://github.com/apple/swift-log.git", from: "1.0.0"),
```
and to your application/library target, add `"Logging"` to your `dependencies`, e.g. like this:
```swift
.target(name: "BestExampleApp", dependencies: ["Logging']),
```
#### 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")
// 3) we're now ready to use it
logger.info("Hello World!")
```
#### Output
```
2019-03-13T15:46:38+0000 info: Hello World!
```
For further information, please check the [API documentation][api-docs].
## 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 `swift-log` is a 'logging API package'. `swift-log` (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 `swift-log` 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 `swift-log`, 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, they match the [syslog severity levels](https://en.wikipedia.org/wiki/Syslog#Severity_level):
- `debug`
- `info`
- `notice`
- `warning`
- `error`
- `critical`
- `alert`
- `emergency`
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 `swift-log`. 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 `swift-log` consumers can use, you need to do two things: 1) Implement a type (usually a `struct`) that implements `LogHandler`, a protocol provided by `swift-log` and 2) instruct `swift-log` 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?, 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 `swift-log` 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.
## 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
Please refer to the documentation on the [master branch](https://github.com/apple/swift-log/blob/master/README.md).
+23 -6
View File
@@ -11,6 +11,21 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
import Darwin
#else
@@ -34,7 +49,11 @@ internal final class Lock {
deinit {
let err = pthread_mutex_destroy(self.mutex)
precondition(err == 0)
#if swift(>=4.0) && !swift(>=4.0.50)
self.mutex.deallocate(capacity: 1)
#else
self.mutex.deallocate()
#endif
}
/// Acquire the lock.
@@ -65,7 +84,6 @@ extension Lock {
///
/// - Parameter body: The block to execute while holding the lock.
/// - Returns: The value returned by the block.
@inlinable
internal func withLock<T>(_ body: () throws -> T) rethrows -> T {
self.lock()
defer {
@@ -75,7 +93,6 @@ extension Lock {
}
// specialise Void return (for performance)
@inlinable
internal func withLockVoid(_ body: () throws -> Void) rethrows {
try self.withLock(body)
}
@@ -98,7 +115,11 @@ internal final class ReadWriteLock {
deinit {
let err = pthread_rwlock_destroy(self.rwlock)
precondition(err == 0)
#if swift(>=4.0) && !swift(>=4.0.50)
self.rwlock.deallocate(capacity: 1)
#else
self.rwlock.deallocate()
#endif
}
/// Acquire a reader lock.
@@ -138,7 +159,6 @@ extension ReadWriteLock {
///
/// - Parameter body: The block to execute while holding the lock.
/// - Returns: The value returned by the block.
@inlinable
internal func withReaderLock<T>(_ body: () throws -> T) rethrows -> T {
self.lockRead()
defer {
@@ -155,7 +175,6 @@ extension ReadWriteLock {
///
/// - Parameter body: The block to execute while holding the lock.
/// - Returns: The value returned by the block.
@inlinable
internal func withWriterLock<T>(_ body: () throws -> T) rethrows -> T {
self.lockWrite()
defer {
@@ -165,13 +184,11 @@ extension ReadWriteLock {
}
// specialise Void return (for performance)
@inlinable
internal func withReaderLockVoid(_ body: () throws -> Void) rethrows {
try self.withReaderLock(body)
}
// specialise Void return (for performance)
@inlinable
internal func withWriterLockVoid(_ body: () throws -> Void) rethrows {
try self.withWriterLock(body)
}
+1 -1
View File
@@ -15,7 +15,7 @@
/// A `LogHandler` is an implementation of a logging backend.
///
/// This type is an implementation detail and should not normally be used, unless implementing your own logging backend.
/// To use the swift-log API, please refer to the documentation of `Logger`.
/// To use the SwiftLog API, please refer to the documentation of `Logger`.
///
/// # Implementation requirements
///
+183 -33
View File
@@ -18,7 +18,7 @@
import Glibc
#endif
/// A `Logger` is the central type in `swift-log`. Its central function is to emit log messages using one of the methods
/// 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.
///
/// The most basic usage of a `Logger` is
@@ -26,7 +26,6 @@
/// logger.info("Hello World!")
///
public struct Logger {
@usableFromInline
var handler: LogHandler
public let label: String
@@ -52,7 +51,6 @@ extension Logger {
/// it defaults to `#file`.
/// - 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,
@@ -65,11 +63,21 @@ extension Logger {
}
}
public func log(level: Logger.Level,
_ message: @autoclosure () -> String,
metadata: @autoclosure () -> [String: String]? = nil,
file: String = #file, function: String = #function, line: UInt = #line) {
self.log(level: level,
Logger.Message(stringLiteral: message()),
metadata: metadata().map { $0.mapValues { Logger.MetadataValue.string($0) } },
file: file, function: function, line: line)
}
/// Add, change, or remove a logging metadata item.
///
/// - note: Logging metadata behaves as a value that means a change to the logging metadata will only affect the
/// very `Logger` it was changed on.
@inlinable
public subscript(metadataKey metadataKey: String) -> Logger.Metadata.Value? {
get {
return self.handler[metadataKey: metadataKey]
@@ -85,7 +93,6 @@ extension Logger {
/// very `Logger`. It it acceptable for logging backends to have some form of global log level override
/// that affects multiple or even all loggers. This means a change in `logLevel` to one `Logger` might in
/// certain cases have no effect.
@inlinable
public var logLevel: Logger.Level {
get {
return self.handler.logLevel
@@ -112,13 +119,32 @@ extension Logger {
/// it defaults to `#file`.
/// - 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 = #file, function: String = #function, line: UInt = #line) {
self.log(level: .trace, message(), metadata: metadata(), file: file, function: function, line: line)
}
#if swift(>=4.1.50)
#if !compiler(>=5.0)
public func trace(_ message: @autoclosure () -> String,
metadata: @autoclosure () -> [String: String]? = nil,
file: String = #file, function: String = #function, line: UInt = #line) {
self.trace(Logger.Message(stringLiteral: message()),
metadata: metadata().map { $0.mapValues { Logger.MetadataValue.string($0) } },
file: file, function: function, line: line)
}
#endif
#else
public func trace(_ message: @autoclosure () -> String,
metadata: @autoclosure () -> [String: String]? = nil,
file: String = #file, function: String = #function, line: UInt = #line) {
self.trace(Logger.Message(stringLiteral: message()),
metadata: metadata().map { $0.mapValues { Logger.MetadataValue.string($0) } },
file: file, function: function, line: line)
}
#endif
/// Log a message passing with the `Logger.info` log level.
///
/// If `.debug` is at least as severe as the `Logger`'s `logLevel`, it will be logged,
@@ -134,13 +160,32 @@ extension Logger {
/// it defaults to `#file`.
/// - 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 = #file, function: String = #function, line: UInt = #line) {
self.log(level: .debug, message(), metadata: metadata(), file: file, function: function, line: line)
}
#if swift(>=4.1.50)
#if !compiler(>=5.0)
public func debug(_ message: @autoclosure () -> String,
metadata: @autoclosure () -> [String: String]? = nil,
file: String = #file, function: String = #function, line: UInt = #line) {
self.debug(Logger.Message(stringLiteral: message()),
metadata: metadata().map { $0.mapValues { Logger.MetadataValue.string($0) } },
file: file, function: function, line: line)
}
#endif
#else
public func debug(_ message: @autoclosure () -> String,
metadata: @autoclosure () -> [String: String]? = nil,
file: String = #file, function: String = #function, line: UInt = #line) {
self.debug(Logger.Message(stringLiteral: message()),
metadata: metadata().map { $0.mapValues { Logger.MetadataValue.string($0) } },
file: file, function: function, line: line)
}
#endif
/// Log a message passing with the `Logger.Level.info` log level.
///
/// If `.info` is at least as severe as the `Logger`'s `logLevel`, it will be logged,
@@ -156,13 +201,32 @@ extension Logger {
/// it defaults to `#file`.
/// - 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 = #file, function: String = #function, line: UInt = #line) {
self.log(level: .info, message(), metadata: metadata(), file: file, function: function, line: line)
}
#if swift(>=4.1.50)
#if !compiler(>=5.0)
public func info(_ message: @autoclosure () -> String,
metadata: @autoclosure () -> [String: String]? = nil,
file: String = #file, function: String = #function, line: UInt = #line) {
self.info(Logger.Message(stringLiteral: message()),
metadata: metadata().map { $0.mapValues { Logger.MetadataValue.string($0) } },
file: file, function: function, line: line)
}
#endif
#else
public func info(_ message: @autoclosure () -> String,
metadata: @autoclosure () -> [String: String]? = nil,
file: String = #file, function: String = #function, line: UInt = #line) {
self.info(Logger.Message(stringLiteral: message()),
metadata: metadata().map { $0.mapValues { Logger.MetadataValue.string($0) } },
file: file, function: function, line: line)
}
#endif
/// Log a message passing with the `Logger.Level.notice` log level.
///
/// If `.notice` is at least as severe as the `Logger`'s `logLevel`, it will be logged,
@@ -178,13 +242,32 @@ extension Logger {
/// it defaults to `#file`.
/// - 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 = #file, function: String = #function, line: UInt = #line) {
self.log(level: .notice, message(), metadata: metadata(), file: file, function: function, line: line)
}
#if swift(>=4.1.50)
#if !compiler(>=5.0)
public func notice(_ message: @autoclosure () -> String,
metadata: @autoclosure () -> [String: String]? = nil,
file: String = #file, function: String = #function, line: UInt = #line) {
self.notice(Logger.Message(stringLiteral: message()),
metadata: metadata().map { $0.mapValues { Logger.MetadataValue.string($0) } },
file: file, function: function, line: line)
}
#endif
#else
public func notice(_ message: @autoclosure () -> String,
metadata: @autoclosure () -> [String: String]? = nil,
file: String = #file, function: String = #function, line: UInt = #line) {
self.notice(Logger.Message(stringLiteral: message()),
metadata: metadata().map { $0.mapValues { Logger.MetadataValue.string($0) } },
file: file, function: function, line: line)
}
#endif
/// Log a message passing with the `Logger.Level.warning` log level.
///
/// If `.warning` is at least as severe as the `Logger`'s `logLevel`, it will be logged,
@@ -200,13 +283,32 @@ extension Logger {
/// it defaults to `#file`.
/// - 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 = #file, function: String = #function, line: UInt = #line) {
self.log(level: .warning, message(), metadata: metadata(), file: file, function: function, line: line)
}
#if swift(>=4.1.50)
#if !compiler(>=5.0)
public func warning(_ message: @autoclosure () -> String,
metadata: @autoclosure () -> [String: String]? = nil,
file: String = #file, function: String = #function, line: UInt = #line) {
self.warning(Logger.Message(stringLiteral: message()),
metadata: metadata().map { $0.mapValues { Logger.MetadataValue.string($0) } },
file: file, function: function, line: line)
}
#endif
#else
public func warning(_ message: @autoclosure () -> String,
metadata: @autoclosure () -> [String: String]? = nil,
file: String = #file, function: String = #function, line: UInt = #line) {
self.warning(Logger.Message(stringLiteral: message()),
metadata: metadata().map { $0.mapValues { Logger.MetadataValue.string($0) } },
file: file, function: function, line: line)
}
#endif
/// Log a message passing with the `Logger.Level.error` log level.
///
/// If `.error` is at least as severe as the `Logger`'s `logLevel`, it will be logged,
@@ -222,13 +324,32 @@ extension Logger {
/// it defaults to `#file`.
/// - 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 = #file, function: String = #function, line: UInt = #line) {
self.log(level: .error, message(), metadata: metadata(), file: file, function: function, line: line)
}
#if swift(>=4.1.50)
#if !compiler(>=5.0)
public func error(_ message: @autoclosure () -> String,
metadata: @autoclosure () -> [String: String]? = nil,
file: String = #file, function: String = #function, line: UInt = #line) {
self.error(Logger.Message(stringLiteral: message()),
metadata: metadata().map { $0.mapValues { Logger.MetadataValue.string($0) } },
file: file, function: function, line: line)
}
#endif
#else
public func error(_ message: @autoclosure () -> String,
metadata: @autoclosure () -> [String: String]? = nil,
file: String = #file, function: String = #function, line: UInt = #line) {
self.error(Logger.Message(stringLiteral: message()),
metadata: metadata().map { $0.mapValues { Logger.MetadataValue.string($0) } },
file: file, function: function, line: line)
}
#endif
/// Log a message passing with the `Logger.Level.critical` log level.
///
/// `.critical` messages will always be logged.
@@ -243,12 +364,31 @@ extension Logger {
/// it defaults to `#file`.
/// - 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 = #file, function: String = #function, line: UInt = #line) {
self.log(level: .critical, message(), metadata: metadata(), file: file, function: function, line: line)
}
#if swift(>=4.1.50)
#if !compiler(>=5.0)
public func critical(_ message: @autoclosure () -> String,
metadata: @autoclosure () -> [String: String]? = nil,
file: String = #file, function: String = #function, line: UInt = #line) {
self.critical(Logger.Message(stringLiteral: message()),
metadata: metadata().map { $0.mapValues { Logger.MetadataValue.string($0) } },
file: file, function: function, line: line)
}
#endif
#else
public func critical(_ message: @autoclosure () -> String,
metadata: @autoclosure () -> [String: String]? = nil,
file: String = #file, function: String = #function, line: UInt = #line) {
self.critical(Logger.Message(stringLiteral: message()),
metadata: metadata().map { $0.mapValues { Logger.MetadataValue.string($0) } },
file: file, function: function, line: line)
}
#endif
}
/// The `LoggingSystem` is a global facility where the default logging backend implementation (`LogHandler`) can be
@@ -422,10 +562,7 @@ extension Logger {
///
/// logger.info("Hello \(world)")
///
public struct Message: ExpressibleByStringLiteral,
Equatable,
CustomStringConvertible,
ExpressibleByStringInterpolation {
public struct Message: CustomStringConvertible {
public typealias StringLiteralType = String
private var value: String
@@ -440,6 +577,34 @@ extension Logger {
}
}
#if swift(>=4.1.50)
#if compiler(>=5.0)
extension Logger.Message: ExpressibleByStringLiteral,
ExpressibleByStringInterpolation {}
// Extension has to be done on explicit type rather than Logger.Metadata.Value as workaround for
// https://bugs.swift.org/browse/SR-9687
extension Logger.MetadataValue: ExpressibleByStringLiteral, ExpressibleByStringInterpolation {
public typealias StringLiteralType = String
public init(stringLiteral value: String) {
self = .string(value)
}
}
#endif
#endif
#if !swift(>=4.1.50)
extension Logger.Message: Equatable {
public static func == (lhs: Logger.Message, rhs: Logger.Message) -> Bool {
return lhs.value == rhs.value
}
}
#else
extension Logger.Message: Equatable {}
#endif
/// A pseudo-`LogHandler` that can be used to send messages to multiple other `LogHandler`s.
///
/// The first `LogHandler` passed to the initialisation function of `MultiplexLogHandler` control the `logLevel` as
@@ -564,23 +729,13 @@ internal struct StdoutLogHandler: LogHandler {
let localTime = localtime(&timestamp)
strftime(&buffer, buffer.count, "%Y-%m-%dT%H:%M:%S%z", localTime)
return buffer.withUnsafeBufferPointer {
$0.withMemoryRebound(to: CChar.self) {
String(cString: $0.baseAddress!)
$0.baseAddress!.withMemoryRebound(to: CChar.self, capacity: $0.count) { ptr in
String(cString: ptr)
}
}
}
}
// Extension has to be done on explicit type rather than Logger.Metadata.Value as workaround for
// https://bugs.swift.org/browse/SR-9687
extension Logger.MetadataValue: ExpressibleByStringLiteral {
public typealias StringLiteralType = String
public init(stringLiteral value: String) {
self = .string(value)
}
}
extension Logger.MetadataValue: CustomStringConvertible {
public var description: String {
switch self {
@@ -596,11 +751,6 @@ extension Logger.MetadataValue: CustomStringConvertible {
}
}
// Extension has to be done on explicit type rather than Logger.Metadata.Value as workaround for
// https://bugs.swift.org/browse/SR-9687
extension Logger.MetadataValue: ExpressibleByStringInterpolation {
}
// Extension has to be done on explicit type rather than Logger.Metadata.Value as workaround for
// https://bugs.swift.org/browse/SR-9687
extension Logger.MetadataValue: ExpressibleByDictionaryLiteral {
+6 -3
View File
@@ -11,9 +11,12 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
@testable import Logging
import Dispatch
import XCTest
@testable import Logging
class GlobalLoggerTest: XCTestCase {
func test1() throws {
// bootstrap with our test logging impl
@@ -142,7 +145,7 @@ private struct Struct3 {
}
private func doSomethingElse() {
MDC.global["foo"] = "bar"
MDC.global["foo"] = .string("bar")
self.logger.error("Struct3::doSomethingElse")
let group = DispatchGroup()
group.enter()
@@ -161,7 +164,7 @@ private struct Struct3 {
MDC.global["foo"] = nil
// only effects the logger instance
var l = logger
l[metadataKey: "baz"] = "qux"
l[metadataKey: "baz"] = .string("qux")
l.debug("Struct3::doSomethingElse::Local")
logger.debug("Struct3::doSomethingElse::end")
}
+7 -4
View File
@@ -11,9 +11,12 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
@testable import Logging
import Dispatch
import XCTest
@testable import Logging
class LocalLoggerTest: XCTestCase {
func test1() throws {
// bootstrap with our test logging impl
@@ -65,8 +68,8 @@ class LocalLoggerTest: XCTestCase {
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: "Struct3::doSomething::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
}
@@ -129,7 +132,7 @@ private struct Struct3 {
func doSomething(context: Context) {
var c = context
c["bar"] = "baz" // only effects from this point on
c["bar"] = .string("baz") // only effects from this point on
c.logger.error("Struct3::doSomething")
doSomethingElse(context: c)
c.logger.debug("Struct3::doSomething::end")
@@ -150,7 +153,7 @@ private struct Struct3 {
group.wait()
// only effects the logger instance
var l = context.logger
l[metadataKey: "baz"] = "qux"
l[metadataKey: "baz"] = .string("qux")
l.debug("Struct3::doSomethingElse::Local")
context.logger.debug("Struct3::doSomethingElse::end")
}
@@ -28,9 +28,6 @@ extension LoggingTest {
return [
("testAutoclosure", testAutoclosure),
("testMultiplex", testMultiplex),
("testDictionaryMetadata", testDictionaryMetadata),
("testListMetadata", testListMetadata),
("testStringConvertibleMetadata", testStringConvertibleMetadata),
("testAutoClosuresAreNotForcedUnlessNeeded", testAutoClosuresAreNotForcedUnlessNeeded),
("testLocalMetadata", testLocalMetadata),
("testCustomFactory", testCustomFactory),
+50 -61
View File
@@ -22,10 +22,12 @@ class LoggingTest: XCTestCase {
var logger = Logger(label: "test")
logger.logLevel = .info
logger.log(level: .debug, {
logger.log(level: .debug, { () -> String in
XCTFail("trace should not be called")
return "trace"
}())
#if swift(>=4.1.50)
#if compiler(>=5.0)
logger.debug({
XCTFail("trace should not be called")
return "trace"
@@ -34,6 +36,26 @@ class LoggingTest: XCTestCase {
XCTFail("debug should not be called")
return "debug"
}())
#else
logger.debug({ () -> String in
XCTFail("trace should not be called")
return "trace"
}())
logger.debug({ () -> String in
XCTFail("debug should not be called")
return "debug"
}())
#endif
#else
logger.debug({ () -> String in
XCTFail("trace should not be called")
return "trace"
}())
logger.debug({ () -> String in
XCTFail("debug should not be called")
return "debug"
}())
#endif
logger.info({
"info"
}())
@@ -60,7 +82,7 @@ class LoggingTest: XCTestCase {
var logger = Logger(label: "test")
logger.logLevel = .warning
logger.info("hello world?")
logger[metadataKey: "foo"] = "bar"
logger[metadataKey: "foo"] = .string("bar")
logger.warning("hello world!")
logging1.history.assertNotExist(level: .info, message: "hello world?")
logging2.history.assertNotExist(level: .info, message: "hello world?")
@@ -72,38 +94,6 @@ class LoggingTest: XCTestCase {
case boom
}
func testDictionaryMetadata() {
let testLogging = TestLogging()
LoggingSystem.bootstrapInternal(testLogging.make)
var logger = Logger(label: "\(#function)")
logger[metadataKey: "foo"] = ["bar": "buz"]
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"]]]])
}
func testListMetadata() {
let testLogging = TestLogging()
LoggingSystem.bootstrapInternal(testLogging.make)
var logger = Logger(label: "\(#function)")
logger[metadataKey: "foo"] = ["bar", "buz"]
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"]]])
}
// Example of custom "box" which may be used to implement "render at most once" semantics
// Not thread-safe, thus should not be shared across threads.
internal class LazyMetadataBox: CustomStringConvertible {
@@ -131,25 +121,24 @@ class LoggingTest: XCTestCase {
}
}
func testStringConvertibleMetadata() {
let testLogging = TestLogging()
LoggingSystem.bootstrapInternal(testLogging.make)
var logger = Logger(label: "\(#function)")
logger[metadataKey: "foo"] = .stringConvertible("raw-string")
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" }))])
}
#if swift(>=4.1.50)
#if compiler(>=5.0)
private func dontEvaluateThisString(file: StaticString = #file, line: UInt = #line) -> Logger.Message {
XCTFail("should not have been evaluated", file: file, line: line)
return "should not have been evaluated"
}
#else
private func dontEvaluateThisString(file: StaticString = #file, line: UInt = #line) -> String {
XCTFail("should not have been evaluated", file: file, line: line)
return "should not have been evaluated"
}
#endif
#else
private func dontEvaluateThisString(file: StaticString = #file, line: UInt = #line) -> String {
XCTFail("should not have been evaluated", file: file, line: line)
return "should not have been evaluated"
}
#endif
func testAutoClosuresAreNotForcedUnlessNeeded() {
let testLogging = TestLogging()
@@ -171,8 +160,8 @@ class LoggingTest: XCTestCase {
var logger = Logger(label: "\(#function)")
logger.info("hello world!", metadata: ["foo": "bar"])
logger[metadataKey: "bar"] = "baz"
logger[metadataKey: "baz"] = "qux"
logger[metadataKey: "bar"] = .string("baz")
logger[metadataKey: "baz"] = .string("qux")
logger.warning("hello world!")
logger.error("hello world!", metadata: ["baz": "quc"])
testLogging.history.assertExist(level: .info, message: "hello world!", metadata: ["foo": "bar"])
@@ -261,7 +250,7 @@ class LoggingTest: XCTestCase {
var logger = Logger(label: "\(#function)")
logger.logLevel = .debug
let someInt = Int.random(in: 23..<42)
let someInt = 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)
@@ -292,17 +281,17 @@ class LoggingTest: XCTestCase {
var logger1: Logger = {
var logger = Logger(label: "foo")
logger.logLevel = .debug
logger[metadataKey: "only-on"] = "first"
logger[metadataKey: "only-on"] = .string("first")
return logger
}()
XCTAssertEqual(.debug, logger1.logLevel)
var logger2 = logger1
logger2.logLevel = .error
logger2[metadataKey: "only-on"] = "second"
logger2[metadataKey: "only-on"] = .string("second")
XCTAssertEqual(.error, logger2.logLevel)
XCTAssertEqual(.debug, logger1.logLevel)
XCTAssertEqual("first", logger1[metadataKey: "only-on"])
XCTAssertEqual("second", logger2[metadataKey: "only-on"])
XCTAssertEqual(.string("first"), logger1[metadataKey: "only-on"])
XCTAssertEqual(.string("second"), logger2[metadataKey: "only-on"])
logger1.error("hey")
}
@@ -367,13 +356,13 @@ class LoggingTest: XCTestCase {
var logger1 = Logger(label: "logger-\(#file):\(#line)")
var logger2 = logger1
logger1.logLevel = .warning
logger1[metadataKey: "only-on"] = "first"
logger1[metadataKey: "only-on"] = .string("first")
logger2.logLevel = .error
logger2[metadataKey: "only-on"] = "second"
logger2[metadataKey: "only-on"] = .string("second")
XCTAssertEqual(.error, logger2.logLevel)
XCTAssertEqual(.warning, logger1.logLevel)
XCTAssertEqual("first", logger1[metadataKey: "only-on"])
XCTAssertEqual("second", logger2[metadataKey: "only-on"])
XCTAssertEqual(Logger.MetadataValue.string("first"), logger1[metadataKey: "only-on"])
XCTAssertEqual(Logger.MetadataValue.string("second"), logger2[metadataKey: "only-on"])
logger1.notice("logger1, before")
logger2.notice("logger2, before")
@@ -388,7 +377,7 @@ class LoggingTest: XCTestCase {
logRecorder.assertExist(level: .notice, message: "logger1, after")
logRecorder.assertExist(level: .notice, message: "logger2, after")
}
func testLogLevelOrdering() {
XCTAssertLessThan(Logger.Level.trace, Logger.Level.debug)
XCTAssertLessThan(Logger.Level.trace, Logger.Level.info)
+5 -5
View File
@@ -22,15 +22,15 @@ class MDCTest: XCTestCase {
LoggingSystem.bootstrapInternal(logging.make)
// run the program
MDC.global["foo"] = "bar"
MDC.global["foo"] = .string("bar")
let group = DispatchGroup()
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)
let add = 999
let remove = 123
for i in 0 ... add {
MDC.global["key-\(i)"] = "value-\(i)"
MDC.global["key-\(i)"] = .string("value-\(i)")
}
for i in 0 ... remove {
MDC.global["key-\(i)"] = nil
@@ -47,7 +47,7 @@ class MDCTest: XCTestCase {
}
}
group.wait()
XCTAssertEqual(MDC.global["foo"], "bar", "expecting to find top items")
XCTAssertEqual(MDC.global["foo"], .string("bar"), "expecting to find top items")
MDC.global["foo"] = nil
XCTAssertTrue(MDC.global.metadata.isEmpty, "MDC should be empty")
}
+8 -3
View File
@@ -11,10 +11,13 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Dispatch
import Foundation
@testable import Logging
import XCTest
@testable import Logging
internal struct TestLogging {
private let _config = Config() // shared among loggers
private let recorder = Recorder() // shared among loggers
@@ -173,12 +176,14 @@ internal struct LogEntry {
}
extension History {
func assertExist(level: Logger.Level, message: String, metadata: Logger.Metadata? = nil, file: StaticString = #file, line: UInt = #line) {
func assertExist(level: Logger.Level, message: String, metadata: [String: String]? = nil, file: StaticString = #file, line: UInt = #line) {
let metadata = metadata.map { $0.mapValues { Logger.MetadataValue.string($0) } }
let entry = self.find(level: level, message: message, metadata: metadata)
XCTAssertNotNil(entry, "entry not found: \(level), \(String(describing: metadata)), \(message) ", file: file, line: line)
}
func assertNotExist(level: Logger.Level, message: String, metadata: Logger.Metadata? = nil, file: StaticString = #file, line: UInt = #line) {
func assertNotExist(level: Logger.Level, message: String, metadata: [String: String]? = nil, file: StaticString = #file, line: UInt = #line) {
let metadata = metadata.map { $0.mapValues { Logger.MetadataValue.string($0) } }
let entry = self.find(level: level, message: message, metadata: metadata)
XCTAssertNil(entry, "entry was found: \(level), \(String(describing: metadata)), \(message)", file: file, line: line)
}
+13
View File
@@ -0,0 +1,13 @@
version: "3"
services:
runtime-setup:
image: swift-log:16.04-4.0
build:
args:
ubuntu_version: "16.04"
swift_version: "4.0"
test:
image: swift-log:16.04-4.0
+4 -4
View File
@@ -53,18 +53,18 @@ if ! command -v jazzy > /dev/null; then
fi
module_switcher="docs/$version/README.md"
jazzy_args=(--clean
--author 'swift-log team'
--author 'SwiftLog team'
--readme "$module_switcher"
--author_url https://github.com/apple/swift-log
--github_url https://github.com/apple/swift-log
--theme fullwidth
--xcodebuild-arguments -scheme,swift-log-Package)
cat > "$module_switcher" <<"EOF"
# swift-log Docs
# SwiftLog Docs
swift-log is a Swift 5 logging API package.
SwiftLog is a Swift logging API package.
To get started with swift-log, [`import Logging`](../Logging/index.html). The
To get started with SwiftLog, [`import Logging`](../Logging/index.html). The
most important type is [`Logger`](https://apple.github.io/swift-log/docs/current/Logging/Structs/Logger.html)
which you can use to emit log messages.