From 9027df5f03de9d76be3d320bce3bcf5cc2faa05d Mon Sep 17 00:00:00 2001 From: tomer doron Date: Sat, 5 Jan 2019 01:11:30 -0800 Subject: [PATCH] refactor examples and remove dependecy on foundation motivation: * due to the low level nature of the library we prefer not to force-load foundation * help reviewers diffrentiate between examples of usage vs implementation, and add more realistic usage and implementations examples changes: * remove foundation from Logging module, replace with c based locks and time functions * rewrite usage examples to be more realistic * add example of an implementation that writes to files * add example of an implementation that is config driven * rename warn -> warning --- Package.swift | 6 +- .../ExampleImplementation/ConfigLogging.swift | 92 ++++++++++ .../ExampleImplementation/FileLogging.swift | 78 +++++++++ .../ExampleImplementation/SimpleLogger.swift | 78 +++++++++ .../ExampleImplementation/SimpleLogging.swift | 48 +++++ Sources/ExampleUsage/ConfigExample.swift | 21 +++ Sources/ExampleUsage/ContextBasedSystem.swift | 97 ++++++++++ .../GlobalLoggerBasedSystem.swift | 82 +++++++++ .../ExampleUsage/LocalLoggerBasedSystem.swift | 90 ++++++++++ Sources/ExampleUsage/MUXExample.swift | 18 ++ Sources/ExampleUsage/RandomLibrary.swift | 27 +++ Sources/ExampleUsage/main.swift | 19 ++ Sources/Examples/ExampleLoggerImpl.swift | 141 --------------- .../ExplicitLoggerPassingExample.swift | 35 ---- .../Examples/LoggerPerSubsystemExample.swift | 49 ------ Sources/Examples/MUXExample.swift | 12 -- Sources/Examples/OneGlobalLoggerExample.swift | 25 --- Sources/Examples/RandomExample.swift | 66 ------- Sources/Examples/main.swift | 18 -- Sources/Logging/Locks.swift | 165 ++++++++++++++++++ Sources/Logging/Logging.swift | 42 +++-- Tests/LoggingTests/GlobalLoggingTest.swift | 10 +- Tests/LoggingTests/LocalLoggingTest.swift | 8 +- Tests/LoggingTests/LoggingTest.swift | 8 +- Tests/LoggingTests/TestLogger.swift | 4 +- 25 files changed, 858 insertions(+), 381 deletions(-) create mode 100644 Sources/ExampleImplementation/ConfigLogging.swift create mode 100644 Sources/ExampleImplementation/FileLogging.swift create mode 100644 Sources/ExampleImplementation/SimpleLogger.swift create mode 100644 Sources/ExampleImplementation/SimpleLogging.swift create mode 100644 Sources/ExampleUsage/ConfigExample.swift create mode 100644 Sources/ExampleUsage/ContextBasedSystem.swift create mode 100644 Sources/ExampleUsage/GlobalLoggerBasedSystem.swift create mode 100644 Sources/ExampleUsage/LocalLoggerBasedSystem.swift create mode 100644 Sources/ExampleUsage/MUXExample.swift create mode 100644 Sources/ExampleUsage/RandomLibrary.swift create mode 100644 Sources/ExampleUsage/main.swift delete mode 100644 Sources/Examples/ExampleLoggerImpl.swift delete mode 100644 Sources/Examples/ExplicitLoggerPassingExample.swift delete mode 100644 Sources/Examples/LoggerPerSubsystemExample.swift delete mode 100644 Sources/Examples/MUXExample.swift delete mode 100644 Sources/Examples/OneGlobalLoggerExample.swift delete mode 100644 Sources/Examples/RandomExample.swift delete mode 100644 Sources/Examples/main.swift create mode 100644 Sources/Logging/Locks.swift diff --git a/Package.swift b/Package.swift index a614a6d..a036cf4 100644 --- a/Package.swift +++ b/Package.swift @@ -16,9 +16,13 @@ let package = Package( dependencies: [] ), .target( - name: "Examples", + name: "ExampleImplementation", dependencies: ["Logging"] ), + .target( + name: "ExampleUsage", + dependencies: ["Logging", "ExampleImplementation"] + ), .testTarget( name: "LoggingTests", dependencies: ["Logging"] diff --git a/Sources/ExampleImplementation/ConfigLogging.swift b/Sources/ExampleImplementation/ConfigLogging.swift new file mode 100644 index 0000000..38201ce --- /dev/null +++ b/Sources/ExampleImplementation/ConfigLogging.swift @@ -0,0 +1,92 @@ +// +// 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 final class ConfigLogging { + public var config = Config(defaultLogLevel: LogLevel.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: LogLevel, message: String, file _: String, function _: String, line _: UInt) { + self.logger.log(level: level, message: message) { text in + print(text) + } + } + + public var logLevel: LogLevel { + get { return self.logger.logLevel ?? self.config.get(key: self.logger.label) } + set { self.logger.logLevel = newValue } + } + + public var metadata: LoggingMetadata? { + get { return self.logger.metadata } + set { self.logger.metadata = newValue } + } + + public subscript(metadataKey metadataKey: String) -> String? { + 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: LogLevel]() + private var defaultLogLevel: LogLevel + + init(defaultLogLevel: LogLevel) { + self.defaultLogLevel = defaultLogLevel + } + + func get(key: String) -> LogLevel { + return self.get(key) ?? self.get(Config.ALL) ?? self.defaultLogLevel + } + + func get(_ key: String) -> LogLevel? { + return self.lock.withLock { self.storage[key] } + } + + public func set(key: String, value: LogLevel) { + self.lock.withLock { self.storage[key] = value } + } + + public func set(value: LogLevel) { + 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/FileLogging.swift b/Sources/ExampleImplementation/FileLogging.swift new file mode 100644 index 0000000..560eaee --- /dev/null +++ b/Sources/ExampleImplementation/FileLogging.swift @@ -0,0 +1,78 @@ +// +// 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 final class FileLogging { + private let defaultLogLevel = LogLevel.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: LogLevel + private let fileHandler: FileHandler + + public init(label: String, defaultLogLevel: LogLevel, fileHandler: FileHandler) { + self.logger = SimpleLogger(label: label) + self.defaultLogLevel = defaultLogLevel + self.fileHandler = fileHandler + } + + public func log(level: LogLevel, message: String, file _: String, function _: String, line _: UInt) { + self.logger.log(level: level, message: message) { text in + self.fileHandler._write(text) + } + } + + public var logLevel: LogLevel { + get { return self.logger.logLevel ?? self.defaultLogLevel } + set { self.logger.logLevel = newValue } + } + + public var metadata: LoggingMetadata? { + get { return self.logger.metadata } + set { self.logger.metadata = newValue } + } + + public subscript(metadataKey metadataKey: String) -> String? { + 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/SimpleLogger.swift b/Sources/ExampleImplementation/SimpleLogger.swift new file mode 100644 index 0000000..be6fd59 --- /dev/null +++ b/Sources/ExampleImplementation/SimpleLogger.swift @@ -0,0 +1,78 @@ +// +// THIS IS NOT PART OF THE PITCH, JUST AN EXAMPLE HOW A LOGGER IMPLEMENTATION LOOKS LIKE +// + +import Foundation +import Logging + +// helper class to keep things DRY +internal final class SimpleLogger { + let label: String + private var _logLevel: LogLevel? + private let formatter: DateFormatter + private let lock = NSLock() + + public init(label: String) { + self.label = label + let formatter = DateFormatter() + formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" + formatter.locale = Locale(identifier: "en_US") + formatter.calendar = Calendar(identifier: .gregorian) + self.formatter = formatter + } + + public func log(level: LogLevel, message: String, printer: (String) -> Void) { + printer("[\(self.label)] \(self.formatter.string(from: Date()))\(self.prettyMetadata.map { " \($0)" } ?? "") \(level): \(message)") + } + + public var logLevel: LogLevel? { + get { + return self.lock.withLock { self._logLevel } + } + set { + self.lock.withLock { + self._logLevel = newValue + } + } + } + + private var prettyMetadata: String? + private var _metadata: LoggingMetadata? { + didSet { + self.prettyMetadata = !(self._metadata?.isEmpty ?? true) ? self._metadata!.map { "\($0)=\($1)" }.joined(separator: " ") : nil + } + } + + public var metadata: LoggingMetadata? { + get { + return self.lock.withLock { self._metadata } + } + set { + self.lock.withLock { self._metadata = newValue } + } + } + + public subscript(metadataKey metadataKey: String) -> String? { + get { + return self.lock.withLock { self._metadata?[metadataKey] } + } + set { + self.lock.withLock { + if nil == self._metadata { + self._metadata = [:] + } + self._metadata![metadataKey] = newValue + } + } + } +} + +private extension NSLock { + func withLock(_ body: () -> T) -> T { + self.lock() + defer { + self.unlock() + } + return body() + } +} diff --git a/Sources/ExampleImplementation/SimpleLogging.swift b/Sources/ExampleImplementation/SimpleLogging.swift new file mode 100644 index 0000000..df94808 --- /dev/null +++ b/Sources/ExampleImplementation/SimpleLogging.swift @@ -0,0 +1,48 @@ +// +// 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 final class SimpleLogging { + private let defaultLogLevel = LogLevel.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: LogLevel + + public init(label: String, defaultLogLevel: LogLevel) { + self.logger = SimpleLogger(label: label) + self.defaultLogLevel = defaultLogLevel + } + + public func log(level: LogLevel, message: String, file _: String, function _: String, line _: UInt) { + self.logger.log(level: level, message: message) { text in + print(text) + } + } + + public var logLevel: LogLevel { + get { return self.logger.logLevel ?? self.defaultLogLevel } + set { self.logger.logLevel = newValue } + } + + public var metadata: LoggingMetadata? { + get { return self.logger.metadata } + set { self.logger.metadata = newValue } + } + + public subscript(metadataKey metadataKey: String) -> String? { + get { return self.logger[metadataKey: metadataKey] } + set { self.logger[metadataKey: metadataKey] = newValue } + } + } +} diff --git a/Sources/ExampleUsage/ConfigExample.swift b/Sources/ExampleUsage/ConfigExample.swift new file mode 100644 index 0000000..d15c6b0 --- /dev/null +++ b/Sources/ExampleUsage/ConfigExample.swift @@ -0,0 +1,21 @@ +// +// THIS IS NOT PART OF THE PITCH, JUST AN EXAMPLE HOW A LOGGER USAGE LOOKS LIKE +// + +import ExampleImplementation +import Foundation +import Logging + +enum ConfigExample { + static func main() { + // boostrap with our config based sample implementations + let logging = ConfigLogging() + Logging.bootstrap(logging.make) + // run the example + let logger = Logging.make("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) + logger.trace("hello world!") + } +} diff --git a/Sources/ExampleUsage/ContextBasedSystem.swift b/Sources/ExampleUsage/ContextBasedSystem.swift new file mode 100644 index 0000000..ef38432 --- /dev/null +++ b/Sources/ExampleUsage/ContextBasedSystem.swift @@ -0,0 +1,97 @@ +// +// THIS IS NOT PART OF THE PITCH, JUST AN EXAMPLE HOW A LOGGER USAGE LOOKS LIKE +// + +import ExampleImplementation +import Foundation +import Logging + +// this is a contrived example of a context based system, ie a system that explictly passes a context object around +// in this example we include a logger in the context object +// we also allow users to set metadata on the context object and reuse that as the metadata for logging +enum ContextBasedSystem { + static func main() { + // boostrap with our sample implementation + let logging = SimpleLogging() + Logging.bootstrap(logging.make) + // run the example + for i in 1 ... 2 { + print("---------------------------- processing request #\(i) ----------------------------") + let context = Context(metadata: ["requestId": UUID().uuidString]) // contrived context + Foo().doSomething(context: context, requestNumnber: i) + } + } + + struct Context { + var logger = Logging.make("ContextLogger") + + init(metadata: [String: String] = [:]) { + 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) -> String? { + get { return self.logger[metadataKey: metadataKey] } + set { self.logger[metadataKey: metadataKey] = newValue } + } + } + + class Foo { + func doSomething(context: Context, requestNumnber: Int) { + var c = context // context is a value type, changes only effect this instance + if 0 == requestNumnber % 2 { + // debug verbosely every 2nd request + c.logger.logLevel = .trace + } + c.logger.info("\(self)::doSomething") + self.doSomethingElse(context: c) + c.logger.info("\(self)::doSomething::end") + } + + private func doSomethingElse(context: Context) { + var c = context // context is a value type, changes only effect this instance + c["foo"] = "bar" + c.logger.info("\(self)::doSomethingElse") + c.logger.trace("\(self)::doSomethingElse:someDebugInfo") + Bar().doSomething(context: c) + c.logger.info("\(self)::doSomethingElse::end") + } + } + + class Bar { + func doSomething(context: Context) { + var c = context // context is a value type, changes only effect this instance + c["bar"] = "baz" + c.logger.info("\(self)::doSomething") + c.logger.trace("\(self)::doSomething:someDebugInfo") + Baz().doSomething(context: c) + c.logger.info("\(self)::doSomething::end") + } + } + + class Baz { + private let queue = DispatchQueue(label: "ContextBasedSystem::Baz") + + func doSomething(context: Context) { + context.logger.info("\(self)::doSomething") + context.logger.trace("\(self)::doSomething:someDebugInfo") + let group = DispatchGroup() + group.enter() + queue.async { + context.logger.info("\(self)::doSomethingAsync") + // since the library does not know about the context it will loose the metadata + let library = RandomLibrary() + library.doSomething() + library.doSomethingAsync { + group.leave() + } + } + group.wait() + + var l = context.logger // logger is a value type, changes only effect this instance + l[metadataKey: "baz"] = "qux" + l.info("\(self)::doSomething::Local") + context.logger.info("\(self)::doSomething::end") + } + } +} diff --git a/Sources/ExampleUsage/GlobalLoggerBasedSystem.swift b/Sources/ExampleUsage/GlobalLoggerBasedSystem.swift new file mode 100644 index 0000000..452ebc3 --- /dev/null +++ b/Sources/ExampleUsage/GlobalLoggerBasedSystem.swift @@ -0,0 +1,82 @@ +// +// THIS IS NOT PART OF THE PITCH, JUST AN EXAMPLE HOW A LOGGER USAGE LOOKS LIKE +// + +import ExampleImplementation +import Foundation +import Logging + +var logger = Logging.make("GlobalLogger") + +// this is a contrived example of a system that shares one global logger +enum GlobalLoggerBasedSystem { + static func main() { + // boostrap with our sample implementation + let logging = SimpleLogging() + Logging.bootstrap(logging.make) + // run the example + for i in 1 ... 2 { + print("---------------------------- processing request #\(i) ----------------------------") + logger[metadataKey: "requestId"] = UUID().uuidString + Foo().doSomething(requestNumnber: i) + } + } + + class Foo { + func doSomething(requestNumnber: Int) { + if 0 == requestNumnber % 2 { + // debug verbosely every 2nd request + logger.logLevel = .trace + } + logger.info("\(self)::doSomething") + self.doSomethingElse() + logger.info("\(self)::doSomething::end") + } + + private func doSomethingElse() { + logger[metadataKey: "foo"] = "bar" + logger.info("\(self)::doSomethingElse") + logger.trace("\(self)::doSomethingElse:someDebugInfo") + Bar().doSomething() + logger.info("\(self)::doSomethingElse::end") + logger[metadataKey: "foo"] = nil + } + } + + class Bar { + func doSomething() { + logger[metadataKey: "bar"] = "baz" + logger.info("\(self)::doSomething") + logger.trace("\(self)::doSomething:someDebugInfo") + Baz().doSomething() + logger.info("\(self)::doSomething::end") + logger[metadataKey: "bar"] = nil + } + } + + class Baz { + private let queue = DispatchQueue(label: "GlobalLoggerBasedSystem::Baz") + + func doSomething() { + logger.info("\(self)::doSomething") + logger.trace("\(self)::doSomething:someDebugInfo") + let group = DispatchGroup() + group.enter() + queue.async { + logger.info("\(self)::doSomethingAsync") + // since the library does not know about the context it will loose the metadata + let library = RandomLibrary() + library.doSomething() + library.doSomethingAsync { + group.leave() + } + } + group.wait() + + var l = logger // logger is a value type, changes only effect this instance + l[metadataKey: "baz"] = "qux" + l.info("\(self)::doSomething::Local") + logger.info("\(self)::doSomething::end") + } + } +} diff --git a/Sources/ExampleUsage/LocalLoggerBasedSystem.swift b/Sources/ExampleUsage/LocalLoggerBasedSystem.swift new file mode 100644 index 0000000..6579b85 --- /dev/null +++ b/Sources/ExampleUsage/LocalLoggerBasedSystem.swift @@ -0,0 +1,90 @@ +// +// THIS IS NOT PART OF THE PITCH, JUST AN EXAMPLE HOW A LOGGER USAGE LOOKS LIKE +// + +import ExampleImplementation +import Foundation +import Logging + +// this is a contrived example of a system where each component obtain its own logger +enum LocalLoggerBasedSystem { + static func main() { + // boostrap with our sample implementation + let logging = SimpleLogging() + Logging.bootstrap(logging.make) + // run the example + for i in 1 ... 2 { + print("---------------------------- processing request #\(i) ----------------------------") + Foo().doSomething(requestNumnber: i) + } + } + + class Foo { + private var logger = Logging.make("LocalLoggerBasedSystem::Foo") + + func doSomething(requestNumnber: Int) { + if 0 == requestNumnber % 2 { + // debug verbosely every 2nd request + self.logger.logLevel = .trace + } + self.logger.info("\(self)::doSomething") + self.doSomethingElse(requestNumnber: requestNumnber) + self.logger.info("\(self)::doSomething::end") + } + + private func doSomethingElse(requestNumnber: Int) { + self.logger[metadataKey: "foo"] = "bar" // logger is a value type, changes only effect this instance + self.logger.info("\(self)::doSomethingElse") + self.logger.trace("\(self)::doSomethingElse:someDebugInfo") + Bar().doSomething(requestNumnber: requestNumnber) + self.logger.info("\(self)::doSomethingElse::end") + } + } + + class Bar { + private var logger = Logging.make("LocalLoggerBasedSystem::Bar") + + func doSomething(requestNumnber: Int) { + if 0 == requestNumnber % 2 { + // debug verbosely every 2nd request + self.logger.logLevel = .trace + } + self.logger[metadataKey: "bar"] = "baz" // logger is a value type, changes only effect this instance + self.logger.info("\(self)::doSomething") + self.logger.trace("\(self)::doSomething:someDebugInfo") + Baz().doSomething(requestNumnber: requestNumnber) + self.logger.info("\(self)::doSomething::end") + } + } + + class Baz { + private var logger = Logging.make("LocalLoggerBasedSystem::Baz") + private let queue = DispatchQueue(label: "LocalLoggerBasedSystem::Baz") + + func doSomething(requestNumnber: Int) { + if 0 == requestNumnber % 2 { + // debug verbosely every 2nd request + self.logger.logLevel = .trace + } + self.logger.info("\(self)::doSomething") + self.logger.trace("\(self)::doSomething:someDebugInfo") + let group = DispatchGroup() + group.enter() + queue.async { + self.logger.info("\(self)::doSomethingAsync") + // since the library does not know about the context it will loose the metadata + let library = RandomLibrary() + library.doSomething() + library.doSomethingAsync { + group.leave() + } + } + group.wait() + + var l = logger // logger is a value type, changes only effect this instance + l[metadataKey: "baz"] = "qux" + l.info("\(self)::doSomething::Local") + logger.info("\(self)::doSomething::end") + } + } +} diff --git a/Sources/ExampleUsage/MUXExample.swift b/Sources/ExampleUsage/MUXExample.swift new file mode 100644 index 0000000..bcac82e --- /dev/null +++ b/Sources/ExampleUsage/MUXExample.swift @@ -0,0 +1,18 @@ +// +// THIS IS NOT PART OF THE PITCH, JUST AN EXAMPLE HOW A LOGGER USAGE LOOKS LIKE +// + +import ExampleImplementation +import Foundation +import Logging + +enum MUXExample { + static func main() { + // boostrap with two of our sample implementations + let logging = MultiplexLogging([SimpleLogging().make, FileLogging().make]) + Logging.bootstrap(logging.make) + // run the example + let logger = Logging.make("com.example.TestApp") + logger.info("hello world!") + } +} diff --git a/Sources/ExampleUsage/RandomLibrary.swift b/Sources/ExampleUsage/RandomLibrary.swift new file mode 100644 index 0000000..cd0f02c --- /dev/null +++ b/Sources/ExampleUsage/RandomLibrary.swift @@ -0,0 +1,27 @@ +// +// THIS IS NOT PART OF THE PITCH, JUST AN EXAMPLE HOW A LOGGER USAGE LOOKS LIKE +// + +import Foundation +import Logging + +// this is a contrived example of a 3rd party library that is used by the other examples +// 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 queue = DispatchQueue(label: "RandomLibrary") + + public init() {} + + public func doSomething() { + self.logger.info("doSomething") + } + + public func doSomethingAsync(completion: @escaping () -> Void) { + self.queue.asyncAfter(deadline: .now() + 0.1) { + self.logger.info("doSomethingAsync") + completion() + } + } +} diff --git a/Sources/ExampleUsage/main.swift b/Sources/ExampleUsage/main.swift new file mode 100644 index 0000000..6b072e4 --- /dev/null +++ b/Sources/ExampleUsage/main.swift @@ -0,0 +1,19 @@ +print() +print("##### global logger based system #####") +GlobalLoggerBasedSystem.main() + +print() +print("##### local logger based system #####") +LocalLoggerBasedSystem.main() + +print() +print("##### context based system #####") +ContextBasedSystem.main() + +print() +print("##### multiplexiing to multiple logging implementations #####") +MUXExample.main() + +print() +print("##### config based logging implementations #####") +ConfigExample.main() diff --git a/Sources/Examples/ExampleLoggerImpl.swift b/Sources/Examples/ExampleLoggerImpl.swift deleted file mode 100644 index 4439203..0000000 --- a/Sources/Examples/ExampleLoggerImpl.swift +++ /dev/null @@ -1,141 +0,0 @@ -// -// THIS IS NOT PART OF THE PITCH, JUST AN EXAMPLE HOW A LOGGER IMPLEMENTATION LOOKS LIKE -// - -import Foundation -import Logging - -private extension NSLock { - func withLock(_ body: () -> T) -> T { - self.lock() - defer { - self.unlock() - } - return body() - } -} - -public struct ExampleValueLoggerImplementation: LogHandler { - private var _metadata: LoggingMetadata = [:] - - public init(label _: String) {} - - public func log(level: LogLevel, message: String, file _: String, function _: String, line _: UInt) { - print("\(self.formatLevel(level)): \(message) \(self.metadata?.description ?? "")") - } - - private func formatLevel(_ level: LogLevel) -> String { - switch level { - case .error: - return "ERRO" - case .warn: - return "WARN" - case .info: - return "info" - case .debug: - return "dbug" - case .trace: - return "trce" - } - } - - public subscript(metadataKey metadataKey: LoggingMetadata.Key) -> LoggingMetadata.Value? { - get { - return self._metadata[metadataKey] - } - set(newValue) { - self._metadata[metadataKey] = newValue - } - } - - public var metadata: LoggingMetadata? { - get { - return self._metadata - } - set { - if let newValue = newValue { - self._metadata = newValue - } else { - self._metadata.removeAll() - } - } - } - - public var logLevel: LogLevel = .info -} - -public final class ExampleLoggerImplementation: LogHandler { - private let formatter: DateFormatter - private let label: String - private let lock = NSLock() - - private var _logLevel: LogLevel = .info - public var logLevel: LogLevel { - get { - return self.lock.withLock { self._logLevel } - } - set { - self.lock.withLock { - self._logLevel = newValue - } - } - } - - public init(label: String) { - self.label = label - let formatter = DateFormatter() - formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" - formatter.locale = Locale(identifier: "en_US") - formatter.calendar = Calendar(identifier: .gregorian) - self.formatter = formatter - } - - private func formatLevel(_ level: LogLevel) -> String { - switch level { - case .error: - return "ERRO" - case .warn: - return "WARN" - case .info: - return "info" - case .debug: - return "dbug" - case .trace: - return "trce" - } - } - - public func log(level: LogLevel, message: String, file _: String, function _: String, line _: UInt) { - print("\(self.formatter.string(from: Date()))\(self.prettyMetadata.map { " \($0)" } ?? "") \(self.formatLevel(level)): \(message)") - } - - private var prettyMetadata: String? - private var _metadata: LoggingMetadata? { - didSet { - self.prettyMetadata = !(self._metadata?.isEmpty ?? true) ? self._metadata!.map { "\($0)=\($1)" }.joined(separator: " ") : nil - } - } - - public var metadata: LoggingMetadata? { - get { - return self.lock.withLock { self._metadata } - } - set { - self.lock.withLock { self._metadata = newValue } - } - } - - public subscript(metadataKey metadataKey: String) -> String? { - get { - return self.lock.withLock { self._metadata?[metadataKey] } - } - set { - self.lock.withLock { - if nil == self._metadata { - self._metadata = [:] - } - self._metadata![metadataKey] = newValue - } - } - } -} diff --git a/Sources/Examples/ExplicitLoggerPassingExample.swift b/Sources/Examples/ExplicitLoggerPassingExample.swift deleted file mode 100644 index 59b6569..0000000 --- a/Sources/Examples/ExplicitLoggerPassingExample.swift +++ /dev/null @@ -1,35 +0,0 @@ -import Foundation -import Logging - -private class Client { - func spawnFreshClient(uuid: UUID, logger: Logger) { - var logger = logger - logger[metadataKey: "UUID"] = uuid.description - logger.info("we're up and running") - let otherSubSystem = OtherSubSystem() - otherSubSystem.randomFunction(logger: logger) - logger.debug("random function returned") - } -} - -private class OtherSubSystem { - func randomFunction(logger: Logger) { - logger.debug("this propagates UUID and log level") - } -} - -enum ExplicitContextPassingExample { - static func main() { - Logging.bootstrap(ExampleValueLoggerImplementation.init) - let logger = Logging.make("com.example.TestApp.ExplicitContextPassingExample.main") - for clientID in 0 ..< 10 { - var clientLogger = logger - if clientID % 3 == 0 { - clientLogger.logLevel = .debug - } else { - clientLogger.logLevel = .info - } - Client().spawnFreshClient(uuid: UUID(), logger: clientLogger) - } - } -} diff --git a/Sources/Examples/LoggerPerSubsystemExample.swift b/Sources/Examples/LoggerPerSubsystemExample.swift deleted file mode 100644 index 39ebca7..0000000 --- a/Sources/Examples/LoggerPerSubsystemExample.swift +++ /dev/null @@ -1,49 +0,0 @@ -import Foundation -import Logging - -private class Client { - private let logger: Logger - - init(uuid: UUID, logLevel: LogLevel = .info) { - var logger = Logging.make("com.example.TestApp.LoggerPerSubsystemExample.Client") - // NOTE: the log level change below will only affect this `Client` instance which might or might not be what you want. - logger.logLevel = logLevel - logger[metadataKey: "UUID"] = uuid.description - self.logger = logger - } - - func spawnFreshClient() { - self.logger.info("we're up and running") - let otherSubSystem = OtherSubSystem() - otherSubSystem.randomFunction() - logger.debug("random function returned") - } -} - -private class OtherSubSystem { - private let logger = Logging.make("com.example.TestApp.LoggerPerSubsystemExample.OtherSubSystem") - - func randomFunction() { - // NOTE: this won't log the UUID as `Client` can't propagate its state to other sub-systems... - self.logger.info("just to say hi") - } -} - -enum LoggerPerSubsystemExample { - static func main() { - Logging.bootstrap(ExampleLoggerImplementation.init) - let logger = Logging.make("com.example.TestApp.LoggerPerSubsystemExample.main") - - logger.info("main start") - for clientID in 0 ..< 10 { - let client: Client - if clientID % 3 == 0 { - client = Client(uuid: UUID(), logLevel: .debug) - } else { - client = Client(uuid: UUID()) - } - client.spawnFreshClient() - } - logger.info("main end") - } -} diff --git a/Sources/Examples/MUXExample.swift b/Sources/Examples/MUXExample.swift deleted file mode 100644 index 9f2c31f..0000000 --- a/Sources/Examples/MUXExample.swift +++ /dev/null @@ -1,12 +0,0 @@ -import Foundation -import Logging - -enum MUXExample { - static func main() { - // boostrap with logging that multiplexes to two copies of ExampleLoggerImplementation - Logging.bootstrap(MultiplexLogging([ExampleLoggerImplementation.init, ExampleLoggerImplementation.init]).make) - - let logger = Logging.make("com.example.TestApp") - logger.info("we should see this twice!") - } -} diff --git a/Sources/Examples/OneGlobalLoggerExample.swift b/Sources/Examples/OneGlobalLoggerExample.swift deleted file mode 100644 index 5d412c9..0000000 --- a/Sources/Examples/OneGlobalLoggerExample.swift +++ /dev/null @@ -1,25 +0,0 @@ -import Foundation -import Logging - -// this model just uses one global logger. This is similar to what IBM's Logger API uses today (except that the one -// global thing has static methods. -let logger = Logging.make("com.example.TestApp.OneGlobalLoggerExample") - -enum OneGlobalLoggerExample { - static func main() { - Logging.bootstrap(ExampleLoggerImplementation.init) - for _ in 0 ..< 10 { - // NOTE: we can't change the log level per client because we only have one global logger - self.spawnFreshClient(uuid: UUID()) - } - } - - static func spawnFreshClient(uuid _: UUID) { - logger.info("we're up and running") - self.randomFunction() - } - - static func randomFunction() { - logger.debug("just to say hi, here the log level / UUID do not get propagated") - } -} diff --git a/Sources/Examples/RandomExample.swift b/Sources/Examples/RandomExample.swift deleted file mode 100644 index f191d30..0000000 --- a/Sources/Examples/RandomExample.swift +++ /dev/null @@ -1,66 +0,0 @@ -import Foundation -import Logging - -enum RandomExample { - static func main() { - // let's first start off with whatever is the default - print("=== default ===") - var logger = Logging.make("com.example.TestApp.LoggerBeforeConfig") - logger.trace("trace, not logged") - logger.debug("debug, not logged") - logger.info("default, info, no context") - logger.warn("default, warn, no context") - logger.error("default, error, no context") - - logger[metadataKey: "foo"] = "bar" - logger[metadataKey: "UUID"] = UUID().description - - logger.trace("trace, not logged") - logger.debug("debug, not logged") - logger.info("default, info, with context") - logger.warn("default, warn, with context") - logger.error("default, error, with context") - - print("=== reconfiguring the Logging's default to have a minimum level of warn with StdoutLogger ===") - Logging.bootstrap({ label in - let logger = StdoutLogger(label: label) - logger.logLevel = .warn - return logger - }) - logger = Logging.make("com.example.TestApp.LoggerAfterConfig1") - - logger.trace("trace, not logged") - logger.debug("debug, not logged") - logger.info("info, no context") - logger.warn("warn, no context") - logger.error("error, no context") - - logger[metadataKey: "bar"] = "buz" - logger[metadataKey: "UUID"] = UUID().description - - logger.trace("trace, not logged") - logger.debug("debug, not logged") - logger.info("info, with context") - logger.warn("warn, with context") - logger.error("error, with context") - - print("=== installing a custom logger ===") - Logging.bootstrap(ExampleLoggerImplementation.init) - logger = Logging.make("com.example.TestApp.LoggerAfterConfig2") - - logger.trace("trace, not logged") - logger.debug("debug, not logged") - logger.info("info, no context") - logger.warn("warn, no context") - logger.error("error, no context") - - logger[metadataKey: "buz"] = "cux" - logger[metadataKey: "UUID"] = UUID().description - - logger.trace("trace, not logged") - logger.debug("debug, not logged") - logger.info("info, with context") - logger.warn("warn, with context") - logger.error("error, with context") - } -} diff --git a/Sources/Examples/main.swift b/Sources/Examples/main.swift deleted file mode 100644 index f4896a0..0000000 --- a/Sources/Examples/main.swift +++ /dev/null @@ -1,18 +0,0 @@ -print("##### explicit logger passing #####") -ExplicitContextPassingExample.main() - -print() -print("##### one global logger #####") -OneGlobalLoggerExample.main() - -print() -print("##### logger per sub-system #####") -LoggerPerSubsystemExample.main() - -print() -print("##### other random examples #####") -RandomExample.main() - -print() -print("##### mux examples #####") -MUXExample.main() diff --git a/Sources/Logging/Locks.swift b/Sources/Logging/Locks.swift new file mode 100644 index 0000000..7c471cc --- /dev/null +++ b/Sources/Logging/Locks.swift @@ -0,0 +1,165 @@ +#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) + import Darwin +#else + import Glibc +#endif + +/// A threading lock based on `libpthread` instead of `libdispatch`. +/// +/// This object provides a lock on top of a single `pthread_mutex_t`. This kind +/// 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 = UnsafeMutablePointer.allocate(capacity: 1) + + /// Create a new lock. + public init() { + let err = pthread_mutex_init(self.mutex, nil) + precondition(err == 0) + } + + deinit { + let err = pthread_mutex_destroy(self.mutex) + precondition(err == 0) + self.mutex.deallocate() + } + + /// Acquire the lock. + /// + /// Whenever possible, consider using `withLock` instead of this method and + /// `unlock`, to simplify lock handling. + public func lock() { + let err = pthread_mutex_lock(self.mutex) + precondition(err == 0) + } + + /// Release the lock. + /// + /// Whenver possible, consider using `withLock` instead of this method and + /// `lock`, to simplify lock handling. + public func unlock() { + let err = pthread_mutex_unlock(self.mutex) + precondition(err == 0) + } +} + +extension Lock { + /// Acquire the lock for the duration of the given block. + /// + /// This convenience method should be preferred to `lock` and `unlock` in + /// most situations, as it ensures that the lock will be released regardless + /// of how `body` exits. + /// + /// - Parameter body: The block to execute while holding the lock. + /// - Returns: The value returned by the block. + @inlinable + public func withLock(_ body: () throws -> T) rethrows -> T { + self.lock() + defer { + self.unlock() + } + return try body() + } + + // specialise Void return (for performance) + @inlinable + public func withLockVoid(_ body: () throws -> Void) rethrows { + try self.withLock(body) + } +} + +/// A threading lock based on `libpthread` instead of `libdispatch`. +/// +/// This object provides a lock on top of a single `pthread_mutex_t`. This kind +/// 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 = UnsafeMutablePointer.allocate(capacity: 1) + + /// Create a new lock. + public init() { + let err = pthread_rwlock_init(self.rwlock, nil) + precondition(err == 0) + } + + deinit { + let err = pthread_rwlock_destroy(self.rwlock) + precondition(err == 0) + self.rwlock.deallocate() + } + + /// Acquire a reader lock. + /// + /// Whenever possible, consider using `withLock` instead of this method and + /// `unlock`, to simplify lock handling. + public func lockRead() { + let err = pthread_rwlock_rdlock(self.rwlock) + precondition(err == 0) + } + + /// Acquire a writer lock. + /// + /// Whenever possible, consider using `withLock` instead of this method and + /// `unlock`, to simplify lock handling. + public func lockWrite() { + let err = pthread_rwlock_wrlock(self.rwlock) + precondition(err == 0) + } + + /// Release the lock. + /// + /// Whenver possible, consider using `withLock` instead of this method and + /// `lock`, to simplify lock handling. + public func unlock() { + let err = pthread_rwlock_unlock(self.rwlock) + precondition(err == 0) + } +} + +extension ReadWriteLock { + /// Acquire the reader lock for the duration of the given block. + /// + /// This convenience method should be preferred to `lock` and `unlock` in + /// most situations, as it ensures that the lock will be released regardless + /// of how `body` exits. + /// + /// - Parameter body: The block to execute while holding the lock. + /// - Returns: The value returned by the block. + @inlinable + public func withReaderLock(_ body: () throws -> T) rethrows -> T { + self.lockRead() + defer { + self.unlock() + } + return try body() + } + + /// Acquire the writer lock for the duration of the given block. + /// + /// This convenience method should be preferred to `lock` and `unlock` in + /// most situations, as it ensures that the lock will be released regardless + /// of how `body` exits. + /// + /// - Parameter body: The block to execute while holding the lock. + /// - Returns: The value returned by the block. + @inlinable + public func withWriterLock(_ body: () throws -> T) rethrows -> T { + self.lockWrite() + defer { + self.unlock() + } + return try body() + } + + // specialise Void return (for performance) + @inlinable + public func withReaderLockVoid(_ body: () throws -> Void) rethrows { + try self.withReaderLock(body) + } + + // specialise Void return (for performance) + @inlinable + public func withWriterLockVoid(_ body: () throws -> Void) rethrows { + try self.withWriterLock(body) + } +} diff --git a/Sources/Logging/Logging.swift b/Sources/Logging/Logging.swift index 4582d16..443f866 100644 --- a/Sources/Logging/Logging.swift +++ b/Sources/Logging/Logging.swift @@ -1,4 +1,8 @@ -import Foundation +#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) + import Darwin +#else + import Glibc +#endif /// This is the protocol a custom logger implements. public protocol LogHandler { @@ -52,8 +56,8 @@ public struct Logger { } @inlinable - public func warn(_ message: @autoclosure () -> String, file: String = #file, function: String = #function, line: UInt = #line) { - self.log(level: .warn, message: message(), file: file, function: function, line: line) + public func warning(_ message: @autoclosure () -> String, file: String = #file, function: String = #function, line: UInt = #line) { + self.log(level: .warning, message: message(), file: file, function: function, line: line) } @inlinable @@ -96,7 +100,7 @@ public enum LogLevel: Int { case trace case debug case info - case warn + case warning case error } @@ -111,18 +115,18 @@ extension LogLevel: Comparable { // 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 = NSLock() + private static let lock = ReadWriteLock() private static var _factory: (String) -> LogHandler = StdoutLogger.init // Configures which `LogHandler` to use in the application. public static func bootstrap(_ factory: @escaping (String) -> LogHandler) { - self.lock.withLock { + self.lock.withWriterLock { self._factory = factory } } public static func make(_ label: String) -> Logger { - return self.lock.withLock { Logger(self._factory(label)) } + return self.lock.withReaderLock { Logger(self._factory(label)) } } } @@ -140,7 +144,7 @@ public final class MultiplexLogging { } private class MUXLogHandler: LogHandler { - private let lock = NSLock() + private let lock = Lock() private var handlers: [LogHandler] public init(handlers: [LogHandler]) { @@ -193,8 +197,8 @@ private class MUXLogHandler: LogHandler { } /// Ships with the logging module, really boring just prints something using the `print` function -public final class StdoutLogger: LogHandler { - private let lock = NSLock() +internal final class StdoutLogger: LogHandler { + private let lock = Lock() public init(label _: String) {} @@ -219,7 +223,7 @@ public final class StdoutLogger: LogHandler { public func log(level: LogLevel, message: String, file _: String, function _: String, line _: UInt) { if level >= self.logLevel { - print("\(Date()) \(level)\(self.prettyMetadata.map { " \($0)" } ?? "") \(message)") + print("\(self.timestamp()) \(level)\(self.prettyMetadata.map { " \($0)" } ?? "") \(message)") } } @@ -245,14 +249,14 @@ public final class StdoutLogger: LogHandler { } } } -} -private extension NSLock { - func withLock(_ body: () -> T) -> T { - self.lock() - defer { - self.unlock() - } - return body() + private func timestamp() -> String { + var buffer = [Int8](repeating: 0, count: 255) + var timestamp = time(nil) + let localTime = localtime(×tamp) + strftime(&buffer, buffer.count, "%Y-%m-%dT%H:%M:%S%z", localTime) + return buffer.map { UInt8($0) }.withUnsafeBufferPointer { ptr in + String.decodeCString(ptr.baseAddress, as: UTF8.self, repairingInvalidCodeUnits: true) + }?.0 ?? "\(timestamp)" } } diff --git a/Tests/LoggingTests/GlobalLoggingTest.swift b/Tests/LoggingTests/GlobalLoggingTest.swift index 8b40357..1f965a6 100644 --- a/Tests/LoggingTests/GlobalLoggingTest.swift +++ b/Tests/LoggingTests/GlobalLoggingTest.swift @@ -17,7 +17,7 @@ class GlobalLoggerTest: XCTestCase { logging.history.assertExist(level: .info, metadata: nil, message: "Struct2::doSomethingElse") logging.history.assertExist(level: .error, metadata: nil, message: "Struct3::doSomething") logging.history.assertExist(level: .error, metadata: ["foo": "bar"], message: "Struct3::doSomethingElse") - logging.history.assertExist(level: .warn, metadata: ["foo": "bar"], message: "Struct3::doSomethingElseAsync") + logging.history.assertExist(level: .warning, metadata: ["foo": "bar"], message: "Struct3::doSomethingElseAsync") logging.history.assertExist(level: .info, metadata: ["foo": "bar"], message: "TestLibrary::doSomething") logging.history.assertExist(level: .info, metadata: ["foo": "bar"], message: "TestLibrary::doSomethingAsync") logging.history.assertExist(level: .trace, metadata: ["baz": "qux"], message: "Struct3::doSomethingElse::Local") @@ -43,7 +43,7 @@ class GlobalLoggerTest: XCTestCase { logging.history.assertNotExist(level: .info, metadata: nil, message: "Struct2::doSomethingElse") logging.history.assertExist(level: .error, metadata: nil, message: "Struct3::doSomething") logging.history.assertExist(level: .error, metadata: ["foo": "bar"], message: "Struct3::doSomethingElse") - logging.history.assertNotExist(level: .warn, metadata: ["foo": "bar"], message: "Struct3::doSomethingElseAsync") + logging.history.assertNotExist(level: .warning, metadata: ["foo": "bar"], message: "Struct3::doSomethingElseAsync") logging.history.assertNotExist(level: .info, metadata: ["foo": "bar"], message: "TestLibrary::doSomething") logging.history.assertNotExist(level: .info, metadata: ["foo": "bar"], message: "TestLibrary::doSomethingAsync") logging.history.assertNotExist(level: .trace, metadata: ["baz": "qux"], message: "Struct3::doSomethingElse::Local") @@ -59,7 +59,7 @@ class GlobalLoggerTest: XCTestCase { let logging = TestLogging() Logging.bootstrap(logging.make) // change test logging config - logging.config.set(value: LogLevel.warn) + logging.config.set(value: LogLevel.warning) logging.config.set(key: "GlobalLoggerTest::Struct2", value: LogLevel.info) logging.config.set(key: "TestLibrary", value: LogLevel.trace) // run our program @@ -71,7 +71,7 @@ class GlobalLoggerTest: XCTestCase { logging.history.assertExist(level: .info, metadata: nil, message: "Struct2::doSomethingElse") logging.history.assertExist(level: .error, metadata: nil, message: "Struct3::doSomething") logging.history.assertExist(level: .error, metadata: ["foo": "bar"], message: "Struct3::doSomethingElse") - logging.history.assertExist(level: .warn, metadata: ["foo": "bar"], message: "Struct3::doSomethingElseAsync") + logging.history.assertExist(level: .warning, metadata: ["foo": "bar"], message: "Struct3::doSomethingElseAsync") logging.history.assertExist(level: .info, metadata: ["foo": "bar"], message: "TestLibrary::doSomething") logging.history.assertExist(level: .info, metadata: ["foo": "bar"], message: "TestLibrary::doSomethingAsync") logging.history.assertNotExist(level: .trace, metadata: ["baz": "qux"], message: "Struct3::doSomethingElse::Local") @@ -133,7 +133,7 @@ private struct Struct3 { let loggingMetadata = MDC.global.metadata queue.async { MDC.global.with(metadata: loggingMetadata) { - self.logger.warn("Struct3::doSomethingElseAsync") + self.logger.warning("Struct3::doSomethingElseAsync") let library = TestLibrary() library.doSomething() library.doSomethingAsync { diff --git a/Tests/LoggingTests/LocalLoggingTest.swift b/Tests/LoggingTests/LocalLoggingTest.swift index 0852003..6b292c3 100644 --- a/Tests/LoggingTests/LocalLoggingTest.swift +++ b/Tests/LoggingTests/LocalLoggingTest.swift @@ -18,7 +18,7 @@ class LocalLoggerTest: XCTestCase { logging.history.assertExist(level: .info, metadata: nil, message: "Struct2::doSomethingElse") logging.history.assertExist(level: .error, metadata: ["bar": "baz"], message: "Struct3::doSomething") logging.history.assertExist(level: .error, metadata: ["bar": "baz"], message: "Struct3::doSomethingElse") - logging.history.assertExist(level: .warn, metadata: ["bar": "baz"], message: "Struct3::doSomethingElseAsync") + logging.history.assertExist(level: .warning, metadata: ["bar": "baz"], message: "Struct3::doSomethingElseAsync") logging.history.assertExist(level: .info, metadata: nil, message: "TestLibrary::doSomething") logging.history.assertExist(level: .info, metadata: nil, message: "TestLibrary::doSomethingAsync") logging.history.assertExist(level: .trace, metadata: ["bar": "baz", "baz": "qux"], message: "Struct3::doSomethingElse::Local") @@ -45,7 +45,7 @@ class LocalLoggerTest: XCTestCase { logging.history.assertExist(level: .info, metadata: nil, message: "Struct2::doSomethingElse") // local context logging.history.assertExist(level: .error, metadata: ["bar": "baz"], message: "Struct3::doSomething") // local context logging.history.assertExist(level: .error, metadata: ["bar": "baz"], message: "Struct3::doSomethingElse") // local context - logging.history.assertExist(level: .warn, metadata: ["bar": "baz"], message: "Struct3::doSomethingElseAsync") // local context + logging.history.assertExist(level: .warning, metadata: ["bar": "baz"], message: "Struct3::doSomethingElseAsync") // local context logging.history.assertNotExist(level: .info, metadata: nil, message: "TestLibrary::doSomething") // global context logging.history.assertNotExist(level: .info, metadata: nil, message: "TestLibrary::doSomethingAsync") // global context logging.history.assertExist(level: .trace, metadata: ["bar": "baz", "baz": "qux"], message: "Struct3::doSomethingElse::Local") // hyper local context @@ -84,7 +84,7 @@ private struct Struct1 { private func doSomethingElse(context: Context) { let originalContext = context var context = context - context.logger.logLevel = .warn + context.logger.logLevel = .warning context.logger.trace("Struct1::doSomethingElse") Struct2().doSomething(context: context) originalContext.logger.trace("Struct1::doSomethingElse::end") @@ -125,7 +125,7 @@ private struct Struct3 { let group = DispatchGroup() group.enter() queue.async { - context.logger.warn("Struct3::doSomethingElseAsync") + context.logger.warning("Struct3::doSomethingElseAsync") let library = TestLibrary() library.doSomething() library.doSomethingAsync { diff --git a/Tests/LoggingTests/LoggingTest.swift b/Tests/LoggingTests/LoggingTest.swift index 7a706df..035ec1f 100644 --- a/Tests/LoggingTests/LoggingTest.swift +++ b/Tests/LoggingTests/LoggingTest.swift @@ -9,13 +9,13 @@ class LoggingTest: XCTestCase { Logging.bootstrap(MultiplexLogging([logging1.make, logging2.make]).make) var logger = Logging.make("test") - logger.logLevel = .warn + logger.logLevel = .warning logger.info("hello world") logger[metadataKey: "foo"] = "bar" - logger.warn("hello world!") + logger.warning("hello world!") logging1.history.assertNotExist(level: .info, metadata: nil, message: "hello world") logging2.history.assertNotExist(level: .info, metadata: nil, message: "hello world") - logging1.history.assertExist(level: .warn, metadata: ["foo": "bar"], message: "hello world!") - logging2.history.assertExist(level: .warn, metadata: ["foo": "bar"], message: "hello world!") + logging1.history.assertExist(level: .warning, metadata: ["foo": "bar"], message: "hello world!") + logging2.history.assertExist(level: .warning, metadata: ["foo": "bar"], message: "hello world!") } } diff --git a/Tests/LoggingTests/TestLogger.swift b/Tests/LoggingTests/TestLogger.swift index cebde73..c553733 100644 --- a/Tests/LoggingTests/TestLogger.swift +++ b/Tests/LoggingTests/TestLogger.swift @@ -143,8 +143,8 @@ internal extension History { return self.atLevel(level: .info) } - var warn: [LogEntry] { - return self.atLevel(level: .warn) + var warning: [LogEntry] { + return self.atLevel(level: .warning) } var error: [LogEntry] {