WARNING: THIS SITE IS A MIRROR OF GITHUB.COM / IT CANNOT LOGIN OR REGISTER ACCOUNTS / THE CONTENTS ARE PROVIDED AS-IS / THIS SITE ASSUMES NO RESPONSIBILITY FOR ANY DISPLAYED CONTENT OR LINKS / IF YOU FOUND SOMETHING MAY NOT GOOD FOR EVERYONE, CONTACT ADMIN AT ilovescratch@foxmail.com
Skip to content

Commit a747c21

Browse files
committed
Clean up setting of metadata on Logger
1 parent e7aa01c commit a747c21

File tree

2 files changed

+10
-7
lines changed

2 files changed

+10
-7
lines changed

Sources/Hummingbird/Extensions/Extensions.swift

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,8 @@ public struct HBExtensions<ParentObject> {
3232
return value
3333
}
3434

35-
/// Get extension from a `KeyPath`. If it doesn't exist then create it
35+
/// Get extension from a `KeyPath`. If it doesn't exist then create it. Use this with care it may cause race conditions
36+
/// especially if used on a global object like `HBApplication`.
3637
/// - Parameters:
3738
/// - key: KeyPath
3839
/// - createCB: closure used to create instance of object if it doesn't exist

Sources/Hummingbird/Server/Request.swift

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ public final class HBRequest: HBExtensible {
5858
self.method = head.method
5959
self.headers = head.headers
6060
self.body = body
61-
self.logger = Self.loggerWithRequestId(application.logger, uri: head.uri, method: head.method.rawValue)
61+
self.logger = application.logger.with(metadataKey: "hb_id", value: .string(Self.globalRequestID.add(1).description))
6262
self.application = application
6363
self.eventLoop = eventLoop
6464
self.allocator = allocator
@@ -109,11 +109,13 @@ public final class HBRequest: HBExtensible {
109109
public var allocator: ByteBufferAllocator
110110
}
111111

112-
private static func loggerWithRequestId(_ logger: Logger, uri: String, method: String) -> Logger {
113-
var logger = logger
114-
logger[metadataKey: "hb_id"] = .string(String(describing: Self.globalRequestID.add(1)))
112+
private static let globalRequestID = NIOAtomic<Int>.makeAtomic(value: 0)
113+
}
114+
115+
extension Logger {
116+
func with(metadataKey: String, value: MetadataValue) -> Logger {
117+
var logger = self
118+
logger[metadataKey: metadataKey] = value
115119
return logger
116120
}
117-
118-
private static let globalRequestID = NIOAtomic<Int>.makeAtomic(value: 0)
119121
}

0 commit comments

Comments
 (0)