mirror of
https://github.com/apple/swift-log
synced 2026-11-24 03:47:49 +00:00
improve global logging example (#30)
motivation: better example changes: the exmaple is single threaded, but better to show how to properly use global loggers (although we discourage them)
This commit is contained in:
1 parent
1d983153b4
commit
11ea26a505
1 file changed
+25
-1
@@ -6,7 +6,21 @@ import ExampleImplementation
|
||||
import Foundation
|
||||
import Logging
|
||||
|
||||
var logger = Logging.make("GlobalLogger")
|
||||
// since this example mutates the global logger, we need to lock around it
|
||||
var _logger = Logging.make("GlobalLogger")
|
||||
var lock = NSLock()
|
||||
var logger: Logger {
|
||||
get {
|
||||
return lock.withLock {
|
||||
_logger
|
||||
}
|
||||
}
|
||||
set {
|
||||
lock.withLock {
|
||||
_logger = newValue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// this is a contrived example of a system that shares one global logger
|
||||
enum GlobalLoggerBasedSystem {
|
||||
@@ -80,3 +94,13 @@ enum GlobalLoggerBasedSystem {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension NSLock {
|
||||
func withLock<T>(_ body: () -> T) -> T {
|
||||
self.lock()
|
||||
defer {
|
||||
self.unlock()
|
||||
}
|
||||
return body()
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user