Akka-http logrequest未记录请求正文

时间:2017-08-02 10:39:14

标签: scala akka akka-http

我正在使用akka-http并尝试使用logrequest在特定路径上记录请求:

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

然而,在我的日志中,我看到类似

的内容
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))

我正在寻找的是确切的请求,包括请求者发送的正文(json)。

1 个答案:

答案 0 :(得分:3)

日志的"HttpEntity.Chunked(application/json)"段是HttpEntity.Chunked#toString的输出。要获取整个请求正文(实现为流),您需要调用HttpEntity#toStrictChunked请求实体转换为Strict请求实体。您可以使用自定义路线进行此调用:

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)
}

要使用上述内容,请将路线传递给它:

val loggedRoute = logRequestEntity(route, Logging.InfoLevel)