mirror of
https://github.com/apple/swift-log
synced 2026-11-24 03:47:49 +00:00
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
This commit is contained in:
1 parent
0f23cda751
commit
9027df5f03
25 files changed
+858
-381
No files matched your search
+5
-1
@@ -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"]
|
||||
|
||||
@@ -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<T>(_ body: () -> T) -> T {
|
||||
self.lock()
|
||||
defer {
|
||||
self.unlock()
|
||||
}
|
||||
return body()
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<T>(_ body: () -> T) -> T {
|
||||
self.lock()
|
||||
defer {
|
||||
self.unlock()
|
||||
}
|
||||
return body()
|
||||
}
|
||||
}
|
||||
@@ -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 }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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!")
|
||||
}
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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!")
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
@@ -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<T>(_ 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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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!")
|
||||
}
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
@@ -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<pthread_mutex_t> = 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<T>(_ 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<pthread_rwlock_t> = 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<T>(_ 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<T>(_ 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)
|
||||
}
|
||||
}
|
||||
@@ -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<T>(_ 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)"
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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!")
|
||||
}
|
||||
}
|
||||
@@ -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] {
|
||||
|
||||
Reference in new issue
Block a user