Skip to content

Instantly share code, notes, and snippets.

@jjunqueira
Created February 16, 2018 13:58
Show Gist options
  • Save jjunqueira/ad30ac9afa83564c5eb5e4954eb7cbf9 to your computer and use it in GitHub Desktop.
Save jjunqueira/ad30ac9afa83564c5eb5e4954eb7cbf9 to your computer and use it in GitHub Desktop.
Log Akka Http Response time including transmission of bytes
def akkaResponseTimeLoggingFunction(loggingAdapter: LoggingAdapter,
requestTimestamp: Long,
level: LogLevel = Logging.InfoLevel)(req: HttpRequest)(res: RouteResult): Unit = {
res match {
case Complete(resp) =>
resp.entity.transformDataBytes(Flow[ByteString].watchTermination() {
case (_, f) =>
f.foreach { _ =>
val responseTimestamp: Long = System.nanoTime
val elapsedTime: Long = (responseTimestamp - requestTimestamp) / 1000000
val loggingString = s"""Logged Request:${req.method}:${req.uri}:${resp.status}:$elapsedTime"""
LogEntry(loggingString, level).logTo(loggingAdapter)
}
})
case Rejected(reason) =>
directives.LogEntry(s"Rejected Reason: ${reason.mkString(",")}", level).logTo(loggingAdapter)
}
}
def printResponseTime(log: LoggingAdapter) = {
val requestTimestamp = System.nanoTime
akkaResponseTimeLoggingFunction(log, requestTimestamp)(_)
}
val logResponseTime = DebuggingDirectives.logRequestResult(LoggingMagnet(printResponseTime))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment