diff --git a/Sources/Pulse/PersistentLogHandler.swift b/Sources/Pulse/PersistentLogHandler.swift index 02e542ce3..3d2c196e9 100644 --- a/Sources/Pulse/PersistentLogHandler.swift +++ b/Sources/Pulse/PersistentLogHandler.swift @@ -53,7 +53,12 @@ extension PersistentLogHandler: LogHandler { public func log(level: Logger.Level, message: Logger.Message, metadata: Logger.Metadata?, file: String, function: String, line: UInt) { let context = store.backgroundContext - let date = makeCurrentDate() + let date: Date + if let metadata = metadata, case let .stringConvertible(value)? = metadata["networkEventCreatedAt"], let customDate = value as? Date { + date = customDate + } else { + date = makeCurrentDate() + } let label = self.label context.perform { @@ -64,7 +69,8 @@ extension PersistentLogHandler: LogHandler { entity.session = Self.logSessionId.uuidString entity.text = String(describing: message) if let entries = metadata?.unpack(), !entries.isEmpty { - entity.metadata = Set(entries.map { key, value in + entity.metadata = Set(entries.compactMap { key, value in + guard key != "networkEventCreatedAt" else { return nil } let entity = MetadataEntity(context: context) entity.key = key entity.value = value diff --git a/Tests/PulseTests/PersistenLogHandlerTests.swift b/Tests/PulseTests/PersistenLogHandlerTests.swift index a2d389691..39d216081 100644 --- a/Tests/PulseTests/PersistenLogHandlerTests.swift +++ b/Tests/PulseTests/PersistenLogHandlerTests.swift @@ -146,6 +146,25 @@ final class PersistentLogHandlerTests: XCTestCase { XCTAssertEqual(entry.key, "system") XCTAssertEqual(entry.value, "auth") } + + + func testOverridingCreatedAtDateFromNetworkLogger() throws { + // GIVEN + let eventDate = Date() + let sut = PersistentLogHandler(label: "network-logger", store: self.store, makeCurrentDate: { eventDate + 60 }) + + // WHEN + sut.log(level: .debug, message: "request failed", metadata: ["networkEventCreatedAt": .stringConvertible(eventDate)]) + flush(store: store) + + // THEN "networkEventCreatedAt" is used as "createdAt" + let message = try XCTUnwrap(store.allMessages().first) + XCTAssertEqual(message.createdAt, eventDate) + XCTAssertNotEqual(message.createdAt, eventDate + 60) + + // THEN metadata is not stored + XCTAssertTrue(message.metadata.isEmpty) + } } extension LogHandler {