简体   繁体   中英

Akka-http logrequest not logging the request body

I am using akka-http and trying to log a request on a specific path using logrequest :

 path(Segment / "account") { id =>
            logRequest("users/account", Logging.InfoLevel) {
              post {
              entity(as[Account]) { account => ???
                complete(HttpResponse(StatusCodes.NoContent))
              }
            }
          }

however on my log I see something like

HttpRequest(HttpMethod(POST),https://localhost:9009/api/users/123/account,List(Host: localhost:9009, User-Agent: akka-http/10.0.6, Timeout-Access: <function1>),HttpEntity.Chunked(application/json),HttpProtocol(HTTP/1.1))

what I am looking for is the exact request including the body (json) as it was sent by the requestor.

The "HttpEntity.Chunked(application/json)" segment of the log is the output of HttpEntity.Chunked#toString . To get the entire request body, which is implemented as a stream, you need to call HttpEntity#toStrict to convert the Chunked request entity into a Strict request entity. You can make this call in a custom route:

def logRequestEntity(route: Route, level: LogLevel)
                    (implicit m: Materializer, ex: ExecutionContext) = {

  def requestEntityLoggingFunction(loggingAdapter: LoggingAdapter)(req: HttpRequest): Unit = {
    val timeout = 900.millis
    val bodyAsBytes: Future[ByteString] = req.entity.toStrict(timeout).map(_.data)
    val bodyAsString: Future[String] = bodyAsBytes.map(_.utf8String)
    bodyAsString.onComplete {
      case Success(body) =>
        val logMsg = s"$req\nRequest body: $body"
        loggingAdapter.log(level, logMsg)
      case Failure(t) =>
        val logMsg = s"Failed to get the body for: $req"
        loggingAdapter.error(t, logMsg)
    }
  }
  DebuggingDirectives.logRequest(LoggingMagnet(requestEntityLoggingFunction(_)))(route)
}

To use the above, pass your route to it:

val loggedRoute = logRequestEntity(route, Logging.InfoLevel)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM