Created
November 26, 2017 07:10
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 this is outdated. Take look here https://github.com/techmonad/learning-akka-http
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can you please attach the working coed , I am getting a lot of error.
Thanks.