From d1af77eebdb7e14543bd2aed270d759d07769471 Mon Sep 17 00:00:00 2001 From: Johannes Weiss Date: Thu, 21 Mar 2019 12:34:41 +0000 Subject: [PATCH] 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 --- Package.swift | 2 +- Sources/Logging/Locks.swift | 14 ++- Sources/Logging/Logging.swift | 116 ++++++++++++++------ Tests/LoggingTests/GlobalLoggingTest.swift | 9 +- Tests/LoggingTests/LocalLoggingTest.swift | 9 +- Tests/LoggingTests/LoggingTest+XCTest.swift | 4 - Tests/LoggingTests/LoggingTest.swift | 84 +++----------- Tests/LoggingTests/MDCTest.swift | 10 +- Tests/LoggingTests/TestLogger.swift | 11 +- 9 files changed, 133 insertions(+), 126 deletions(-) diff --git a/Package.swift b/Package.swift index efc6ef4..248e255 100644 --- a/Package.swift +++ b/Package.swift @@ -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 diff --git a/Sources/Logging/Locks.swift b/Sources/Logging/Locks.swift index 6498278..8298a37 100644 --- a/Sources/Logging/Locks.swift +++ b/Sources/Logging/Locks.swift @@ -49,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. @@ -80,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(_ body: () throws -> T) rethrows -> T { self.lock() defer { @@ -90,7 +93,6 @@ extension Lock { } // specialise Void return (for performance) - @inlinable internal func withLockVoid(_ body: () throws -> Void) rethrows { try self.withLock(body) } @@ -113,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. @@ -153,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(_ body: () throws -> T) rethrows -> T { self.lockRead() defer { @@ -170,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(_ body: () throws -> T) rethrows -> T { self.lockWrite() defer { @@ -180,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) } diff --git a/Sources/Logging/Logging.swift b/Sources/Logging/Logging.swift index 49cda79..0ae8e91 100644 --- a/Sources/Logging/Logging.swift +++ b/Sources/Logging/Logging.swift @@ -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,20 @@ 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) } + 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) + } + /// 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 +148,20 @@ 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) } + 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) + } + /// 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 +177,20 @@ 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) } + 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) + } + /// 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 +206,20 @@ 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) } + 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) + } + /// 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 +235,20 @@ 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) } + 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) + } + /// 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 +264,20 @@ 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) } + 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) + } + /// Log a message passing with the `Logger.Level.critical` log level. /// /// `.critical` messages will always be logged. @@ -243,12 +292,20 @@ 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) } + + 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) + } + } /// The `LoggingSystem` is a global facility where the default logging backend implementation (`LogHandler`) can be @@ -304,7 +361,7 @@ extension Logger { /// /// Raw values of log levels correspond to their severity, and are ordered by lowest numeric value (0) being /// the most severe. The raw values match the syslog values. - public enum Level: CaseIterable { + public enum Level { /// Appropriate for messages that contain information only when debugging a program. case trace @@ -422,10 +479,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 +494,17 @@ extension Logger { } } +#if swift(>=4.0) && !swift(>=4.0.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 +629,13 @@ internal struct StdoutLogHandler: LogHandler { let localTime = localtime(×tamp) 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 +651,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 { diff --git a/Tests/LoggingTests/GlobalLoggingTest.swift b/Tests/LoggingTests/GlobalLoggingTest.swift index 687e8df..dea07a1 100644 --- a/Tests/LoggingTests/GlobalLoggingTest.swift +++ b/Tests/LoggingTests/GlobalLoggingTest.swift @@ -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") } diff --git a/Tests/LoggingTests/LocalLoggingTest.swift b/Tests/LoggingTests/LocalLoggingTest.swift index 75c8492..d9dd9a6 100644 --- a/Tests/LoggingTests/LocalLoggingTest.swift +++ b/Tests/LoggingTests/LocalLoggingTest.swift @@ -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 @@ -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") } diff --git a/Tests/LoggingTests/LoggingTest+XCTest.swift b/Tests/LoggingTests/LoggingTest+XCTest.swift index 31dcfe3..a99d0a7 100644 --- a/Tests/LoggingTests/LoggingTest+XCTest.swift +++ b/Tests/LoggingTests/LoggingTest+XCTest.swift @@ -28,9 +28,6 @@ extension LoggingTest { return [ ("testAutoclosure", testAutoclosure), ("testMultiplex", testMultiplex), - ("testDictionaryMetadata", testDictionaryMetadata), - ("testListMetadata", testListMetadata), - ("testStringConvertibleMetadata", testStringConvertibleMetadata), ("testAutoClosuresAreNotForcedUnlessNeeded", testAutoClosuresAreNotForcedUnlessNeeded), ("testLocalMetadata", testLocalMetadata), ("testCustomFactory", testCustomFactory), @@ -40,7 +37,6 @@ extension LoggingTest { ("testLoggingAString", testLoggingAString), ("testMultiplexerIsValue", testMultiplexerIsValue), ("testLoggerWithGlobalOverride", testLoggerWithGlobalOverride), - ("testLogLevelCases", testLogLevelCases), ("testLogLevelOrdering", testLogLevelOrdering), ] } diff --git a/Tests/LoggingTests/LoggingTest.swift b/Tests/LoggingTests/LoggingTest.swift index 4b4677e..e550873 100644 --- a/Tests/LoggingTests/LoggingTest.swift +++ b/Tests/LoggingTests/LoggingTest.swift @@ -22,15 +22,15 @@ 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" }()) - logger.debug({ + logger.debug({ () -> String in XCTFail("trace should not be called") return "trace" }()) - logger.debug({ + logger.debug({ () -> String in XCTFail("debug should not be called") return "debug" }()) @@ -60,7 +60,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 +72,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,22 +99,7 @@ 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" }))]) - } - - private func dontEvaluateThisString(file: StaticString = #file, line: UInt = #line) -> Logger.Message { + 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" } @@ -171,8 +124,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 +214,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 +245,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 +320,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") @@ -389,11 +342,6 @@ class LoggingTest: XCTestCase { logRecorder.assertExist(level: .notice, message: "logger2, after") } - func testLogLevelCases() { - let levels = Logger.Level.allCases - XCTAssertEqual(7, levels.count) - } - func testLogLevelOrdering() { XCTAssertLessThan(Logger.Level.trace, Logger.Level.debug) XCTAssertLessThan(Logger.Level.trace, Logger.Level.info) diff --git a/Tests/LoggingTests/MDCTest.swift b/Tests/LoggingTests/MDCTest.swift index c5cef47..47472af 100644 --- a/Tests/LoggingTests/MDCTest.swift +++ b/Tests/LoggingTests/MDCTest.swift @@ -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") } diff --git a/Tests/LoggingTests/TestLogger.swift b/Tests/LoggingTests/TestLogger.swift index 3717776..3295bf0 100644 --- a/Tests/LoggingTests/TestLogger.swift +++ b/Tests/LoggingTests/TestLogger.swift @@ -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) }