Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow for LogRequestMiddleware to filter the headers it outputs #433

Merged
merged 9 commits into from
May 6, 2024
34 changes: 29 additions & 5 deletions Sources/Hummingbird/Middleware/LogRequestMiddleware.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,32 +12,56 @@
//
//===----------------------------------------------------------------------===//

import HTTPTypes
import Logging

/// Middleware outputting to log for every call to server
public struct LogRequestsMiddleware<Context: BaseRequestContext>: RouterMiddleware {
public enum HeaderFilter: Sendable {
adam-fowler marked this conversation as resolved.
Show resolved Hide resolved
case none
case all
case some([HTTPField.Name])
}

let logLevel: Logger.Level
let includeHeaders: Bool
let includeHeaders: HeaderFilter

public init(_ logLevel: Logger.Level, includeHeaders: Bool = false) {
public init(_ logLevel: Logger.Level, includeHeaders: HeaderFilter = .none) {
self.logLevel = logLevel
self.includeHeaders = includeHeaders
}

public func handle(_ request: Request, context: Context, next: (Request, Context) async throws -> Response) async throws -> Response {
if self.includeHeaders {
switch self.includeHeaders {
case .none:
context.logger.log(
level: self.logLevel,
"",
metadata: ["hb_uri": .stringConvertible(request.uri), "hb_method": .string(request.method.rawValue)]
)
case .all:
context.logger.log(
level: self.logLevel,
"\(request.headers)",
metadata: ["hb_uri": .stringConvertible(request.uri), "hb_method": .string(request.method.rawValue)]
)
} else {
case .some(let filter):
context.logger.log(
level: self.logLevel,
"",
"\(self.filterHeaders(headers: request.headers, filter: filter))",
metadata: ["hb_uri": .stringConvertible(request.uri), "hb_method": .string(request.method.rawValue)]
)
}
return try await next(request, context)
}

func filterHeaders(headers: HTTPFields, filter: [HTTPField.Name]) -> String {
var filteredHeaders: [(String, String)] = []
for entry in filter {
if let value = headers[entry] {
filteredHeaders.append((entry.canonicalName, value))
}
}
return "[\(filteredHeaders.map { "\"\($0)\":\"\($1)\"" }.joined(separator: ", "))]"
}
}
9 changes: 7 additions & 2 deletions Tests/HummingbirdTests/MiddlewareTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -233,13 +233,18 @@ final class MiddlewareTests: XCTestCase {

func testRouteLoggingMiddleware() async throws {
let router = Router()
router.middlewares.add(LogRequestsMiddleware(.debug))
router.middlewares.add(LogRequestsMiddleware(.info, includeHeaders: .some([.contentType])))
router.put("/hello") { _, _ -> String in
throw HTTPError(.badRequest)
}
let app = Application(responder: router.buildResponder())
try await app.test(.router) { client in
try await client.execute(uri: "/hello", method: .put) { _ in
try await client.execute(
uri: "/hello",
method: .put,
headers: [.contentType: "application/json"],
body: .init(string: "{}")
) { _ in
}
}
}
Expand Down
Loading