From d756065630dc3972f5aa405ed2bc888c54c4859d Mon Sep 17 00:00:00 2001 From: Johannes Weiss Date: Tue, 9 Oct 2018 17:42:47 +0100 Subject: [PATCH] initial commit --- .gitignore | 5 + Package.swift | 21 +++ README.md | 29 ++++ .../ExampleLoggerImpl/ExampleLoggerImpl.swift | 84 +++++++++++ Sources/ServerLoggerAPI/logging.swift | 139 ++++++++++++++++++ .../ExplicitLoggerPassingExample.swift | 35 +++++ .../TestApp/LoggerPerSubsystemExample.swift | 50 +++++++ Sources/TestApp/OneGlobalLoggerExample.swift | 24 +++ Sources/TestApp/RandomExample.swift | 69 +++++++++ Sources/TestApp/main.swift | 19 +++ 10 files changed, 475 insertions(+) create mode 100644 .gitignore create mode 100644 Package.swift create mode 100644 README.md create mode 100644 Sources/ExampleLoggerImpl/ExampleLoggerImpl.swift create mode 100644 Sources/ServerLoggerAPI/logging.swift create mode 100644 Sources/TestApp/ExplicitLoggerPassingExample.swift create mode 100644 Sources/TestApp/LoggerPerSubsystemExample.swift create mode 100644 Sources/TestApp/OneGlobalLoggerExample.swift create mode 100644 Sources/TestApp/RandomExample.swift create mode 100644 Sources/TestApp/main.swift diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e580695 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +.DS_Store +/.build +/Packages +/*.xcodeproj +.xcode diff --git a/Package.swift b/Package.swift new file mode 100644 index 0000000..4ccf072 --- /dev/null +++ b/Package.swift @@ -0,0 +1,21 @@ +// swift-tools-version:4.2 +// The swift-tools-version declares the minimum version of Swift required to build this package. + +import PackageDescription + +let package = Package( + name: "ServerLoggerAPI", + targets: [ + // Targets are the basic building blocks of a package. A target can define a module or a test suite. + // Targets can depend on other targets in this package, and on products in packages which this package depends on. + .target( + name: "ServerLoggerAPI", + dependencies: []), + .target( + name: "TestApp", + dependencies: ["ServerLoggerAPI", "ExampleLoggerImpl"]), + .target( + name: "ExampleLoggerImpl", + dependencies: ["ServerLoggerAPI"]), + ] +) diff --git a/README.md b/README.md new file mode 100644 index 0000000..542f3e7 --- /dev/null +++ b/README.md @@ -0,0 +1,29 @@ +# swift-server-logger-api + +This is *pre-pitch stage* SSWG proposal about a logger API that intends to support a number programming models: + +- explicit logger passing (see `ExplicitLoggerPassingExample.swift`) +- one global logger (see `OneGlobalLoggerExample.swift`) +- one logger per sub-system (see `LoggerPerSubsystem.swift`) + +The file `RandomExample.swift` contains demoes of some other things that you may want to do. + +## Feedback Wishes + +This is really only a first pass and I will speak to the OSLog folks again to maybe get towards an API that's at least very similar between client & server. + +Feedback that would really be great is: +- if anything, what does this proposal *not cover* that you will definitely need +- if anything, what could we remove from this and still be happy? +- API-wise: what do you like, what don't you like? + +Feel free to post this as message on the SSWG forum and/or github issues in this repo. + +## Open Questions + +Very many. But here a couple that come to my mind: + +- currently attaching context to a logger is done through `subscript(diagnosticKey diagnosticKey: String) -> String? { get set }` + clearly setting and deleting extra context is necessary. But reading it is really not. Should we make it `addContext(key: String, value: String)` and `removeContext(key:String)` instead? +- should the logging context values be `String`? +- should we remove the possible customisation around log level evaluation and stick that in the API? If yes, the `_log` function would need to unconditionally log if called because the `level > self.logLevel` has already been done. diff --git a/Sources/ExampleLoggerImpl/ExampleLoggerImpl.swift b/Sources/ExampleLoggerImpl/ExampleLoggerImpl.swift new file mode 100644 index 0000000..e0b8c9e --- /dev/null +++ b/Sources/ExampleLoggerImpl/ExampleLoggerImpl.swift @@ -0,0 +1,84 @@ +// +// THIS IS NOT PART OF THE PITCH, JUST AN EXAMPLE HOW A LOGGER IMPLEMENTATION LOOKS LIKE +// + +import Foundation +import ServerLoggerAPI + +private extension NSLock { + func withLock(_ body: () -> T) -> T { + self.lock() + defer { + self.unlock() + } + return body() + } +} + +public final class ExampleLoggerImplementation: Logger { + private let formatter: DateFormatter + private let identifier: String + + private let lock = NSLock() + private var context: [String: String] = [:] { + didSet { + if self.context.isEmpty { + self.prettyContext = "" + } else { + self.prettyContext = " \(self.context.description) @\(self.identifier)" + } + } + } + private var prettyContext: String + 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(identifier: String) { + self.prettyContext = "" + self.identifier = identifier + 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: @autoclosure () -> String, file: String, function: String, line: UInt) { + if level >= self.logLevel { + print("\(self.formatter.string(from: Date())) \(self.formatLevel(level)): \(message())\(self.prettyContext)") + } + } + + public subscript(diagnosticKey diagnosticKey: String) -> String? { + get { + return self.lock.withLock { self.context[diagnosticKey] } + } + set { + self.lock.withLock { self.context[diagnosticKey] = newValue } + } + } +} diff --git a/Sources/ServerLoggerAPI/logging.swift b/Sources/ServerLoggerAPI/logging.swift new file mode 100644 index 0000000..d9e00c7 --- /dev/null +++ b/Sources/ServerLoggerAPI/logging.swift @@ -0,0 +1,139 @@ +import Foundation + +/// The most important type, the one the users will actually interact with and for example write: +/// +/// let myModuleLogger = LoggerFactory.make(label: "example.myproject.FooModule") +/// class MyClass { +/// func something() { +/// myModuleLogger.warn("something isn't a great function name") +/// } +/// } +public protocol Logger { + /// not called directly, only by the helper methods like `info(...)` + func _log(level: LogLevel, message: @autoclosure () -> String, file: String, function: String, line: UInt) + + /// This adds diagnostic context to a place the concrete logger considers appropriate. Some loggers + /// might not support this feature at all. + subscript(diagnosticKey diagnosticKey: String) -> String? { get set } + + var logLevel: LogLevel { get set } +} + +extension Logger { + + @inlinable + public func trace(_ message: @autoclosure () -> String, file: String = #file, function: String = #function, line: UInt = #line) { + self._log(level: .trace, message: message, file: file, function: function, line: line) + } + + @inlinable + public func debug(_ message: @autoclosure () -> String, file: String = #file, function: String = #function, line: UInt = #line) { + self._log(level: .debug, message: message, file: file, function: function, line: line) + } + + @inlinable + public func info(_ message: @autoclosure () -> String, file: String = #file, function: String = #function, line: UInt = #line) { + self._log(level: .info, message: message, file: file, function: function, line: line) + } + + @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) + } + + @inlinable + public func error(_ message: @autoclosure () -> String, file: String = #file, function: String = #function, line: UInt = #line) { + self._log(level: .error, message: message, file: file, function: function, line: line) + } +} + +public enum LogLevel: Int { + case trace + case debug + case info + case warn + case error +} + +extension LogLevel: Comparable { + public static func < (lhs: LogLevel, rhs: LogLevel) -> Bool { + return lhs.rawValue < rhs.rawValue + } +} + +/// The second most important type, this is where users will get a logger from. +public enum LoggerFactory { + private static let lock = NSLock() + private static var _factory: (String) -> Logger = StdoutLogger.init + public static var factory: (String) -> Logger { + get { + return self.lock.withLock { self._factory } + } + set { + self.lock.withLock { + self._factory = newValue + } + } + } + + // this is used to create a logger for a certain unit which might be a module, file, class/struct, function, whatever works for the concrete application. Systems that pass the logger explicitly would not use this function. + public static func make(identifier: String) -> Logger { + return self.factory(identifier) + } +} + +/// Ships with the logging module, really boring just prints something using the `print` function +final public class StdoutLogger: Logger { + + private let lock = NSLock() + private var context: [String: String] = [:] { + didSet { + if self.context.isEmpty { + self.prettyContext = "" + } else { + self.prettyContext = " \(self.context.description)" + } + } + } + private var prettyContext: String = "" + 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(identifier: String) { + } + + public func _log(level: LogLevel, message: @autoclosure () -> String, file: String, function: String, line: UInt) { + if level >= self.logLevel { + print("\(message())\(self.prettyContext)") + } + } + + public subscript(diagnosticKey diagnosticKey: String) -> String? { + get { + return self.lock.withLock { self.context[diagnosticKey] } + } + set { + self.lock.withLock { self.context[diagnosticKey] = newValue } + } + } +} + +private extension NSLock { + func withLock(_ body: () -> T) -> T { + self.lock() + defer { + self.unlock() + } + return body() + } +} diff --git a/Sources/TestApp/ExplicitLoggerPassingExample.swift b/Sources/TestApp/ExplicitLoggerPassingExample.swift new file mode 100644 index 0000000..9b03667 --- /dev/null +++ b/Sources/TestApp/ExplicitLoggerPassingExample.swift @@ -0,0 +1,35 @@ +import Foundation +import ServerLoggerAPI + +private class Client { + func spawnFreshClient(uuid: UUID, logger: Logger) { + var logger = logger + logger[diagnosticKey: "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() { + let logger = LoggerFactory.make(identifier: "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/TestApp/LoggerPerSubsystemExample.swift b/Sources/TestApp/LoggerPerSubsystemExample.swift new file mode 100644 index 0000000..4cce1cc --- /dev/null +++ b/Sources/TestApp/LoggerPerSubsystemExample.swift @@ -0,0 +1,50 @@ +import Foundation +import ServerLoggerAPI + +private class Client { + private let logger: Logger + + init(uuid: UUID, logLevel: LogLevel = .info) { + var logger = LoggerFactory.make(identifier: "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[diagnosticKey: "UUID"] = uuid.description + self.logger = logger + } + + func spawnFreshClient() { + logger.info("we're up and running") + let otherSubSystem = OtherSubSystem() + otherSubSystem.randomFunction() + logger.debug("random function returned") + } +} + +private class OtherSubSystem { + private let logger: Logger = LoggerFactory.make(identifier: "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... + logger.info("just to say hi") + } +} + + +enum LoggerPerSubsystemExample { + static func main() { + let logger = LoggerFactory.make(identifier: "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/TestApp/OneGlobalLoggerExample.swift b/Sources/TestApp/OneGlobalLoggerExample.swift new file mode 100644 index 0000000..9857678 --- /dev/null +++ b/Sources/TestApp/OneGlobalLoggerExample.swift @@ -0,0 +1,24 @@ +import Foundation +import ServerLoggerAPI + +// 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 = LoggerFactory.make(identifier: "com.example.TestApp.OneGlobalLoggerExample") + +enum OneGlobalLoggerExample { + static func main() { + for _ in 0..<10 { + // NOTE: we can't change the log level per client because we only have one global logger + spawnFreshClient(uuid: UUID()) + } + } + + static func spawnFreshClient(uuid: UUID) { + logger.info("we're up and running") + randomFunction() + } + + static func randomFunction() { + logger.debug("just to say hi, here the log level / UUID do not get propagated") + } +} diff --git a/Sources/TestApp/RandomExample.swift b/Sources/TestApp/RandomExample.swift new file mode 100644 index 0000000..75e5524 --- /dev/null +++ b/Sources/TestApp/RandomExample.swift @@ -0,0 +1,69 @@ +import Foundation +import ServerLoggerAPI +import ExampleLoggerImpl + +enum RandomExample { + static func main() { + // let's first start off with whatever is the default + print("=== default ===") + var logger = LoggerFactory.make(identifier: "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[diagnosticKey: "foo"] = "bar" + logger[diagnosticKey: "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 LoggerFactory's default to have a minimum level of warn with StdoutLogger ===") + LoggerFactory.factory = { identifier in + let logger = StdoutLogger(identifier: identifier) + logger.logLevel = .warn + return logger + } + logger = LoggerFactory.make(identifier: "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[diagnosticKey: "bar"] = "buz" + logger[diagnosticKey: "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 ===") + LoggerFactory.factory = ExampleLoggerImplementation.init + logger = LoggerFactory.make(identifier: "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[diagnosticKey: "buz"] = "cux" + logger[diagnosticKey: "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/TestApp/main.swift b/Sources/TestApp/main.swift new file mode 100644 index 0000000..58a47f0 --- /dev/null +++ b/Sources/TestApp/main.swift @@ -0,0 +1,19 @@ +import ServerLoggerAPI +import ExampleLoggerImpl +import Foundation + +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() +