Skip to content

Commit

Permalink
Clean up setting of metadata on Logger
Browse files Browse the repository at this point in the history
  • Loading branch information
adam-fowler committed Mar 6, 2021
1 parent e7aa01c commit a747c21
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 7 deletions.
3 changes: 2 additions & 1 deletion Sources/Hummingbird/Extensions/Extensions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@ public struct HBExtensions<ParentObject> {
return value
}

/// Get extension from a `KeyPath`. If it doesn't exist then create it
/// Get extension from a `KeyPath`. If it doesn't exist then create it. Use this with care it may cause race conditions
/// especially if used on a global object like `HBApplication`.
/// - Parameters:
/// - key: KeyPath
/// - createCB: closure used to create instance of object if it doesn't exist
Expand Down
14 changes: 8 additions & 6 deletions Sources/Hummingbird/Server/Request.swift
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public final class HBRequest: HBExtensible {
self.method = head.method
self.headers = head.headers
self.body = body
self.logger = Self.loggerWithRequestId(application.logger, uri: head.uri, method: head.method.rawValue)
self.logger = application.logger.with(metadataKey: "hb_id", value: .string(Self.globalRequestID.add(1).description))
self.application = application
self.eventLoop = eventLoop
self.allocator = allocator
Expand Down Expand Up @@ -109,11 +109,13 @@ public final class HBRequest: HBExtensible {
public var allocator: ByteBufferAllocator
}

private static func loggerWithRequestId(_ logger: Logger, uri: String, method: String) -> Logger {
var logger = logger
logger[metadataKey: "hb_id"] = .string(String(describing: Self.globalRequestID.add(1)))
private static let globalRequestID = NIOAtomic<Int>.makeAtomic(value: 0)
}

extension Logger {
func with(metadataKey: String, value: MetadataValue) -> Logger {
var logger = self
logger[metadataKey: metadataKey] = value
return logger
}

private static let globalRequestID = NIOAtomic<Int>.makeAtomic(value: 0)
}

0 comments on commit a747c21

Please sign in to comment.