Skip to content

Instantly share code, notes, and snippets.

@xdev-developer
Forked from calvinlfer/request-logging.scala
Created November 15, 2016 18:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xdev-developer/36c67215c2e41f9bc690079c405a7d58 to your computer and use it in GitHub Desktop.
Save xdev-developer/36c67215c2e41f9bc690079c405a7d58 to your computer and use it in GitHub Desktop.
Logging request duration, path, status code using Akka HTTP
// Setup
val rejectionHandler = RejectionHandler.default
val logDuration = extractRequestContext.flatMap { ctx =>
val start = System.currentTimeMillis()
// handling rejections here so that we get proper status codes
mapResponse { resp =>
val d = System.currentTimeMillis() - start
logger.info(s"[${resp.status.intValue()}] ${ctx.request.method.name} ${ctx.request.uri} took: ${d}ms")
resp
} & handleRejections(rejectionHandler)
}
// Usage
// Example Route
def healthRoute =
pathPrefix("health") {
get {
...
}
}
}
// This will log the following routes
val routes = logDuration(healthRoute ~ otherRoute ~ anotherRoute)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment