diff --git a/Sources/Logging/Logging.swift b/Sources/Logging/Logging.swift index 59a95a2..86d7920 100644 --- a/Sources/Logging/Logging.swift +++ b/Sources/Logging/Logging.swift @@ -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 { diff --git a/Tests/LoggingTests/LoggingTest.swift b/Tests/LoggingTests/LoggingTest.swift index 3b83317..9788783 100644 --- a/Tests/LoggingTests/LoggingTest.swift +++ b/Tests/LoggingTests/LoggingTest.swift @@ -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") + } }