Skip to content

Instantly share code, notes, and snippets.

@pedantix
Created March 5, 2018 03:57
Show Gist options
  • Save pedantix/2c0f65d93aeb32e1718db694ae1e6ec4 to your computer and use it in GitHub Desktop.
Save pedantix/2c0f65d93aeb32e1718db694ae1e6ec4 to your computer and use it in GitHub Desktop.
Vapor 3 Request Logger
public func configure(
_ config: inout Config,
_ env: inout Environment,
_ services: inout Services
) throws {
// App Configuration
configureMiddleware(&services, env: env)
}
private func configureMiddleware(_ services: inout Services, env: Environment) {
guard !env.isRelease else { return }
// configure middleware
var mwc = MiddlewareConfig.default()
mwc.use(RouteLoggingMiddleware())
services.register(mwc)
}
final class RouteLoggingMiddleware: Middleware, Service {
func respond(to request: Request, chainingTo next: Responder) throws -> Future<Response> {
let logger = try request.make(Logger.self)
let method = request.http.method
let path = request.http.uri.path
let query = request.http.uri.query
let reqString = "[\(method)]@\(path) with query:\(query)"
logger.debug(reqString)
return try next.respond(to: request)
}
}
@ditansu
Copy link

ditansu commented Mar 8, 2018

it doesn't work

⚠️ [ServiceError.make: No services are available for 'RouteLoggingMiddleware'.] [Suggested fixes: Register a service for 'RouteLoggingMiddleware'. services.register(RouteLoggingMiddleware.self) { ... }.]
Program ended with exit code: 1

fix:

RouteLoggingMiddleware.swift

extension RouteLoggingMiddleware: ServiceType {
  static func makeService(for worker: Container) throws -> Self {
    return .init()
  }
}

configure.swift

private func configureRouteLogginMiddleware(_ services: inout Services, env: Environment) {

  var middlewares = MiddlewareConfig.default()

  if !env.isRelease  {
     services.register(RouteLoggingMiddleware.self)
     middlewares.use(RouteLoggingMiddleware.self)
  }

  services.register(middlewares)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment