Skip to content

Commit 129e70f

Browse files
committed
adding a replacement for the default route logging middleware from Vapor that adds in the cf-ray id, if any, from cloudflare
1 parent c61c582 commit 129e70f

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import Vapor
2+
3+
// Replica of the Vapor RouteLoggingMiddleware that's tweaked to explicitly expose the cf-ray header in the logger metadata for the request.
4+
public final class CFRayRouteLoggingMiddleware: Middleware {
5+
public let logLevel: Logger.Level
6+
7+
public init(logLevel: Logger.Level = .info) {
8+
self.logLevel = logLevel
9+
}
10+
11+
public func respond(to request: Request, chainingTo next: Responder) -> EventLoopFuture<Response> {
12+
let cfray = request.headers.first(name: "cf-ray") ?? "--nil--"
13+
request.logger[metadataKey: "cf-ray"] = .string(cfray)
14+
request.logger.log(level: self.logLevel, "\(request.method) \(request.url.path.removingPercentEncoding ?? request.url.path)")
15+
return next.respond(to: request)
16+
}
17+
}

Sources/App/configure.swift

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,15 @@ public func configure(_ app: Application) async throws -> String {
3636
// app.http.server.configuration.responseCompression = .enabled
3737
// app.http.server.configuration.requestDecompression = .enabled
3838

39+
// This stanza replaces the default middleware from Vapor, specifically replacing the
40+
// default route logging middleware with the tweaked up version that reports on the cf-ray
41+
// header (if any) from CloudFlare.
42+
app.middleware = Middlewares()
43+
app.middleware.use(Vapor.ErrorMiddleware.default(environment: app.environment))
44+
app.middleware.use(CFRayRouteLoggingMiddleware())
45+
// disable the 3 lines above to return to the default middleware setup before we add SPI-specific
46+
// middleware.
47+
3948
app.middleware.use(FileMiddleware(publicDirectory: app.directory.publicDirectory))
4049
app.middleware.use(ErrorMiddleware())
4150

0 commit comments

Comments
 (0)