Skip to content

Instantly share code, notes, and snippets.

@adamw
Last active May 10, 2021 09:33
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save adamw/bd4f5aafa9d01abbc883 to your computer and use it in GitHub Desktop.
Save adamw/bd4f5aafa9d01abbc883 to your computer and use it in GitHub Desktop.
Logging request duration, path, status code using Akka HTTP
val rejectionHandler = RejectionHandler.default
def logDuration(inner: Route): Route = { ctx =>
val start = System.currentTimeMillis()
// handling rejections here so that we get proper status codes
val innerRejectionsHandled = handleRejections(rejectionHandler)(inner)
mapResponse { resp =>
val d = System.currentTimeMillis() - start
logger.info(s"[${resp.status.intValue()}] ${ctx.request.method.name} ${ctx.request.uri} took: ${d}ms")
resp
}(innerRejectionsHandled)(ctx)
}
// improved by @luksow
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)
}
@jasonqu
Copy link

jasonqu commented Mar 29, 2017

new to akka http, how could I use extractClientIP in logDuration? thanks

update :
found here http://stackoverflow.com/a/36729869/851099

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