Skip to content

Commit

Permalink
Add networkEventCreatedAt predefined metadata key
Browse files Browse the repository at this point in the history
  • Loading branch information
kean committed Feb 4, 2021
1 parent 854e0dd commit acfee52
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
10 changes: 8 additions & 2 deletions Sources/Pulse/PersistentLogHandler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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
Expand Down
19 changes: 19 additions & 0 deletions Tests/PulseTests/PersistenLogHandlerTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down

0 comments on commit acfee52

Please sign in to comment.