Skip to content

Instantly share code, notes, and snippets.

@satendrakumar
Created November 26, 2017 07:10
Show Gist options
  • Save satendrakumar/a4f893a2e3c3b02cea0c2a6d8a958424 to your computer and use it in GitHub Desktop.
Save satendrakumar/a4f893a2e3c3b02cea0c2a6d8a958424 to your computer and use it in GitHub Desktop.
Log your Http request and response into log file with time taken by server to process that request.
import akka.event.LoggingAdapter
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.HttpRequest
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import akka.http.scaladsl.server.RouteResult.{Complete, Rejected}
import akka.http.scaladsl.server.directives.{DebuggingDirectives, LoggingMagnet}
import akka.stream.ActorMaterializer
import scala.concurrent.Future
object AkkaHttpService extends Logging {
def start(route: Route)(implicit system: ActorSystem,materializer: ActorMaterializer): Future[Http.ServerBinding] = {
val clientRouteLogged = DebuggingDirectives.logRequestResult(LoggingMagnet(logResponseTime(_)))(route)
Http().bindAndHandle(clientRouteLogged, "0.0.0.0", 9000)
}
private def logResponseTime(log: LoggingAdapter): HttpRequest => Any => Unit =
akkaResponseTimeLoggingFunction(log, System.currentTimeMillis())(_)
private def akkaResponseTimeLoggingFunction(loggingAdapter: LoggingAdapter, requestTimestamp: Long)(req: HttpRequest)(res: Any): Unit =
res match {
case Complete(resp) =>
val responseTimestamp: Long = System.currentTimeMillis()
val elapsedTime: Long = (responseTimestamp - requestTimestamp)
warn(s"Request : [$req]")
warn(s"[total time taken : $elapsedTime milliseconds] [Response : $resp]")
case Rejected(reason) =>
warn(s"Rejected Reason: ${reason.mkString(",")}")
}
}
@akashshivshukla
Copy link

akashshivshukla commented Nov 26, 2021

Can you please attach the working coed , I am getting a lot of error.
Thanks.

@satendrakumar
Copy link
Author

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