mirror of
https://github.com/apple/swift-log
synced 2026-11-22 03:40:39 +00:00
Compare commits
27
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f1a88bda3e | ||
|
|
87c2553da2 | ||
|
|
c08d7f72b9 | ||
|
|
da2c8aa854 | ||
|
|
fa15ddefc4 | ||
|
|
8ede07bf98 | ||
|
|
0e21dd7893 | ||
|
|
4d7ef13e01 | ||
|
|
4aad45c1c1 | ||
|
|
1b5f8a5034 | ||
|
|
01ce2959de | ||
|
|
57d2a6d872 | ||
|
|
7b01660491 | ||
|
|
27da3424c7 | ||
|
|
3a9a783347 | ||
|
|
b321ca1807 | ||
|
|
068014614c | ||
|
|
012cff81f6 | ||
|
|
f0f77b00c4 | ||
|
|
74d7b91cee | ||
|
|
77b2e836f1 | ||
|
|
1111d309a5 | ||
|
|
e5a4bd1003 | ||
|
|
fd6c6b338d | ||
|
|
6669bdf615 | ||
|
|
6171b4483e | ||
|
|
2b7d68a486 |
No files matched your search
@@ -4,6 +4,9 @@
|
||||
/*.xcodeproj
|
||||
.xcode
|
||||
DerivedData
|
||||
.swiftpm
|
||||
|
||||
.SourceKitten/
|
||||
docs/
|
||||
|
||||
.*.sw?
|
||||
+1
-1
@@ -1,5 +1,6 @@
|
||||
# file options
|
||||
|
||||
--swiftversion 5.0
|
||||
--exclude .build
|
||||
|
||||
# format options
|
||||
@@ -7,7 +8,6 @@
|
||||
--self insert
|
||||
--patternlet inline
|
||||
--stripunusedargs unnamed-only
|
||||
--comments ignore
|
||||
--ifdef no-indent
|
||||
|
||||
# rules
|
||||
+1
-1
@@ -49,7 +49,7 @@ of an incident.
|
||||
*This policy is adapted from the Contributor Code of Conduct [version 1.3.0](https://contributor-covenant.org/version/1/3/0/).*
|
||||
|
||||
### Reporting
|
||||
A working group of community members is committed to promptly addressing any [reported issues](mailto:swift-log-conduct@group.apple.com).
|
||||
A working group of community members is committed to promptly addressing any [reported issues](mailto:swift-server-conduct@group.apple.com).
|
||||
Working group members are volunteers appointed by the project lead, with a
|
||||
preference for individuals with varied backgrounds and perspectives. Membership is expected
|
||||
to change regularly, and may grow or shrink.
|
||||
@@ -46,7 +46,7 @@ logger.info("Hello World!")
|
||||
#### 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)
|
||||
```
|
||||
|
||||
@@ -54,14 +54,24 @@ LoggingSystem.bootstrap(StreamLogHandler.standardError)
|
||||
|
||||
For further information, please check the [API documentation][api-docs].
|
||||
|
||||
<a name="backends"></a>
|
||||
#### Selecting a logging backend implementation (applications only)
|
||||
|
||||
As the API has just launched, not many implementations exist yet. If you are interested in implementing one see the "Implementation considerations" section below explaining how to do so. List of existing SwiftLog API compatible libraries:
|
||||
|
||||
- [IBM-Swift/HeliumLogger](https://github.com/IBM-Swift/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
|
||||
- Your library? [Get in touch!](https://forums.swift.org/c/server)
|
||||
| Repository | Handler Description|
|
||||
| ----------- | ----------- |
|
||||
| [IBM-Swift/HeliumLogger](https://github.com/IBM-Swift/HeliumLogger) |a logging backend widely used in the Kitura ecosystem |
|
||||
| [ianpartridge/swift-log-**syslog**](https://github.com/ianpartridge/swift-log-syslog) | a [syslog](https://en.wikipedia.org/wiki/Syslog) backend|
|
||||
| [Adorkable/swift-log-**format-and-pipe**](https://github.com/Adorkable/swift-log-format-and-pipe) | a backend that allows customization of the output format and the resulting destination |
|
||||
| [chrisaljoudi/swift-log-**oslog**](https://github.com/chrisaljoudi/swift-log-oslog) | an OSLog [Unified Logging](https://developer.apple.com/documentation/os/logging) backend for use on Apple platforms. **Important Note:** we recommend using os_log directly as decribed [here](https://developer.apple.com/documentation/os/logging). Using os_log through swift-log using this backend will be less efficient and will also prevent specifying the privacy of the message. The backend always uses `%{public}@` as the format string and eagerly converts all string interpolations to strings. This has two drawbacks: 1. the static components of the string interpolation would be eagerly copied by the unified logging system, which will result in loss of performance. 2. It makes all messages public, which changes the default privacy policy of os_log, and doesn't allow specifying fine-grained privacy of sections of the message. In a separate on-going work, Swift APIs for os_log are being improved and made to align closely with swift-log APIs. References: [Unifying Logging Levels](https://forums.swift.org/t/custom-string-interpolation-and-compile-time-interpretation-applied-to-logging/18799), [Making os_log accept string interpolations using compile-time interpretation](https://forums.swift.org/t/logging-levels-for-swifts-server-side-logging-apis-and-new-os-log-apis/20365). |
|
||||
| [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) |
|
||||
| [vapor/console-kit](https://github.com/vapor/console-kit/) | print log messages to a terminal with stylized ([ANSI](https://en.wikipedia.org/wiki/ANSI_escape_code)) output |
|
||||
| [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)) |
|
||||
| Your library? | [Get in touch!](https://forums.swift.org/c/server) |
|
||||
|
||||
## What is an API package?
|
||||
|
||||
@@ -190,16 +200,22 @@ In most cases, there is only one thing you need to remember: Always use _string
|
||||
|
||||
Good:
|
||||
|
||||
logger.info("hello world")
|
||||
```swift
|
||||
logger.info("hello world")
|
||||
```
|
||||
|
||||
Bad:
|
||||
|
||||
let message = "hello world"
|
||||
logger.info(message)
|
||||
```swift
|
||||
let message = "hello world"
|
||||
logger.info(message)
|
||||
```
|
||||
|
||||
If you have a `String` that you received from elsewhere, please use
|
||||
|
||||
logger.info("\(stringIAlreadyHave)")
|
||||
```swift
|
||||
logger.info("\(stringIAlreadyHave)")
|
||||
```
|
||||
|
||||
For more details, have a look in the next section.
|
||||
|
||||
@@ -221,8 +237,10 @@ Swift 4.0 & 4.1 don't support `@inlinable`, so SwiftLog 0 can't use them.
|
||||
Because all Swift 4 versions don't have a (non-deprecated) mechanism for a type to be `ExpressibleByStringInterpolation` we couldn't make `Logger.Message` expressible by string literals. Unfortunately, the most basic form of our logging API is `logger.info("Hello \(world)")`. For this to work however, `"Hello \(world)"` needs to be accepted and because we can't make `Logger.Message` `ExpressibleByStringInterpolation` we added an overload for all the logging methods to also accept `String`. In most cases, you won't even notice that with SwiftLog 0 you're creating a `String` (which is then transformed to a `Logger.Message`) and with SwiftLog 1 you're creating a `Logger.Message` directly. That is because both `String` and `Logger.Message` will accept all forms of string literals and string interpolations.
|
||||
Unfortunately, there is code that will make this seemingly small difference visible. If you write
|
||||
|
||||
let message = "Hello world"
|
||||
logger.info(message)
|
||||
```swift
|
||||
let message = "Hello world"
|
||||
logger.info(message)
|
||||
```
|
||||
|
||||
then this will only work in SwiftLog 0 and not in SwiftLog 1. Why? Because SwiftLog 1 will want a `Logger.Message` but `let message = "Hello world"` will make `message` to be of type `String` and in SwiftLog 1, the logging methods don't accept `String`s.
|
||||
|
||||
@@ -230,8 +248,10 @@ So if you intend to be compatible with SwiftLog 0 and 1 at the same time, please
|
||||
|
||||
In the case that you already have a `String` handy that you want to log, don't worry at all, just use
|
||||
|
||||
let message = "Hello world"
|
||||
logger.info("\(message)")
|
||||
```swift
|
||||
let message = "Hello world"
|
||||
logger.info("\(message)")
|
||||
```
|
||||
|
||||
and again, you will be okay with SwiftLog 0 and 1.
|
||||
|
||||
|
||||
@@ -28,6 +28,8 @@
|
||||
|
||||
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
|
||||
import Darwin
|
||||
#elseif os(Windows)
|
||||
import WinSDK
|
||||
#else
|
||||
import Glibc
|
||||
#endif
|
||||
@@ -38,17 +40,31 @@ import Glibc
|
||||
/// of lock is safe to use with `libpthread`-based threading models, such as the
|
||||
/// one used by NIO.
|
||||
internal final class Lock {
|
||||
fileprivate let mutex: UnsafeMutablePointer<pthread_mutex_t> = UnsafeMutablePointer.allocate(capacity: 1)
|
||||
#if os(Windows)
|
||||
fileprivate let mutex: UnsafeMutablePointer<SRWLOCK> =
|
||||
UnsafeMutablePointer.allocate(capacity: 1)
|
||||
#else
|
||||
fileprivate let mutex: UnsafeMutablePointer<pthread_mutex_t> =
|
||||
UnsafeMutablePointer.allocate(capacity: 1)
|
||||
#endif
|
||||
|
||||
/// Create a new lock.
|
||||
public init() {
|
||||
#if os(Windows)
|
||||
InitializeSRWLock(self.mutex)
|
||||
#else
|
||||
let err = pthread_mutex_init(self.mutex, nil)
|
||||
precondition(err == 0)
|
||||
#endif
|
||||
}
|
||||
|
||||
deinit {
|
||||
#if os(Windows)
|
||||
// SRWLOCK does not need to be free'd
|
||||
#else
|
||||
let err = pthread_mutex_destroy(self.mutex)
|
||||
precondition(err == 0)
|
||||
#endif
|
||||
self.mutex.deallocate()
|
||||
}
|
||||
|
||||
@@ -57,8 +73,12 @@ internal final class Lock {
|
||||
/// Whenever possible, consider using `withLock` instead of this method and
|
||||
/// `unlock`, to simplify lock handling.
|
||||
public func lock() {
|
||||
#if os(Windows)
|
||||
AcquireSRWLockExclusive(self.mutex)
|
||||
#else
|
||||
let err = pthread_mutex_lock(self.mutex)
|
||||
precondition(err == 0)
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Release the lock.
|
||||
@@ -66,8 +86,12 @@ internal final class Lock {
|
||||
/// Whenever possible, consider using `withLock` instead of this method and
|
||||
/// `lock`, to simplify lock handling.
|
||||
public func unlock() {
|
||||
#if os(Windows)
|
||||
ReleaseSRWLockExclusive(self.mutex)
|
||||
#else
|
||||
let err = pthread_mutex_unlock(self.mutex)
|
||||
precondition(err == 0)
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
@@ -102,17 +126,32 @@ extension Lock {
|
||||
/// of lock is safe to use with `libpthread`-based threading models, such as the
|
||||
/// one used by NIO.
|
||||
internal final class ReadWriteLock {
|
||||
fileprivate let rwlock: UnsafeMutablePointer<pthread_rwlock_t> = UnsafeMutablePointer.allocate(capacity: 1)
|
||||
#if os(Windows)
|
||||
fileprivate let rwlock: UnsafeMutablePointer<SRWLOCK> =
|
||||
UnsafeMutablePointer.allocate(capacity: 1)
|
||||
fileprivate var shared: Bool = true
|
||||
#else
|
||||
fileprivate let rwlock: UnsafeMutablePointer<pthread_rwlock_t> =
|
||||
UnsafeMutablePointer.allocate(capacity: 1)
|
||||
#endif
|
||||
|
||||
/// Create a new lock.
|
||||
public init() {
|
||||
#if os(Windows)
|
||||
InitializeSRWLock(self.rwlock)
|
||||
#else
|
||||
let err = pthread_rwlock_init(self.rwlock, nil)
|
||||
precondition(err == 0)
|
||||
#endif
|
||||
}
|
||||
|
||||
deinit {
|
||||
#if os(Windows)
|
||||
// SRWLOCK does not need to be free'd
|
||||
#else
|
||||
let err = pthread_rwlock_destroy(self.rwlock)
|
||||
precondition(err == 0)
|
||||
#endif
|
||||
self.rwlock.deallocate()
|
||||
}
|
||||
|
||||
@@ -121,8 +160,13 @@ internal final class ReadWriteLock {
|
||||
/// Whenever possible, consider using `withLock` instead of this method and
|
||||
/// `unlock`, to simplify lock handling.
|
||||
public func lockRead() {
|
||||
#if os(Windows)
|
||||
AcquireSRWLockShared(self.rwlock)
|
||||
self.shared = true
|
||||
#else
|
||||
let err = pthread_rwlock_rdlock(self.rwlock)
|
||||
precondition(err == 0)
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Acquire a writer lock.
|
||||
@@ -130,8 +174,13 @@ internal final class ReadWriteLock {
|
||||
/// Whenever possible, consider using `withLock` instead of this method and
|
||||
/// `unlock`, to simplify lock handling.
|
||||
public func lockWrite() {
|
||||
#if os(Windows)
|
||||
AcquireSRWLockExclusive(self.rwlock)
|
||||
self.shared = true
|
||||
#else
|
||||
let err = pthread_rwlock_wrlock(self.rwlock)
|
||||
precondition(err == 0)
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Release the lock.
|
||||
@@ -139,8 +188,16 @@ internal final class ReadWriteLock {
|
||||
/// Whenever possible, consider using `withLock` instead of this method and
|
||||
/// `lock`, to simplify lock handling.
|
||||
public func unlock() {
|
||||
#if os(Windows)
|
||||
if self.shared {
|
||||
ReleaseSRWLockShared(self.rwlock)
|
||||
} else {
|
||||
ReleaseSRWLockExclusive(self.rwlock)
|
||||
}
|
||||
#else
|
||||
let err = pthread_rwlock_unlock(self.rwlock)
|
||||
precondition(err == 0)
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,8 @@
|
||||
|
||||
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
|
||||
import Darwin
|
||||
#elseif os(Windows)
|
||||
import MSVCRT
|
||||
#else
|
||||
import Glibc
|
||||
#endif
|
||||
@@ -105,7 +107,6 @@ extension Logger {
|
||||
/// otherwise nothing will happen.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - level: The log level to log `message` at. For the available log levels, see `Logger.Level`.
|
||||
/// - message: The message to be logged. `message` can be used with any string interpolation literal.
|
||||
/// - metadata: One-off metadata to attach to this log message
|
||||
/// - file: The file this log message originates from (there's usually no need to pass it explicitly as it
|
||||
@@ -127,7 +128,6 @@ extension Logger {
|
||||
/// otherwise nothing will happen.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - level: The log level to log `message` at. For the available log levels, see `Logger.Level`.
|
||||
/// - message: The message to be logged. `message` can be used with any string interpolation literal.
|
||||
/// - metadata: One-off metadata to attach to this log message
|
||||
/// - file: The file this log message originates from (there's usually no need to pass it explicitly as it
|
||||
@@ -149,7 +149,6 @@ extension Logger {
|
||||
/// otherwise nothing will happen.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - level: The log level to log `message` at. For the available log levels, see `Logger.Level`.
|
||||
/// - message: The message to be logged. `message` can be used with any string interpolation literal.
|
||||
/// - metadata: One-off metadata to attach to this log message
|
||||
/// - file: The file this log message originates from (there's usually no need to pass it explicitly as it
|
||||
@@ -171,7 +170,6 @@ extension Logger {
|
||||
/// otherwise nothing will happen.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - level: The log level to log `message` at. For the available log levels, see `Logger.Level`.
|
||||
/// - message: The message to be logged. `message` can be used with any string interpolation literal.
|
||||
/// - metadata: One-off metadata to attach to this log message
|
||||
/// - file: The file this log message originates from (there's usually no need to pass it explicitly as it
|
||||
@@ -193,7 +191,6 @@ extension Logger {
|
||||
/// otherwise nothing will happen.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - level: The log level to log `message` at. For the available log levels, see `Logger.Level`.
|
||||
/// - message: The message to be logged. `message` can be used with any string interpolation literal.
|
||||
/// - metadata: One-off metadata to attach to this log message
|
||||
/// - file: The file this log message originates from (there's usually no need to pass it explicitly as it
|
||||
@@ -215,7 +212,6 @@ extension Logger {
|
||||
/// otherwise nothing will happen.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - level: The log level to log `message` at. For the available log levels, see `Logger.Level`.
|
||||
/// - message: The message to be logged. `message` can be used with any string interpolation literal.
|
||||
/// - metadata: One-off metadata to attach to this log message
|
||||
/// - file: The file this log message originates from (there's usually no need to pass it explicitly as it
|
||||
@@ -236,7 +232,6 @@ extension Logger {
|
||||
/// `.critical` messages will always be logged.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - level: The log level to log `message` at. For the available log levels, see `Logger.Level`.
|
||||
/// - message: The message to be logged. `message` can be used with any string interpolation literal.
|
||||
/// - metadata: One-off metadata to attach to this log message
|
||||
/// - file: The file this log message originates from (there's usually no need to pass it explicitly as it
|
||||
@@ -327,8 +322,9 @@ extension Logger {
|
||||
///
|
||||
/// Log levels are ordered by their severity, with `.trace` being the least severe and
|
||||
/// `.critical` being the most severe.
|
||||
public enum Level: CaseIterable {
|
||||
/// Appropriate for messages that contain information only when debugging a program.
|
||||
public enum Level: String, Codable, CaseIterable {
|
||||
/// Appropriate for messages that contain information normally of use only when
|
||||
/// tracing the execution of a program.
|
||||
case trace
|
||||
|
||||
/// Appropriate for messages that contain information normally of use only when
|
||||
@@ -445,10 +441,7 @@ 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
|
||||
@@ -535,9 +528,17 @@ internal struct StdioOutputStream: TextOutputStream {
|
||||
|
||||
internal func write(_ string: String) {
|
||||
string.withCString { ptr in
|
||||
#if os(Windows)
|
||||
_lock_file(self.file)
|
||||
#else
|
||||
flockfile(self.file)
|
||||
#endif
|
||||
defer {
|
||||
#if os(Windows)
|
||||
_unlock_file(self.file)
|
||||
#else
|
||||
funlockfile(self.file)
|
||||
#endif
|
||||
}
|
||||
_ = fputs(ptr, self.file)
|
||||
if case .always = self.flushMode {
|
||||
@@ -566,6 +567,9 @@ internal struct StdioOutputStream: TextOutputStream {
|
||||
#if os(macOS) || os(tvOS) || os(iOS) || os(watchOS)
|
||||
let systemStderr = Darwin.stderr
|
||||
let systemStdout = Darwin.stdout
|
||||
#elseif os(Windows)
|
||||
let systemStderr = MSVCRT.stderr
|
||||
let systemStdout = MSVCRT.stdout
|
||||
#else
|
||||
let systemStderr = Glibc.stderr!
|
||||
let systemStdout = Glibc.stdout!
|
||||
@@ -585,6 +589,7 @@ public struct StreamLogHandler: LogHandler {
|
||||
}
|
||||
|
||||
private let stream: TextOutputStream
|
||||
private let label: String
|
||||
|
||||
public var logLevel: Logger.Level = .info
|
||||
|
||||
@@ -606,6 +611,7 @@ public struct StreamLogHandler: LogHandler {
|
||||
|
||||
// internal for testing only
|
||||
internal init(label: String, stream: TextOutputStream) {
|
||||
self.label = label
|
||||
self.stream = stream
|
||||
}
|
||||
|
||||
@@ -618,7 +624,7 @@ public struct StreamLogHandler: LogHandler {
|
||||
: self.prettify(self.metadata.merging(metadata!, uniquingKeysWith: { _, new in new }))
|
||||
|
||||
var stream = self.stream
|
||||
stream.write("\(self.timestamp()) \(level):\(prettyMetadata.map { " \($0)" } ?? "") \(message)\n")
|
||||
stream.write("\(self.timestamp()) \(level) \(self.label) :\(prettyMetadata.map { " \($0)" } ?? "") \(message)\n")
|
||||
}
|
||||
|
||||
private func prettify(_ metadata: Logger.Metadata) -> String? {
|
||||
|
||||
@@ -42,7 +42,10 @@ extension LoggingTest {
|
||||
("testLogLevelCases", testLogLevelCases),
|
||||
("testLogLevelOrdering", testLogLevelOrdering),
|
||||
("testStreamLogHandlerWritesToAStream", testStreamLogHandlerWritesToAStream),
|
||||
("testStreamLogHandlerOutputFormat", testStreamLogHandlerOutputFormat),
|
||||
("testStreamLogHandlerOutputFormatWithMetaData", testStreamLogHandlerOutputFormatWithMetaData),
|
||||
("testStdioOutputStreamFlush", testStdioOutputStreamFlush),
|
||||
("testOverloadingError", testOverloadingError),
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -29,10 +29,10 @@ class LoggingTest: XCTestCase {
|
||||
var logger = Logger(label: "test")
|
||||
logger.logLevel = .info
|
||||
logger.log(level: .debug, {
|
||||
XCTFail("trace should not be called")
|
||||
return "trace"
|
||||
XCTFail("debug should not be called")
|
||||
return "debug"
|
||||
}())
|
||||
logger.debug({
|
||||
logger.trace({
|
||||
XCTFail("trace should not be called")
|
||||
return "trace"
|
||||
}())
|
||||
@@ -295,7 +295,7 @@ class LoggingTest: XCTestCase {
|
||||
print("new multi")
|
||||
return multi
|
||||
}
|
||||
var logger1: Logger = {
|
||||
let logger1: Logger = {
|
||||
var logger = Logger(label: "foo")
|
||||
logger.logLevel = .debug
|
||||
logger[metadataKey: "only-on"] = "first"
|
||||
@@ -451,6 +451,44 @@ class LoggingTest: XCTestCase {
|
||||
XCTAssertEqual(interceptStream.strings.count, 1)
|
||||
}
|
||||
|
||||
func testStreamLogHandlerOutputFormat() {
|
||||
let interceptStream = InterceptStream()
|
||||
let label = "testLabel"
|
||||
LoggingSystem.bootstrapInternal { _ in
|
||||
StreamLogHandler(label: label, stream: interceptStream)
|
||||
}
|
||||
let log = Logger(label: label)
|
||||
|
||||
let testString = "my message is better than yours"
|
||||
log.critical("\(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:\\s\(testString)$"
|
||||
|
||||
let messageSucceeded = interceptStream.interceptedText?.trimmingCharacters(in: .whitespacesAndNewlines).range(of: pattern, options: .regularExpression) != nil
|
||||
|
||||
XCTAssertTrue(messageSucceeded)
|
||||
XCTAssertEqual(interceptStream.strings.count, 1)
|
||||
}
|
||||
|
||||
func testStreamLogHandlerOutputFormatWithMetaData() {
|
||||
let interceptStream = InterceptStream()
|
||||
let label = "testLabel"
|
||||
LoggingSystem.bootstrapInternal { _ in
|
||||
StreamLogHandler(label: label, stream: interceptStream)
|
||||
}
|
||||
let log = Logger(label: label)
|
||||
|
||||
let testString = "my message is better than yours"
|
||||
log.critical("\(testString)", metadata: ["test": "test"])
|
||||
|
||||
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\(testString)$"
|
||||
|
||||
let messageSucceeded = interceptStream.interceptedText?.trimmingCharacters(in: .whitespacesAndNewlines).range(of: pattern, options: .regularExpression) != nil
|
||||
|
||||
XCTAssertTrue(messageSucceeded)
|
||||
XCTAssertEqual(interceptStream.strings.count, 1)
|
||||
}
|
||||
|
||||
func testStdioOutputStreamFlush() {
|
||||
// flush on every statement
|
||||
self.withWriteReadFDsAndReadBuffer { writeFD, readFD, readBuffer in
|
||||
@@ -512,4 +550,29 @@ class LoggingTest: XCTestCase {
|
||||
|
||||
fds.forEach { close($0) }
|
||||
}
|
||||
|
||||
func testOverloadingError() {
|
||||
struct Dummy: Error, LocalizedError {
|
||||
var errorDescription: String? {
|
||||
return "errorDescription"
|
||||
}
|
||||
}
|
||||
// bootstrap with our test logging impl
|
||||
let logging = TestLogging()
|
||||
LoggingSystem.bootstrapInternal(logging.make)
|
||||
|
||||
var logger = Logger(label: "test")
|
||||
logger.logLevel = .error
|
||||
logger.error(Dummy())
|
||||
|
||||
logging.history.assertExist(level: .error, message: "errorDescription")
|
||||
}
|
||||
}
|
||||
|
||||
extension Logger {
|
||||
public func error(_ error: Error,
|
||||
metadata: @autoclosure () -> Logger.Metadata? = nil,
|
||||
file: String = #file, function: String = #function, line: UInt = #line) {
|
||||
self.error("\(error.localizedDescription)", metadata: metadata(), file: file, function: function, line: line)
|
||||
}
|
||||
}
|
||||
+4
-3
@@ -1,6 +1,7 @@
|
||||
ARG swift_version=5.0
|
||||
ARG ubuntu_version=bionic
|
||||
FROM swift:$swift_version-$ubuntu_version
|
||||
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
|
||||
@@ -13,7 +14,7 @@ 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 # used by integration tests
|
||||
RUN apt-get update && apt-get install -y lsof dnsutils netcat-openbsd net-tools curl jq # used by integration tests
|
||||
|
||||
# ruby and jazzy for docs generation
|
||||
RUN apt-get update && apt-get install -y ruby ruby-dev libsqlite3-dev
|
||||
@@ -29,7 +30,7 @@ RUN chmod 755 $HOME/.tools/symbolicate-linux-fatal
|
||||
|
||||
# swiftformat (until part of the toolchain)
|
||||
|
||||
ARG swiftformat_version=0.40.11
|
||||
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
|
||||
@@ -11,3 +11,6 @@ services:
|
||||
|
||||
test:
|
||||
image: swift-log:18.04-5.0
|
||||
|
||||
shell:
|
||||
image: swift-log:18.04-5.0
|
||||
@@ -0,0 +1,18 @@
|
||||
version: "3"
|
||||
|
||||
services:
|
||||
|
||||
runtime-setup:
|
||||
image: swift-log:18.04-5.1
|
||||
build:
|
||||
args:
|
||||
ubuntu_version: "bionic"
|
||||
swift_version: "5.1"
|
||||
|
||||
test:
|
||||
image: swift-log:18.04-5.1
|
||||
environment: []
|
||||
#- SANITIZER_ARG=--sanitize=thread
|
||||
|
||||
shell:
|
||||
image: swift-log:18.04-5.1
|
||||
@@ -0,0 +1,18 @@
|
||||
version: "3"
|
||||
|
||||
services:
|
||||
|
||||
runtime-setup:
|
||||
image: swift-log:18.04-5.2
|
||||
build:
|
||||
args:
|
||||
ubuntu_version: "bionic"
|
||||
swift_version: "5.2"
|
||||
|
||||
test:
|
||||
image: swift-log:18.04-5.2
|
||||
environment: []
|
||||
#- SANITIZER_ARG=--sanitize=thread
|
||||
|
||||
shell:
|
||||
image: swift-log:18.04-5.2
|
||||
@@ -0,0 +1,17 @@
|
||||
version: "3"
|
||||
|
||||
services:
|
||||
|
||||
runtime-setup:
|
||||
image: swift-log:18.04-5.3
|
||||
build:
|
||||
args:
|
||||
base_image: "swiftlang/swift:nightly-5.3-bionic"
|
||||
|
||||
test:
|
||||
image: swift-log:18.04-5.3
|
||||
environment: []
|
||||
#- SANITIZER_ARG=--sanitize=thread
|
||||
|
||||
shell:
|
||||
image: swift-log:18.04-5.3
|
||||
@@ -16,13 +16,22 @@ services:
|
||||
depends_on: [runtime-setup]
|
||||
volumes:
|
||||
- ~/.ssh:/root/.ssh
|
||||
- ..:/code
|
||||
- ..:/code:z
|
||||
working_dir: /code
|
||||
cap_drop:
|
||||
- CAP_NET_RAW
|
||||
- CAP_NET_BIND_SERVICE
|
||||
|
||||
sanity:
|
||||
<<: *common
|
||||
command: /bin/bash -cl "./scripts/sanity.sh"
|
||||
command: /bin/bash -xcl "./scripts/sanity.sh"
|
||||
|
||||
test:
|
||||
<<: *common
|
||||
command: /bin/bash -cl "swift test"
|
||||
command: /bin/bash -xcl "swift test -Xswiftc -warnings-as-errors $${SANITIZER_ARG-}"
|
||||
|
||||
# util
|
||||
|
||||
shell:
|
||||
<<: *common
|
||||
entrypoint: /bin/bash
|
||||
Executable
+136
@@ -0,0 +1,136 @@
|
||||
#!/bin/bash
|
||||
##===----------------------------------------------------------------------===##
|
||||
##
|
||||
## This source file is part of the Swift Logging API open source project
|
||||
##
|
||||
## Copyright (c) 2019 Apple Inc. and the Swift Logging API project authors
|
||||
## Licensed under Apache License v2.0
|
||||
##
|
||||
## See LICENSE.txt for license information
|
||||
## See CONTRIBUTORS.txt for the list of Swift Logging API project authors
|
||||
##
|
||||
## SPDX-License-Identifier: Apache-2.0
|
||||
##
|
||||
##===----------------------------------------------------------------------===##
|
||||
|
||||
##===----------------------------------------------------------------------===##
|
||||
##
|
||||
## This source file is part of the SwiftNIO open source project
|
||||
##
|
||||
## Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
|
||||
## Licensed under Apache License v2.0
|
||||
##
|
||||
## See LICENSE.txt for license information
|
||||
## See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
##
|
||||
## SPDX-License-Identifier: Apache-2.0
|
||||
##
|
||||
##===----------------------------------------------------------------------===##
|
||||
|
||||
set -eu
|
||||
|
||||
# repodir
|
||||
function all_modules() {
|
||||
local repodir="$1"
|
||||
(
|
||||
set -eu
|
||||
cd "$repodir"
|
||||
swift package dump-package | jq '.products |
|
||||
map(select(.type | has("library") )) |
|
||||
map(.name) | .[]' | tr -d '"'
|
||||
)
|
||||
}
|
||||
|
||||
# repodir tag output
|
||||
function build_and_do() {
|
||||
local repodir=$1
|
||||
local tag=$2
|
||||
local output=$3
|
||||
|
||||
(
|
||||
cd "$repodir"
|
||||
git checkout -q "$tag"
|
||||
swift build
|
||||
while read -r module; do
|
||||
swift api-digester -sdk "$sdk" -dump-sdk -module "$module" \
|
||||
-o "$output/$module.json" -I "$repodir/.build/debug"
|
||||
done < <(all_modules "$repodir")
|
||||
)
|
||||
}
|
||||
|
||||
function usage() {
|
||||
echo >&2 "Usage: $0 REPO-GITHUB-URL NEW-VERSION OLD-VERSIONS..."
|
||||
echo >&2
|
||||
echo >&2 "This script requires a Swift 5.1+ toolchain."
|
||||
echo >&2
|
||||
echo >&2 "Examples:"
|
||||
echo >&2
|
||||
echo >&2 "Check between master and tag 2.1.1 of swift-nio:"
|
||||
echo >&2 " $0 https://github.com/apple/swift-nio master 2.1.1"
|
||||
echo >&2
|
||||
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
|
||||
|
||||
sdk=/
|
||||
if [[ "$(uname -s)" == Darwin ]]; then
|
||||
sdk=$(xcrun --show-sdk-path)
|
||||
fi
|
||||
|
||||
hash jq 2> /dev/null || { echo >&2 "ERROR: jq must be installed"; exit 1; }
|
||||
tmpdir=$(mktemp -d /tmp/.check-api_XXXXXX)
|
||||
repo_url=$1
|
||||
new_tag=$2
|
||||
shift 2
|
||||
|
||||
repodir="$tmpdir/repo"
|
||||
git clone "$repo_url" "$repodir"
|
||||
git -C "$repodir" fetch -q origin '+refs/pull/*:refs/remotes/origin/pr/*'
|
||||
errors=0
|
||||
|
||||
for old_tag in "$@"; do
|
||||
mkdir "$tmpdir/api-old"
|
||||
mkdir "$tmpdir/api-new"
|
||||
|
||||
echo "Checking public API breakages from $old_tag to $new_tag"
|
||||
|
||||
build_and_do "$repodir" "$new_tag" "$tmpdir/api-new/"
|
||||
build_and_do "$repodir" "$old_tag" "$tmpdir/api-old/"
|
||||
|
||||
for f in "$tmpdir/api-new"/*; do
|
||||
f=$(basename "$f")
|
||||
report="$tmpdir/$f.report"
|
||||
if [[ ! -f "$tmpdir/api-old/$f" ]]; then
|
||||
echo "NOTICE: NEW MODULE $f"
|
||||
continue
|
||||
fi
|
||||
|
||||
echo -n "Checking $f... "
|
||||
swift api-digester -sdk "$sdk" -diagnose-sdk \
|
||||
--input-paths "$tmpdir/api-old/$f" -input-paths "$tmpdir/api-new/$f" 2>&1 \
|
||||
> "$report" 2>&1
|
||||
|
||||
if ! shasum "$report" | grep -q cefc4ee5bb7bcdb7cb5a7747efa178dab3c794d5; then
|
||||
echo ERROR
|
||||
echo >&2 "=============================="
|
||||
echo >&2 "ERROR: public API change in $f"
|
||||
echo >&2 "=============================="
|
||||
cat >&2 "$report"
|
||||
errors=$(( errors + 1 ))
|
||||
else
|
||||
echo OK
|
||||
fi
|
||||
done
|
||||
rm -rf "$tmpdir/api-new" "$tmpdir/api-old"
|
||||
done
|
||||
|
||||
if [[ "$errors" == 0 ]]; then
|
||||
echo "OK, all seems good"
|
||||
fi
|
||||
echo done
|
||||
exit "$errors"
|
||||
@@ -13,7 +13,7 @@
|
||||
##
|
||||
##===----------------------------------------------------------------------===##
|
||||
|
||||
set -e
|
||||
set -ex
|
||||
|
||||
my_path="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
|
||||
root_path="$my_path/.."
|
||||
@@ -51,7 +51,12 @@ fi
|
||||
if ! command -v jazzy > /dev/null; then
|
||||
gem install jazzy --no-ri --no-rdoc
|
||||
fi
|
||||
module_switcher="docs/$version/README.md"
|
||||
|
||||
jazzy_dir="$root_path/.build/jazzy"
|
||||
rm -rf "$jazzy_dir"
|
||||
mkdir -p "$jazzy_dir"
|
||||
|
||||
module_switcher="$jazzy_dir/README.md"
|
||||
jazzy_args=(--clean
|
||||
--author 'SwiftLog team'
|
||||
--readme "$module_switcher"
|
||||
@@ -68,12 +73,12 @@ SwiftLog is a Swift logging API package.
|
||||
To get started with SwiftLog, [`import Logging`](../Logging/index.html). The
|
||||
most important type is [`Logger`](https://apple.github.io/swift-log/docs/current/Logging/Structs/Logger.html)
|
||||
which you can use to emit log messages.
|
||||
|
||||
EOF
|
||||
|
||||
tmp=`mktemp -d`
|
||||
for module in "${modules[@]}"; do
|
||||
args=("${jazzy_args[@]}" --output "$tmp/docs/$version/$module" --docset-path "$tmp/docset/$version/$module" --module "$module")
|
||||
args=("${jazzy_args[@]}" --output "$jazzy_dir/docs/$version/$module" --docset-path "$jazzy_dir/docset/$version/$module"
|
||||
--module "$module" --module-version $version
|
||||
--root-url "https://apple.github.io/swift-log/docs/$version/$module/")
|
||||
if [[ -f "$root_path/.build/sourcekitten/$module.json" ]]; then
|
||||
args+=(--sourcekitten-sourcefile "$root_path/.build/sourcekitten/$module.json")
|
||||
fi
|
||||
@@ -81,13 +86,14 @@ for module in "${modules[@]}"; do
|
||||
done
|
||||
|
||||
# push to github pages
|
||||
if [[ $CI == true ]]; then
|
||||
if [[ $PUSH == true ]]; then
|
||||
BRANCH_NAME=$(git rev-parse --abbrev-ref HEAD)
|
||||
GIT_AUTHOR=$(git --no-pager show -s --format='%an <%ae>' HEAD)
|
||||
git fetch origin +gh-pages:gh-pages
|
||||
git checkout gh-pages
|
||||
rm -rf "docs"
|
||||
cp -r "$tmp/docs" .
|
||||
rm -rf "docs/$version"
|
||||
rm -rf "docs/current"
|
||||
cp -r "$jazzy_dir/docs/$version" docs/
|
||||
cp -r "docs/$version" docs/current
|
||||
git add --all docs
|
||||
echo '<html><head><meta http-equiv="refresh" content="0; url=docs/current/Logging/index.html" /></head></html>' > index.html
|
||||
|
||||
Reference in new issue
Block a user