[英]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 : 我正在使用akka-http并尝试使用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. 我正在寻找的是确切的请求,包括请求者发送的正文(json)。
The "HttpEntity.Chunked(application/json)"
segment of the log is the output of HttpEntity.Chunked#toString
. 日志的
"HttpEntity.Chunked(application/json)"
段是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. 要获取整个请求主体(实现为流),您需要调用
HttpEntity#toStrict
将Chunked
请求实体转换为Strict
请求实体。 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.