mirror of
https://github.com/apple/swift-log
synced 2026-11-28 04:14:20 +00:00
support custom logging factories (#33)
motivation: make the API flexible enough so that users that need to inject custom factories as an escape hatch can do that changes: add a Logging::make API variant that takes a custom factory instead of the default one
This commit is contained in:
1 parent
b0e59933ac
commit
aa3990dfa0
2 files changed
+33
-1
No files matched your search
@@ -131,6 +131,12 @@ extension Logger {
|
||||
public init(label: String) {
|
||||
self = Logging.lock.withReaderLock { Logger(Logging.factory(label)) }
|
||||
}
|
||||
|
||||
// this is to provide an escape hatch for situations one must use a custom factory instead of the gloabl one
|
||||
// we do not expect this API to be used in normal circumstances, so if you find yourself using it make sure its for a good reason
|
||||
public init(label: String, factory: (String) -> LogHandler) {
|
||||
self = Logger(factory(label))
|
||||
}
|
||||
}
|
||||
|
||||
extension Logger.Level: Comparable {
|
||||
|
||||
@@ -163,7 +163,7 @@ class LoggingTest: XCTestCase {
|
||||
func testStringConvertibleMetadata() {
|
||||
let testLogging = TestLogging()
|
||||
Logging.bootstrap(testLogging.make)
|
||||
var logger = Logging.make("\(#function)")
|
||||
var logger = Logger(label: "\(#function)")
|
||||
logger[metadataKey: "foo"] = .stringConvertible("raw-string")
|
||||
let lazyBox = LazyMetadataBox({ "rendered-at-first-use" })
|
||||
logger[metadataKey: "lazy"] = .stringConvertible(lazyBox)
|
||||
@@ -206,4 +206,30 @@ class LoggingTest: XCTestCase {
|
||||
testLogging.history.assertExist(level: .warning, message: "hello world!", metadata: ["bar": "baz", "baz": "qux"])
|
||||
testLogging.history.assertExist(level: .error, message: "hello world!", metadata: ["bar": "baz", "baz": "quc"])
|
||||
}
|
||||
|
||||
func testCustomFactory() {
|
||||
struct CustomHandler: LogHandler {
|
||||
func log(level: Logger.Level, message: String, metadata: Logger.Metadata?, error: Error?, file: StaticString, function: StaticString, line: UInt) {}
|
||||
|
||||
subscript(metadataKey _: String) -> Logger.Metadata.Value? {
|
||||
get { return nil }
|
||||
set {}
|
||||
}
|
||||
|
||||
var metadata: Logger.Metadata {
|
||||
get { return Logger.Metadata() }
|
||||
set {}
|
||||
}
|
||||
|
||||
var logLevel: Logger.Level {
|
||||
get { return .info }
|
||||
set {}
|
||||
}
|
||||
}
|
||||
|
||||
let logger1 = Logger(label: "foo")
|
||||
XCTAssertFalse(logger1.handler is CustomHandler, "expected non-custom log handler")
|
||||
let logger2 = Logger(label: "foo", factory: { _ in CustomHandler() })
|
||||
XCTAssertTrue(logger2.handler is CustomHandler, "expected custom log handler")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user