From 2474d61a8097dbe7c03425a8ac37247c8bfda37a Mon Sep 17 00:00:00 2001 From: David Hart Date: Mon, 18 Feb 2019 21:27:59 +0200 Subject: [PATCH] Multiple proposal improvements to the API (#41) * Move `Logging.make` to a `Logger` initializer. * Remove all factory initializers in example and test code. --- ...pleLogger.swift => CommonLogHandler.swift} | 16 +-- .../ConfigLogHandler.swift | 82 ++++++++++++ .../ExampleImplementation/ConfigLogging.swift | 92 ------------- .../FileLogHandler.swift | 70 ++++++++++ .../ExampleImplementation/FileLogging.swift | 78 ----------- .../SimpleLogHandler.swift | 42 ++++++ .../ExampleImplementation/SimpleLogging.swift | 48 ------- Sources/ExampleUsage/ConfigExample.swift | 8 +- Sources/ExampleUsage/ContextBasedSystem.swift | 9 +- .../GlobalLoggerBasedSystem.swift | 5 +- .../ExampleUsage/LocalLoggerBasedSystem.swift | 9 +- Sources/ExampleUsage/MultiplexExample.swift | 5 +- Sources/ExampleUsage/RandomLibrary.swift | 2 +- Sources/Logging/Logging.swift | 126 ++++++++---------- Tests/LoggingTests/GlobalLoggingTest.swift | 16 +-- Tests/LoggingTests/LocalLoggingTest.swift | 14 +- Tests/LoggingTests/LoggingTest.swift | 32 ++--- Tests/LoggingTests/MDCTest.swift | 2 +- Tests/LoggingTests/TestLogger.swift | 56 ++++---- 19 files changed, 336 insertions(+), 376 deletions(-) rename Sources/ExampleImplementation/{SimpleLogger.swift => CommonLogHandler.swift} (79%) create mode 100644 Sources/ExampleImplementation/ConfigLogHandler.swift delete mode 100644 Sources/ExampleImplementation/ConfigLogging.swift create mode 100644 Sources/ExampleImplementation/FileLogHandler.swift delete mode 100644 Sources/ExampleImplementation/FileLogging.swift create mode 100644 Sources/ExampleImplementation/SimpleLogHandler.swift delete mode 100644 Sources/ExampleImplementation/SimpleLogging.swift diff --git a/Sources/ExampleImplementation/SimpleLogger.swift b/Sources/ExampleImplementation/CommonLogHandler.swift similarity index 79% rename from Sources/ExampleImplementation/SimpleLogger.swift rename to Sources/ExampleImplementation/CommonLogHandler.swift index 0979c45..727d8da 100644 --- a/Sources/ExampleImplementation/SimpleLogger.swift +++ b/Sources/ExampleImplementation/CommonLogHandler.swift @@ -6,9 +6,9 @@ import Foundation import Logging // helper class to keep things DRY -internal struct SimpleLogger { +internal struct CommonLogHandler { let label: String - private var _logLevel: Logging.Level? + private var _logLevel: Logger.Level? private let formatter: DateFormatter private let lock = NSLock() @@ -21,12 +21,12 @@ internal struct SimpleLogger { self.formatter = formatter } - public func log(level: Logging.Level, message: String, metadata: Logging.Metadata?, error: Error?, printer: (String) -> Void) { + public func log(level: Logger.Level, message: String, metadata: Logger.Metadata?, error: Error?, printer: (String) -> Void) { let prettyMetadata = metadata?.isEmpty ?? true ? self.prettyMetadata : self.prettify(self.metadata.merging(metadata!, uniquingKeysWith: { _, new in new })) printer("[\(self.label)] \(self.formatter.string(from: Date()))\(prettyMetadata.map { " \($0)" } ?? "") \(level): \(message)\(error.map { " \($0)" } ?? "")") } - public var logLevel: Logging.Level? { + public var logLevel: Logger.Level? { get { return self.lock.withLock { self._logLevel } } @@ -38,13 +38,13 @@ internal struct SimpleLogger { } private var prettyMetadata: String? - private var _metadata = Logging.Metadata() { + private var _metadata = Logger.Metadata() { didSet { self.prettyMetadata = self.prettify(self._metadata) } } - public var metadata: Logging.Metadata { + public var metadata: Logger.Metadata { get { return self.lock.withLock { self._metadata } } @@ -53,7 +53,7 @@ internal struct SimpleLogger { } } - public subscript(metadataKey metadataKey: String) -> Logging.Metadata.Value? { + public subscript(metadataKey metadataKey: String) -> Logger.Metadata.Value? { get { return self.lock.withLock { self._metadata[metadataKey] } } @@ -64,7 +64,7 @@ internal struct SimpleLogger { } } - private func prettify(_ metadata: Logging.Metadata) -> String? { + private func prettify(_ metadata: Logger.Metadata) -> String? { return !metadata.isEmpty ? metadata.map { "\($0)=\($1)" }.joined(separator: " ") : nil } } diff --git a/Sources/ExampleImplementation/ConfigLogHandler.swift b/Sources/ExampleImplementation/ConfigLogHandler.swift new file mode 100644 index 0000000..678da1e --- /dev/null +++ b/Sources/ExampleImplementation/ConfigLogHandler.swift @@ -0,0 +1,82 @@ +// +// THIS IS NOT PART OF THE PITCH, JUST AN EXAMPLE HOW A LOGGER IMPLEMENTATION LOOKS LIKE +// + +import Foundation +import Logging + +// this is a contrived example of a logging library implementation that allows users to define log levels per logger label +// this example uses a simplistic in-memory config which can be changed at runtime via code +// real implementations could use external config files that can be changed outside the running program +public class Config { + private static let ALL = "*" + + private let lock = NSLock() + private var storage = [String: Logger.Level]() + private var defaultLogLevel: Logger.Level + + public init(defaultLogLevel: Logger.Level) { + self.defaultLogLevel = defaultLogLevel + } + + func get(key: String) -> Logger.Level { + return self.get(key) ?? self.get(Config.ALL) ?? self.defaultLogLevel + } + + func get(_ key: String) -> Logger.Level? { + return self.lock.withLock { self.storage[key] } + } + + public func set(key: String, value: Logger.Level) { + self.lock.withLock { self.storage[key] = value } + } + + public func set(value: Logger.Level) { + self.lock.withLock { self.storage[Config.ALL] = value } + } + + public func clear() { + self.lock.withLock { self.storage.removeAll() } + } +} + +public struct ConfigLogHandler: LogHandler { + private var handler: CommonLogHandler + private var config: Config + + public init(label: String, config: Config) { + self.handler = CommonLogHandler(label: label) + self.config = config + } + + public func log(level: Logger.Level, message: String, metadata: Logger.Metadata?, error: Error?, file: StaticString, function: StaticString, line: UInt) { + self.handler.log(level: level, message: message, metadata: metadata, error: error) { text in + print(text) + } + } + + public var logLevel: Logger.Level { + get { return self.handler.logLevel ?? self.config.get(key: self.handler.label) } + set { self.handler.logLevel = newValue } + } + + public var metadata: Logger.Metadata { + get { return self.handler.metadata } + set { self.handler.metadata = newValue } + } + + public subscript(metadataKey metadataKey: String) -> Logger.Metadata.Value? { + get { return self.handler[metadataKey: metadataKey] } + set { self.handler[metadataKey: metadataKey] = newValue } + } +} + +private extension NSLock { + func withLock(_ body: () -> T) -> T { + self.lock() + defer { + self.unlock() + } + return body() + } +} diff --git a/Sources/ExampleImplementation/ConfigLogging.swift b/Sources/ExampleImplementation/ConfigLogging.swift deleted file mode 100644 index ba93a0f..0000000 --- a/Sources/ExampleImplementation/ConfigLogging.swift +++ /dev/null @@ -1,92 +0,0 @@ -// -// THIS IS NOT PART OF THE PITCH, JUST AN EXAMPLE HOW A LOGGER IMPLEMENTATION LOOKS LIKE -// - -import Foundation -import Logging - -// this is a contrived example of a logging library implementation that allows users to define log levels per logger label -// this example uses a simplistic in-memory config which can be changed at runtime via code -// real implementations could use external config files that can be changed outside the running program -public struct ConfigLogging { - public var config = Config(defaultLogLevel: .info) - - public init() {} - - public func make(label: String) -> LogHandler { - return Logger(label: label, config: self.config) - } - - private struct Logger: LogHandler { - private var logger: SimpleLogger - private var config: Config - - public init(label: String, config: Config) { - self.logger = SimpleLogger(label: label) - self.config = config - } - - public func log(level: Logging.Level, message: String, metadata: Logging.Metadata?, error: Error?, file: StaticString, function: StaticString, line: UInt) { - self.logger.log(level: level, message: message, metadata: metadata, error: error) { text in - print(text) - } - } - - public var logLevel: Logging.Level { - get { return self.logger.logLevel ?? self.config.get(key: self.logger.label) } - set { self.logger.logLevel = newValue } - } - - public var metadata: Logging.Metadata { - get { return self.logger.metadata } - set { self.logger.metadata = newValue } - } - - public subscript(metadataKey metadataKey: String) -> Logging.Metadata.Value? { - get { return self.logger[metadataKey: metadataKey] } - set { self.logger[metadataKey: metadataKey] = newValue } - } - } - - public class Config { - private static let ALL = "*" - - private let lock = NSLock() - private var storage = [String: Logging.Level]() - private var defaultLogLevel: Logging.Level - - init(defaultLogLevel: Logging.Level) { - self.defaultLogLevel = defaultLogLevel - } - - func get(key: String) -> Logging.Level { - return self.get(key) ?? self.get(Config.ALL) ?? self.defaultLogLevel - } - - func get(_ key: String) -> Logging.Level? { - return self.lock.withLock { self.storage[key] } - } - - public func set(key: String, value: Logging.Level) { - self.lock.withLock { self.storage[key] = value } - } - - public func set(value: Logging.Level) { - self.lock.withLock { self.storage[Config.ALL] = value } - } - - public func clear() { - self.lock.withLock { self.storage.removeAll() } - } - } -} - -private extension NSLock { - func withLock(_ body: () -> T) -> T { - self.lock() - defer { - self.unlock() - } - return body() - } -} diff --git a/Sources/ExampleImplementation/FileLogHandler.swift b/Sources/ExampleImplementation/FileLogHandler.swift new file mode 100644 index 0000000..98aa1b1 --- /dev/null +++ b/Sources/ExampleImplementation/FileLogHandler.swift @@ -0,0 +1,70 @@ +// +// THIS IS NOT PART OF THE PITCH, JUST AN EXAMPLE HOW A LOGGER IMPLEMENTATION LOOKS LIKE +// + +import Foundation +import Logging +#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) + import Darwin +#else + import Glibc +#endif + +// this is a contrived example of a logging library implementation that writes logs to files +public struct FileLogHandler: LogHandler { + private var handler: CommonLogHandler + private let defaultLogLevel: Logger.Level + private let fileHandler = FileHandler() + + public init(label: String) { + self.init(label: label, defaultLogLevel: .info) + } + + public init(label: String, defaultLogLevel: Logger.Level) { + self.handler = CommonLogHandler(label: label) + self.defaultLogLevel = defaultLogLevel + } + + public func log(level: Logger.Level, message: String, metadata: Logger.Metadata?, error: Error?, file: StaticString, function: StaticString, line: UInt) { + self.handler.log(level: level, message: message, metadata: metadata, error: error) { text in + self.fileHandler._write(text) + } + } + + public var logLevel: Logger.Level { + get { return self.handler.logLevel ?? self.defaultLogLevel } + set { self.handler.logLevel = newValue } + } + + public var metadata: Logger.Metadata { + get { return self.handler.metadata } + set { self.handler.metadata = newValue } + } + + public subscript(metadataKey metadataKey: String) -> Logger.Metadata.Value? { + get { return self.handler[metadataKey: metadataKey] } + set { self.handler[metadataKey: metadataKey] = newValue } + } +} + +private class FileHandler { + let path: String + let fd: Int32 + + init() { + self.path = "/tmp/log-\(UUID().uuidString).txt" + self.fd = open(self.path, O_WRONLY | O_CREAT, 0o666) + assert(self.fd > 0, "could not open \(self.path)") + print("writing logs to \(self.path)") + } + + deinit { + if fd > 0 { + close(fd) + } + } + + func _write(_ text: String) { + write(self.fd, text, text.utf8.count) + } +} diff --git a/Sources/ExampleImplementation/FileLogging.swift b/Sources/ExampleImplementation/FileLogging.swift deleted file mode 100644 index e500bb1..0000000 --- a/Sources/ExampleImplementation/FileLogging.swift +++ /dev/null @@ -1,78 +0,0 @@ -// -// THIS IS NOT PART OF THE PITCH, JUST AN EXAMPLE HOW A LOGGER IMPLEMENTATION LOOKS LIKE -// - -import Foundation -import Logging -#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) - import Darwin -#else - import Glibc -#endif - -// this is a contrived example of a logging library implementation that writes logs to files -public struct FileLogging { - private let defaultLogLevel: Logging.Level = .info - private let fileHandler = FileHandler() - - public init() {} - - public func make(label: String) -> LogHandler { - return Logger(label: label, defaultLogLevel: self.defaultLogLevel, fileHandler: self.fileHandler) - } - - private struct Logger: LogHandler { - private var logger: SimpleLogger - private let defaultLogLevel: Logging.Level - private let fileHandler: FileHandler - - public init(label: String, defaultLogLevel: Logging.Level, fileHandler: FileHandler) { - self.logger = SimpleLogger(label: label) - self.defaultLogLevel = defaultLogLevel - self.fileHandler = fileHandler - } - - public func log(level: Logging.Level, message: String, metadata: Logging.Metadata?, error: Error?, file: StaticString, function: StaticString, line: UInt) { - self.logger.log(level: level, message: message, metadata: metadata, error: error) { text in - self.fileHandler._write(text) - } - } - - public var logLevel: Logging.Level { - get { return self.logger.logLevel ?? self.defaultLogLevel } - set { self.logger.logLevel = newValue } - } - - public var metadata: Logging.Metadata { - get { return self.logger.metadata } - set { self.logger.metadata = newValue } - } - - public subscript(metadataKey metadataKey: String) -> Logging.Metadata.Value? { - get { return self.logger[metadataKey: metadataKey] } - set { self.logger[metadataKey: metadataKey] = newValue } - } - } - - private class FileHandler { - let path: String - let fd: Int32 - - init() { - self.path = "/tmp/log-\(UUID().uuidString).txt" - self.fd = open(self.path, O_WRONLY | O_CREAT, 0o666) - assert(self.fd > 0, "could not open \(self.path)") - print("writing logs to \(self.path)") - } - - deinit { - if fd > 0 { - close(fd) - } - } - - func _write(_ text: String) { - write(self.fd, text, text.utf8.count) - } - } -} diff --git a/Sources/ExampleImplementation/SimpleLogHandler.swift b/Sources/ExampleImplementation/SimpleLogHandler.swift new file mode 100644 index 0000000..012d62b --- /dev/null +++ b/Sources/ExampleImplementation/SimpleLogHandler.swift @@ -0,0 +1,42 @@ +// +// THIS IS NOT PART OF THE PITCH, JUST AN EXAMPLE HOW A LOGGER IMPLEMENTATION LOOKS LIKE +// + +import Foundation +import Logging + +// this is a contrived example of a logging library implementation that writes logs to stdout +public struct SimpleLogHandler: LogHandler { + private var handler: CommonLogHandler + private let defaultLogLevel: Logger.Level + + public init(label: String) { + self.init(label: label, defaultLogLevel: .info) + } + + public init(label: String, defaultLogLevel: Logger.Level) { + self.handler = CommonLogHandler(label: label) + self.defaultLogLevel = defaultLogLevel + } + + public func log(level: Logger.Level, message: String, metadata: Logger.Metadata?, error: Error?, file: StaticString, function: StaticString, line: UInt) { + self.handler.log(level: level, message: message, metadata: metadata, error: error) { text in + print(text) + } + } + + public var logLevel: Logger.Level { + get { return self.handler.logLevel ?? self.defaultLogLevel } + set { self.handler.logLevel = newValue } + } + + public var metadata: Logger.Metadata { + get { return self.handler.metadata } + set { self.handler.metadata = newValue } + } + + public subscript(metadataKey metadataKey: String) -> Logger.Metadata.Value? { + get { return self.handler[metadataKey: metadataKey] } + set { self.handler[metadataKey: metadataKey] = newValue } + } +} diff --git a/Sources/ExampleImplementation/SimpleLogging.swift b/Sources/ExampleImplementation/SimpleLogging.swift deleted file mode 100644 index 84ef76b..0000000 --- a/Sources/ExampleImplementation/SimpleLogging.swift +++ /dev/null @@ -1,48 +0,0 @@ -// -// THIS IS NOT PART OF THE PITCH, JUST AN EXAMPLE HOW A LOGGER IMPLEMENTATION LOOKS LIKE -// - -import Foundation -import Logging - -// this is a contrived example of a logging library implementation that writes logs to stdout -public struct SimpleLogging { - private let defaultLogLevel = Logging.Level.info - - public init() {} - - public func make(label: String) -> LogHandler { - return Logger(label: label, defaultLogLevel: self.defaultLogLevel) - } - - private struct Logger: LogHandler { - private var logger: SimpleLogger - private let defaultLogLevel: Logging.Level - - public init(label: String, defaultLogLevel: Logging.Level) { - self.logger = SimpleLogger(label: label) - self.defaultLogLevel = defaultLogLevel - } - - public func log(level: Logging.Level, message: String, metadata: Logging.Metadata?, error: Error?, file: StaticString, function: StaticString, line: UInt) { - self.logger.log(level: level, message: message, metadata: metadata, error: error) { text in - print(text) - } - } - - public var logLevel: Logging.Level { - get { return self.logger.logLevel ?? self.defaultLogLevel } - set { self.logger.logLevel = newValue } - } - - public var metadata: Logging.Metadata { - get { return self.logger.metadata } - set { self.logger.metadata = newValue } - } - - public subscript(metadataKey metadataKey: String) -> Logging.Metadata.Value? { - get { return self.logger[metadataKey: metadataKey] } - set { self.logger[metadataKey: metadataKey] = newValue } - } - } -} diff --git a/Sources/ExampleUsage/ConfigExample.swift b/Sources/ExampleUsage/ConfigExample.swift index d15c6b0..914017f 100644 --- a/Sources/ExampleUsage/ConfigExample.swift +++ b/Sources/ExampleUsage/ConfigExample.swift @@ -9,13 +9,13 @@ import Logging enum ConfigExample { static func main() { // boostrap with our config based sample implementations - let logging = ConfigLogging() - Logging.bootstrap(logging.make) + let config = Config(defaultLogLevel: .info) + Logging.bootstrap({ ConfigLogHandler(label: $0, config: config) }) // run the example - let logger = Logging.make("com.example.TestApp") + let logger = Logger(label: "com.example.TestApp") logger.trace("hello world?") // changes the config in runtime, real implemnetations will use config files instead of in-memory config - logging.config.set(key: "com.example.TestApp", value: .trace) + config.set(key: "com.example.TestApp", value: .trace) logger.trace("hello world!") } } diff --git a/Sources/ExampleUsage/ContextBasedSystem.swift b/Sources/ExampleUsage/ContextBasedSystem.swift index 0e8a7ea..2ec6ba5 100644 --- a/Sources/ExampleUsage/ContextBasedSystem.swift +++ b/Sources/ExampleUsage/ContextBasedSystem.swift @@ -12,8 +12,7 @@ import Logging enum ContextBasedSystem { static func main() { // boostrap with our sample implementation - let logging = SimpleLogging() - Logging.bootstrap(logging.make) + Logging.bootstrap(SimpleLogHandler.init) // run the example for i in 1 ... 2 { print("---------------------------- processing request #\(i) ----------------------------") @@ -23,14 +22,14 @@ enum ContextBasedSystem { } struct Context { - var logger = Logging.make("ContextLogger") + var logger = Logger(label: "ContextLogger") - init(metadata: Logging.Metadata = [:]) { + init(metadata: Logger.Metadata = [:]) { metadata.forEach { self[$0.0] = $0.1 } } // since logger is a value type, we can reuse our copy to manage the metadata - subscript(metadataKey: String) -> Logging.Metadata.Value? { + subscript(metadataKey: String) -> Logger.Metadata.Value? { get { return self.logger[metadataKey: metadataKey] } set { self.logger[metadataKey: metadataKey] = newValue } } diff --git a/Sources/ExampleUsage/GlobalLoggerBasedSystem.swift b/Sources/ExampleUsage/GlobalLoggerBasedSystem.swift index bf7191c..395b25d 100644 --- a/Sources/ExampleUsage/GlobalLoggerBasedSystem.swift +++ b/Sources/ExampleUsage/GlobalLoggerBasedSystem.swift @@ -7,7 +7,7 @@ import Foundation import Logging // since this example mutates the global logger, we need to lock around it -var _logger = Logging.make("GlobalLogger") +var _logger = Logger(label: "GlobalLogger") var lock = NSLock() var logger: Logger { get { @@ -26,8 +26,7 @@ var logger: Logger { enum GlobalLoggerBasedSystem { static func main() { // boostrap with our sample implementation - let logging = SimpleLogging() - Logging.bootstrap(logging.make) + Logging.bootstrap(SimpleLogHandler.init) // run the example for i in 1 ... 2 { print("---------------------------- processing request #\(i) ----------------------------") diff --git a/Sources/ExampleUsage/LocalLoggerBasedSystem.swift b/Sources/ExampleUsage/LocalLoggerBasedSystem.swift index 6579b85..d7e51ae 100644 --- a/Sources/ExampleUsage/LocalLoggerBasedSystem.swift +++ b/Sources/ExampleUsage/LocalLoggerBasedSystem.swift @@ -10,8 +10,7 @@ import Logging enum LocalLoggerBasedSystem { static func main() { // boostrap with our sample implementation - let logging = SimpleLogging() - Logging.bootstrap(logging.make) + Logging.bootstrap(SimpleLogHandler.init) // run the example for i in 1 ... 2 { print("---------------------------- processing request #\(i) ----------------------------") @@ -20,7 +19,7 @@ enum LocalLoggerBasedSystem { } class Foo { - private var logger = Logging.make("LocalLoggerBasedSystem::Foo") + private var logger = Logger(label: "LocalLoggerBasedSystem::Foo") func doSomething(requestNumnber: Int) { if 0 == requestNumnber % 2 { @@ -42,7 +41,7 @@ enum LocalLoggerBasedSystem { } class Bar { - private var logger = Logging.make("LocalLoggerBasedSystem::Bar") + private var logger = Logger(label: "LocalLoggerBasedSystem::Bar") func doSomething(requestNumnber: Int) { if 0 == requestNumnber % 2 { @@ -58,7 +57,7 @@ enum LocalLoggerBasedSystem { } class Baz { - private var logger = Logging.make("LocalLoggerBasedSystem::Baz") + private var logger = Logger(label: "LocalLoggerBasedSystem::Baz") private let queue = DispatchQueue(label: "LocalLoggerBasedSystem::Baz") func doSomething(requestNumnber: Int) { diff --git a/Sources/ExampleUsage/MultiplexExample.swift b/Sources/ExampleUsage/MultiplexExample.swift index f79acdb..21f0f13 100644 --- a/Sources/ExampleUsage/MultiplexExample.swift +++ b/Sources/ExampleUsage/MultiplexExample.swift @@ -9,10 +9,9 @@ import Logging enum MultiplexExample { static func main() { // boostrap with two of our sample implementations - let logging = MultiplexLogging([SimpleLogging().make, FileLogging().make]) - Logging.bootstrap(logging.make) + Logging.bootstrap({ MultiplexLogHandler([SimpleLogHandler(label: $0), FileLogHandler(label: $0)]) }) // run the example - let logger = Logging.make("com.example.TestApp") + let logger = Logger(label: "com.example.TestApp") logger.info("hello world!") } } diff --git a/Sources/ExampleUsage/RandomLibrary.swift b/Sources/ExampleUsage/RandomLibrary.swift index cd0f02c..a85ae84 100644 --- a/Sources/ExampleUsage/RandomLibrary.swift +++ b/Sources/ExampleUsage/RandomLibrary.swift @@ -9,7 +9,7 @@ import Logging // this library does not know anything about the systewm that used it, so cannot make // assumptions about them class RandomLibrary { - private let logger = Logging.make("RandomLibrary") + private let logger = Logger(label: "RandomLibrary") private let queue = DispatchQueue(label: "RandomLibrary") public init() {} diff --git a/Sources/Logging/Logging.swift b/Sources/Logging/Logging.swift index 72769d3..85b2801 100644 --- a/Sources/Logging/Logging.swift +++ b/Sources/Logging/Logging.swift @@ -10,17 +10,17 @@ public protocol LogHandler { // `Logger`'s `info`, `error`, or `warning` functions. // // An implementation does not need to check the log level because that has been done before by `Logger` itself. - func log(level: Logging.Level, message: String, metadata: Logging.Metadata?, error: Error?, file: StaticString, function: StaticString, line: UInt) + func log(level: Logger.Level, message: String, metadata: Logger.Metadata?, error: Error?, file: StaticString, function: StaticString, line: UInt) // This adds metadata to a place the concrete logger considers appropriate. Some loggers // might not support this feature at all. - subscript(metadataKey _: String) -> Logging.Metadata.Value? { get set } + subscript(metadataKey _: String) -> Logger.Metadata.Value? { get set } // All available metatdata - var metadata: Logging.Metadata { get set } + var metadata: Logger.Metadata { get set } // The log level - var logLevel: Logging.Level { get set } + var logLevel: Logger.Level { get set } } // This is the logger itself. It can either have value or reference semantics, depending on the `LogHandler` @@ -34,39 +34,39 @@ public struct Logger { } @inlinable - func log(level: Logging.Level, message: @autoclosure () -> String, metadata: @autoclosure () -> Logging.Metadata? = nil, error: Error? = nil, file: StaticString = #file, function: StaticString = #function, line: UInt = #line) { + func log(level: Logger.Level, message: @autoclosure () -> String, metadata: @autoclosure () -> Logger.Metadata? = nil, error: Error? = nil, file: StaticString = #file, function: StaticString = #function, line: UInt = #line) { if self.logLevel <= level { self.handler.log(level: level, message: message(), metadata: metadata(), error: error, file: file, function: function, line: line) } } @inlinable - public func trace(_ message: @autoclosure () -> String, metadata: @autoclosure () -> Logging.Metadata? = nil, error: Error? = nil, file: StaticString = #file, function: StaticString = #function, line: UInt = #line) { + public func trace(_ message: @autoclosure () -> String, metadata: @autoclosure () -> Logger.Metadata? = nil, error: Error? = nil, file: StaticString = #file, function: StaticString = #function, line: UInt = #line) { self.log(level: .trace, message: message, metadata: metadata, error: error, file: file, function: function, line: line) } @inlinable - public func debug(_ message: @autoclosure () -> String, metadata: @autoclosure () -> Logging.Metadata? = nil, error: Error? = nil, file: StaticString = #file, function: StaticString = #function, line: UInt = #line) { + public func debug(_ message: @autoclosure () -> String, metadata: @autoclosure () -> Logger.Metadata? = nil, error: Error? = nil, file: StaticString = #file, function: StaticString = #function, line: UInt = #line) { self.log(level: .debug, message: message, metadata: metadata, error: error, file: file, function: function, line: line) } @inlinable - public func info(_ message: @autoclosure () -> String, metadata: @autoclosure () -> Logging.Metadata? = nil, error: Error? = nil, file: StaticString = #file, function: StaticString = #function, line: UInt = #line) { + public func info(_ message: @autoclosure () -> String, metadata: @autoclosure () -> Logger.Metadata? = nil, error: Error? = nil, file: StaticString = #file, function: StaticString = #function, line: UInt = #line) { self.log(level: .info, message: message, metadata: metadata, error: error, file: file, function: function, line: line) } @inlinable - public func warning(_ message: @autoclosure () -> String, metadata: @autoclosure () -> Logging.Metadata? = nil, error: Error? = nil, file: StaticString = #file, function: StaticString = #function, line: UInt = #line) { + public func warning(_ message: @autoclosure () -> String, metadata: @autoclosure () -> Logger.Metadata? = nil, error: Error? = nil, file: StaticString = #file, function: StaticString = #function, line: UInt = #line) { self.log(level: .warning, message: message, metadata: metadata, error: error, file: file, function: function, line: line) } @inlinable - public func error(_ message: @autoclosure () -> String, metadata: @autoclosure () -> Logging.Metadata? = nil, error: Error? = nil, file: StaticString = #file, function: StaticString = #function, line: UInt = #line) { + public func error(_ message: @autoclosure () -> String, metadata: @autoclosure () -> Logger.Metadata? = nil, error: Error? = nil, file: StaticString = #file, function: StaticString = #function, line: UInt = #line) { self.log(level: .error, message: message, metadata: metadata, error: error, file: file, function: function, line: line) } @inlinable - public subscript(metadataKey metadataKey: String) -> Logging.Metadata.Value? { + public subscript(metadataKey metadataKey: String) -> Logger.Metadata.Value? { get { return self.handler[metadataKey: metadataKey] } @@ -76,7 +76,7 @@ public struct Logger { } @inlinable - public var metadata: Logging.Metadata { + public var metadata: Logger.Metadata { get { return self.handler.metadata } @@ -86,7 +86,7 @@ public struct Logger { } @inlinable - public var logLevel: Logging.Level { + public var logLevel: Logger.Level { get { return self.handler.logLevel } @@ -99,22 +99,18 @@ public struct Logger { // This is the logging system itself, it's mostly used to obtain loggers and to set the type of the `LogHandler` // implementation. public enum Logging { - private static let lock = ReadWriteLock() - private static var _factory: (String) -> LogHandler = StdoutLogger.init + fileprivate static let lock = ReadWriteLock() + fileprivate static var factory: (String) -> LogHandler = StdoutLogHandler.init // Configures which `LogHandler` to use in the application. public static func bootstrap(_ factory: @escaping (String) -> LogHandler) { - self.lock.withWriterLock { - self._factory = factory + lock.withWriterLock { + self.factory = factory } } - - public static func make(_ label: String) -> Logger { - return self.lock.withReaderLock { Logger(self._factory(label)) } - } } -extension Logging { +extension Logger { public typealias Metadata = [String: MetadataValue] public enum MetadataValue { @@ -130,19 +126,23 @@ extension Logging { case warning case error } + + public init(label: String) { + self = Logging.lock.withReaderLock { Logger(Logging.factory(label)) } + } } -extension Logging.Level: Comparable { - public static func < (lhs: Logging.Level, rhs: Logging.Level) -> Bool { +extension Logger.Level: Comparable { + public static func < (lhs: Logger.Level, rhs: Logger.Level) -> Bool { return lhs.rawValue < rhs.rawValue } } -// Extension has to be done on explicit type rather than Logging.Metadata.Value as workaround for: https://bugs.swift.org/browse/SR-9687 +// Extension has to be done on explicit type rather than Logger.Metadata.Value as workaround for: https://bugs.swift.org/browse/SR-9687 // Then we could write it as follows and it would work under Swift 5 and not only 4 as it does currently: -// extension Logging.Metadata.Value: Equatable { -extension Logging.MetadataValue: Equatable { - public static func == (lhs: Logging.Metadata.Value, rhs: Logging.Metadata.Value) -> Bool { +// extension Logger.Metadata.Value: Equatable { +extension Logger.MetadataValue: Equatable { + public static func == (lhs: Logger.Metadata.Value, rhs: Logger.Metadata.Value) -> Bool { switch (lhs, rhs) { case (.string(let lhs), .string(let rhs)): return lhs == rhs @@ -157,28 +157,16 @@ extension Logging.MetadataValue: Equatable { } /// Ships with the logging module, used to multiplex to multiple logging handlers -public final class MultiplexLogging { - private let factories: [(String) -> LogHandler] - - public init(_ factories: [(String) -> LogHandler]) { - self.factories = factories - } - - public func make(_ label: String) -> LogHandler { - return MultiplexLogHandler(handlers: self.factories.map { $0(label) }) - } -} - -private class MultiplexLogHandler: LogHandler { +public class MultiplexLogHandler: LogHandler { private let lock = Lock() private var handlers: [LogHandler] - public init(handlers: [LogHandler]) { + public init(_ handlers: [LogHandler]) { assert(handlers.count > 0) self.handlers = handlers } - public var logLevel: Logging.Level { + public var logLevel: Logger.Level { get { return self.handlers[0].logLevel } @@ -187,13 +175,13 @@ private class MultiplexLogHandler: LogHandler { } } - public func log(level: Logging.Level, message: String, metadata: Logging.Metadata?, error: Error?, file: StaticString, function: StaticString, line: UInt) { + public func log(level: Logger.Level, message: String, metadata: Logger.Metadata?, error: Error?, file: StaticString, function: StaticString, line: UInt) { self.handlers.forEach { handler in handler.log(level: level, message: message, metadata: metadata, error: error, file: file, function: function, line: line) } } - public var metadata: Logging.Metadata { + public var metadata: Logger.Metadata { get { return self.handlers[0].metadata } @@ -202,7 +190,7 @@ private class MultiplexLogHandler: LogHandler { } } - public subscript(metadataKey metadataKey: String) -> Logging.Metadata.Value? { + public subscript(metadataKey metadataKey: String) -> Logger.Metadata.Value? { get { return self.handlers[0].metadata[metadataKey] } @@ -223,13 +211,13 @@ private class MultiplexLogHandler: LogHandler { } /// Ships with the logging module, really boring just prints something using the `print` function -internal struct StdoutLogger: LogHandler { +internal struct StdoutLogHandler: LogHandler { private let lock = Lock() public init(label: String) {} - private var _logLevel: Logging.Level = .info - public var logLevel: Logging.Level { + private var _logLevel: Logger.Level = .info + public var logLevel: Logger.Level { get { return self.lock.withLock { self._logLevel } } @@ -241,18 +229,18 @@ internal struct StdoutLogger: LogHandler { } private var prettyMetadata: String? - private var _metadata = Logging.Metadata() { + private var _metadata = Logger.Metadata() { didSet { self.prettyMetadata = self.prettify(self._metadata) } } - public func log(level: Logging.Level, message: String, metadata: Logging.Metadata?, error: Error?, file: StaticString, function: StaticString, line: UInt) { + public func log(level: Logger.Level, message: String, metadata: Logger.Metadata?, error: Error?, file: StaticString, function: StaticString, line: UInt) { let prettyMetadata = metadata?.isEmpty ?? true ? self.prettyMetadata : self.prettify(self.metadata.merging(metadata!, uniquingKeysWith: { _, new in new })) print("\(self.timestamp()) \(level)\(prettyMetadata.map { " \($0)" } ?? "") \(message)\(error.map { " \($0)" } ?? "")") } - public var metadata: Logging.Metadata { + public var metadata: Logger.Metadata { get { return self.lock.withLock { self._metadata } } @@ -261,7 +249,7 @@ internal struct StdoutLogger: LogHandler { } } - public subscript(metadataKey metadataKey: String) -> Logging.Metadata.Value? { + public subscript(metadataKey metadataKey: String) -> Logger.Metadata.Value? { get { return self.lock.withLock { self._metadata[metadataKey] } } @@ -272,7 +260,7 @@ internal struct StdoutLogger: LogHandler { } } - private func prettify(_ metadata: Logging.Metadata) -> String? { + private func prettify(_ metadata: Logger.Metadata) -> String? { return !metadata.isEmpty ? metadata.map { "\($0)=\($1)" }.joined(separator: " ") : nil } @@ -289,8 +277,8 @@ internal struct StdoutLogger: LogHandler { } } -// Extension has to be done on explicit type rather than Logging.Metadata.Value as workaround for: https://bugs.swift.org/browse/SR-9687 -extension Logging.MetadataValue: ExpressibleByStringLiteral { +// 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) { @@ -298,7 +286,7 @@ extension Logging.MetadataValue: ExpressibleByStringLiteral { } } -extension Logging.MetadataValue: CustomStringConvertible { +extension Logger.MetadataValue: CustomStringConvertible { public var description: String { switch self { case .dictionary(let dict): @@ -311,34 +299,34 @@ extension Logging.MetadataValue: CustomStringConvertible { } } -// Extension has to be done on explicit type rather than Logging.Metadata.Value as workaround for: https://bugs.swift.org/browse/SR-9687 -extension Logging.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: ExpressibleByStringInterpolation { #if !compiler(>=5.0) - public init(stringInterpolation strings: Logging.Metadata.Value...) { + public init(stringInterpolation strings: Logger.Metadata.Value...) { self = .string(strings.map { $0.description }.reduce("", +)) } public init(stringInterpolationSegment expr: T) { self = .string(String(stringInterpolationSegment: expr)) - } + } #endif } -// Extension has to be done on explicit type rather than Logging.Metadata.Value as workaround for: https://bugs.swift.org/browse/SR-9687 -extension Logging.MetadataValue: ExpressibleByDictionaryLiteral { +// 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 { public typealias Key = String - public typealias Value = Logging.Metadata.Value + public typealias Value = Logger.Metadata.Value - public init(dictionaryLiteral elements: (String, Logging.Metadata.Value)...) { + public init(dictionaryLiteral elements: (String, Logger.Metadata.Value)...) { self = .dictionary(.init(uniqueKeysWithValues: elements)) } } -// Extension has to be done on explicit type rather than Logging.Metadata.Value as workaround for: https://bugs.swift.org/browse/SR-9687 -extension Logging.MetadataValue: ExpressibleByArrayLiteral { - public typealias ArrayLiteralElement = Logging.Metadata.Value +// 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: ExpressibleByArrayLiteral { + public typealias ArrayLiteralElement = Logger.Metadata.Value - public init(arrayLiteral elements: Logging.Metadata.Value...) { + public init(arrayLiteral elements: Logger.Metadata.Value...) { self = .array(elements) } } diff --git a/Tests/LoggingTests/GlobalLoggingTest.swift b/Tests/LoggingTests/GlobalLoggingTest.swift index c5323c3..819fab6 100644 --- a/Tests/LoggingTests/GlobalLoggingTest.swift +++ b/Tests/LoggingTests/GlobalLoggingTest.swift @@ -5,9 +5,9 @@ class GlobalLoggerTest: XCTestCase { func test1() throws { // bootstrap with our test logging impl let logging = TestLogging() - Logging.bootstrap(logging.make) + Logger.bootstrap(logging.make) // change test logging config to log traces and above - logging.config.set(value: Logging.Level.trace) + logging.config.set(value: Logger.Level.trace) // run our program Struct1().doSomething() // test results @@ -31,9 +31,9 @@ class GlobalLoggerTest: XCTestCase { func test2() throws { // bootstrap with our test logging impl let logging = TestLogging() - Logging.bootstrap(logging.make) + Logger.bootstrap(logging.make) // change test logging config to log errors and above - logging.config.set(value: Logging.Level.error) + logging.config.set(value: Logger.Level.error) // run our program Struct1().doSomething() // test results @@ -57,7 +57,7 @@ class GlobalLoggerTest: XCTestCase { func test3() throws { // bootstrap with our test logging impl let logging = TestLogging() - Logging.bootstrap(logging.make) + Logger.bootstrap(logging.make) // change test logging config logging.config.set(value: .warning) logging.config.set(key: "GlobalLoggerTest::Struct2", value: .info) @@ -84,7 +84,7 @@ class GlobalLoggerTest: XCTestCase { } private struct Struct1 { - private let logger = Logging.make("GlobalLoggerTest::Struct1") + private let logger = Logger(label: "GlobalLoggerTest::Struct1") func doSomething() { self.logger.trace("Struct1::doSomething") @@ -100,7 +100,7 @@ private struct Struct1 { } private struct Struct2 { - let logger = Logging.make("GlobalLoggerTest::Struct2") + let logger = Logger(label: "GlobalLoggerTest::Struct2") func doSomething() { self.logger.info("Struct2::doSomething") @@ -116,7 +116,7 @@ private struct Struct2 { } private struct Struct3 { - private let logger = Logging.make("GlobalLoggerTest::Struct3") + private let logger = Logger(label: "GlobalLoggerTest::Struct3") private let queue = DispatchQueue(label: "GlobalLoggerTest::Struct3") func doSomething() { diff --git a/Tests/LoggingTests/LocalLoggingTest.swift b/Tests/LoggingTests/LocalLoggingTest.swift index 405eee6..aab6730 100644 --- a/Tests/LoggingTests/LocalLoggingTest.swift +++ b/Tests/LoggingTests/LocalLoggingTest.swift @@ -5,9 +5,9 @@ class LocalLoggerTest: XCTestCase { func test1() throws { // bootstrap with our test logging impl let logging = TestLogging() - Logging.bootstrap(logging.make) + Logger.bootstrap(logging.make) // change test logging config to log traces and above - logging.config.set(value: Logging.Level.trace) + logging.config.set(value: Logger.Level.trace) // run our program let context = Context() Struct1().doSomething(context: context) @@ -32,9 +32,9 @@ class LocalLoggerTest: XCTestCase { func test2() throws { // bootstrap with our test logging impl let logging = TestLogging() - Logging.bootstrap(logging.make) + Logger.bootstrap(logging.make) // change test logging config to log errors and above - logging.config.set(value: Logging.Level.error) + logging.config.set(value: Logger.Level.error) // run our program let context = Context() Struct1().doSomething(context: context) @@ -59,16 +59,16 @@ class LocalLoggerTest: XCTestCase { // systems that follow the context pattern need to implement something like this private struct Context { - var logger = Logging.make("LocalLoggerTest::ContextLogger") + var logger = Logger(label: "LocalLoggerTest::ContextLogger") // since logger is a value type, we can reuse our copy to manage logLevel - var logLevel: Logging.Level { + var logLevel: Logger.Level { get { return self.logger.logLevel } set { self.logger.logLevel = newValue } } // since logger is a value type, we can reuse our copy to manage metadata - subscript(metadataKey: String) -> Logging.Metadata.Value? { + subscript(metadataKey: String) -> Logger.Metadata.Value? { get { return self.logger[metadataKey: metadataKey] } set { self.logger[metadataKey: metadataKey] = newValue } } diff --git a/Tests/LoggingTests/LoggingTest.swift b/Tests/LoggingTests/LoggingTest.swift index faf44ea..8a2ab2a 100644 --- a/Tests/LoggingTests/LoggingTest.swift +++ b/Tests/LoggingTests/LoggingTest.swift @@ -5,8 +5,8 @@ class LoggingTest: XCTestCase { func testAutoclosure() throws { // bootstrap with our test logging impl let logging = TestLogging() - Logging.bootstrap(logging.make) - var logger = Logging.make("test") + Logger.bootstrap(logging.make) + var logger = Logger(label: "test") logger.logLevel = .info logger.trace({ XCTFail("trace should not be called") @@ -36,8 +36,8 @@ class LoggingTest: XCTestCase { func testAutoclosureWithError() throws { // bootstrap with our test logging impl let logging = TestLogging() - Logging.bootstrap(logging.make) - var logger = Logging.make("test") + Logger.bootstrap(logging.make) + var logger = Logger(label: "test") logger.logLevel = .warning logger.trace({ XCTFail("trace should not be called") @@ -67,9 +67,9 @@ class LoggingTest: XCTestCase { func testWithError() throws { let logging = TestLogging() - Logging.bootstrap(logging.make) + Logger.bootstrap(logging.make) - let logger = Logging.make("test") + let logger = Logger(label: "test") logger.error("oh no!", error: TestError.boom) logging.history.assertExist(level: .error, message: "oh no!", error: TestError.boom) } @@ -78,9 +78,9 @@ class LoggingTest: XCTestCase { // bootstrap with our test logging impl let logging1 = TestLogging() let logging2 = TestLogging() - Logging.bootstrap(MultiplexLogging([logging1.make, logging2.make]).make) + Logger.bootstrap({ MultiplexLogHandler([logging1.make(label: $0), logging2.make(label: $0)]) }) - var logger = Logging.make("test") + var logger = Logger(label: "test") logger.logLevel = .warning logger.info("hello world?") logger[metadataKey: "foo"] = "bar" @@ -97,8 +97,8 @@ class LoggingTest: XCTestCase { func testDictionaryMetadata() { let testLogging = TestLogging() - Logging.bootstrap(testLogging.make) - var logger = Logging.make("\(#function)") + Logger.bootstrap(testLogging.make) + var logger = Logger(label: "\(#function)") logger[metadataKey: "foo"] = ["bar": "buz"] logger[metadataKey: "empty-dict"] = [:] logger[metadataKey: "nested-dict"] = ["l1key": ["l2key": ["l3key": "l3value"]]] @@ -112,8 +112,8 @@ class LoggingTest: XCTestCase { func testListMetadata() { let testLogging = TestLogging() - Logging.bootstrap(testLogging.make) - var logger = Logging.make("\(#function)") + Logger.bootstrap(testLogging.make) + var logger = Logger(label: "\(#function)") logger[metadataKey: "foo"] = ["bar", "buz"] logger[metadataKey: "empty-list"] = [] logger[metadataKey: "nested-list"] = ["l1str", ["l2str1", "l2str2"]] @@ -132,8 +132,8 @@ class LoggingTest: XCTestCase { func testAutoClosuresAreNotForcedUnlessNeeded() { let testLogging = TestLogging() - Logging.bootstrap(testLogging.make) - var logger = Logging.make("\(#function)") + Logger.bootstrap(testLogging.make) + var logger = Logger(label: "\(#function)") logger.logLevel = .error logger.debug(self.dontEvaluateThisString(), metadata: ["foo": "\(self.dontEvaluateThisString())"]) @@ -145,8 +145,8 @@ class LoggingTest: XCTestCase { func testLocalMetadata() { let testLogging = TestLogging() - Logging.bootstrap(testLogging.make) - var logger = Logging.make("\(#function)") + Logger.bootstrap(testLogging.make) + var logger = Logger(label: "\(#function)") logger.info("hello world!", metadata: ["foo": "bar"]) logger[metadataKey: "bar"] = "baz" logger[metadataKey: "baz"] = "qux" diff --git a/Tests/LoggingTests/MDCTest.swift b/Tests/LoggingTests/MDCTest.swift index 805022d..102e7f0 100644 --- a/Tests/LoggingTests/MDCTest.swift +++ b/Tests/LoggingTests/MDCTest.swift @@ -6,7 +6,7 @@ class MDCTest: XCTestCase { func test1() throws { // bootstrap with our test logger let logging = TestLogging() - Logging.bootstrap(logging.make) + Logger.bootstrap(logging.make) // run the program MDC.global["foo"] = "bar" let group = DispatchGroup() diff --git a/Tests/LoggingTests/TestLogger.swift b/Tests/LoggingTests/TestLogger.swift index 9a6f520..01aa070 100644 --- a/Tests/LoggingTests/TestLogger.swift +++ b/Tests/LoggingTests/TestLogger.swift @@ -7,14 +7,14 @@ internal struct TestLogging { private let recorder = Recorder() // shared among loggers func make(label: String) -> LogHandler { - return TestLogger(label: label, config: self.config, recorder: self.recorder) + return TestLogHandler(label: label, config: self.config, recorder: self.recorder) } var config: Config { return self._config } var history: History { return self.recorder } } -internal struct TestLogger: LogHandler { +internal struct TestLogHandler: LogHandler { private let logLevelLock = NSLock() private let metadataLock = NSLock() private let recorder: Recorder @@ -26,11 +26,11 @@ internal struct TestLogger: LogHandler { self.label = label self.config = config self.recorder = recorder - self.logger = Logger(StdoutLogger(label: label)) + self.logger = Logger(StdoutLogHandler(label: label)) self.logger.logLevel = .trace } - func log(level: Logging.Level, message: String, metadata: Logging.Metadata?, error: Error?, file: StaticString, function: StaticString, line: UInt) { + func log(level: Logger.Level, message: String, metadata: Logger.Metadata?, error: Error?, file: StaticString, function: StaticString, line: UInt) { let metadata = (self._metadataSet ? self.metadata : MDC.global.metadata).merging(metadata ?? [:], uniquingKeysWith: { _, new in new }) var l = logger // local copy since we gonna override its metadata l.metadata = metadata @@ -38,8 +38,8 @@ internal struct TestLogger: LogHandler { self.recorder.record(level: level, metadata: metadata, message: message, error: error) } - private var _logLevel: Logging.Level? - var logLevel: Logging.Level { + private var _logLevel: Logger.Level? + var logLevel: Logger.Level { get { // get from config unless set return self.logLevelLock.withLock { self._logLevel } ?? self.config.get(key: self.label) @@ -50,13 +50,13 @@ internal struct TestLogger: LogHandler { } private var _metadataSet = false - private var _metadata = Logging.Metadata() { + private var _metadata = Logger.Metadata() { didSet { self._metadataSet = true } } - public var metadata: Logging.Metadata { + public var metadata: Logger.Metadata { get { // return self.logger.metadata return self.metadataLock.withLock { self._metadata } @@ -68,7 +68,7 @@ internal struct TestLogger: LogHandler { } // TODO: would be nice to delegate to local copy of logger but StdoutLogger is a reference type. why? - subscript(metadataKey metadataKey: Logging.Metadata.Key) -> Logging.Metadata.Value? { + subscript(metadataKey metadataKey: Logger.Metadata.Key) -> Logger.Metadata.Value? { get { // return self.logger[metadataKey: metadataKey] return self.metadataLock.withLock { self._metadata[metadataKey] } @@ -86,20 +86,20 @@ internal class Config { private static let ALL = "*" private let lock = NSLock() - private var storage = [String: Logging.Level]() + private var storage = [String: Logger.Level]() - func get(key: String) -> Logging.Level { - return self.get(key) ?? self.get(Config.ALL) ?? Logging.Level.trace + func get(key: String) -> Logger.Level { + return self.get(key) ?? self.get(Config.ALL) ?? Logger.Level.trace } - func get(_ key: String) -> Logging.Level? { + func get(_ key: String) -> Logger.Level? { guard let value = (self.lock.withLock { self.storage[key] }) else { return nil } return value } - func set(key: String = Config.ALL, value: Logging.Level) { + func set(key: String = Config.ALL, value: Logger.Level) { self.lock.withLock { self.storage[key] = value } } @@ -112,7 +112,7 @@ internal class Recorder: History { private let lock = NSLock() private var _entries = [LogEntry]() - func record(level: Logging.Level, metadata: Logging.Metadata?, message: String, error: Error?) { + func record(level: Logger.Level, metadata: Logger.Metadata?, message: String, error: Error?) { return self.lock.withLock { self._entries.append(LogEntry(level: level, metadata: metadata, message: message, error: error)) } @@ -128,7 +128,7 @@ internal protocol History { } internal extension History { - func atLevel(level: Logging.Level) -> [LogEntry] { + func atLevel(level: Logger.Level) -> [LogEntry] { return self.entries.filter { entry in level == entry.level } @@ -156,24 +156,24 @@ internal extension History { } internal struct LogEntry { - let level: Logging.Level - let metadata: Logging.Metadata? + let level: Logger.Level + let metadata: Logger.Metadata? let message: String let error: Error? } extension History { - func assertExist(level: Logging.Level, message: String, metadata: Logging.Metadata? = nil, error: Error? = nil, file: StaticString = #file, line: UInt = #line) { + func assertExist(level: Logger.Level, message: String, metadata: Logger.Metadata? = nil, error: Error? = nil, file: StaticString = #file, line: UInt = #line) { let entry = self.find(level: level, message: message, metadata: metadata, error: error) XCTAssertNotNil(entry, "entry not found: \(level), \(String(describing: metadata)), \(message) \(String(describing: error))", file: file, line: line) } - func assertNotExist(level: Logging.Level, message: String, metadata: Logging.Metadata? = nil, error: Error? = nil, file: StaticString = #file, line: UInt = #line) { + func assertNotExist(level: Logger.Level, message: String, metadata: Logger.Metadata? = nil, error: Error? = nil, file: StaticString = #file, line: UInt = #line) { let entry = self.find(level: level, message: message, metadata: metadata, error: error) XCTAssertNil(entry, "entry was found: \(level), \(String(describing: metadata)), \(message) \(String(describing: error))", file: file, line: line) } - func find(level: Logging.Level, message: String, metadata: Logging.Metadata? = nil, error: Error?) -> LogEntry? { + func find(level: Logger.Level, message: String, metadata: Logger.Metadata? = nil, error: Error?) -> LogEntry? { return self.entries.first { entry in entry.level == level && entry.message == message && @@ -185,13 +185,13 @@ extension History { public class MDC { private let lock = NSLock() - private var storage = [UInt32: Logging.Metadata]() + private var storage = [UInt32: Logger.Metadata]() public static var global = MDC() private init() {} - public subscript(metadataKey: String) -> Logging.Metadata.Value? { + public subscript(metadataKey: String) -> Logger.Metadata.Value? { get { return self.lock.withLock { self.storage[self.threadId]?[metadataKey] @@ -200,14 +200,14 @@ public class MDC { set { self.lock.withLock { if nil == self.storage[self.threadId] { - self.storage[self.threadId] = Logging.Metadata() + self.storage[self.threadId] = Logger.Metadata() } self.storage[self.threadId]![metadataKey] = newValue } } } - public var metadata: Logging.Metadata { + public var metadata: Logger.Metadata { return self.lock.withLock { self.storage[self.threadId] ?? [:] } @@ -219,7 +219,7 @@ public class MDC { } } - public func with(metadata: Logging.Metadata, _ body: () throws -> Void) rethrows { + public func with(metadata: Logger.Metadata, _ body: () throws -> Void) rethrows { metadata.forEach { self[$0] = $1 } defer { metadata.keys.forEach { self[$0] = nil } @@ -227,7 +227,7 @@ public class MDC { try body() } - public func with(metadata: Logging.Metadata, _ body: () throws -> T) rethrows -> T { + public func with(metadata: Logger.Metadata, _ body: () throws -> T) rethrows -> T { metadata.forEach { self[$0] = $1 } defer { metadata.keys.forEach { self[$0] = nil } @@ -258,7 +258,7 @@ internal extension NSLock { } internal struct TestLibrary { - private let logger = Logging.make("TestLibrary") + private let logger = Logger(label: "TestLibrary") private let queue = DispatchQueue(label: "TestLibrary") public init() {}