我需要记录akka http客户端的请求以及它们的响应。虽然似乎有一些API可以记录这些请求,但没有清晰的文档说明应该如何实现。我的方法是创建一个已记录的请求,它透明地包装了Http().singleRequest(req)
,如下所示:
def loggedRequest(req: HttpRequest)
(implicit system: ActorSystem, ctx: ExecutionContext, m: Materializer): Future[HttpResponse] = {
Http().singleRequest(req).map { resp ⇒
Unmarshal(resp.entity).to[String].foreach{s ⇒
system.log.info(req.toString)
system.log.info(resp.toString + "\n" + s)
}
resp
}
}
不幸的是,我必须通过解封装或仅通过请求resp.entity.dataBytes来获取响应正文以抓取未来。 我理解日志,但承诺已完成,我无法再将实体解封装为实际数据。 一个有效的解决方案将记录请求和响应,并通过不抛出“Promise already completed”引发
IllegalStateException
的测试用例:
<code>describe("Logged rest requests") {
it("deliver typed responses") {
val foo = Rest.loggedRequest(Get(s"http://127.0.0.1:9000/some/path"))
val resp = foo.futureValue(patience)
resp.status shouldBe StatusCodes.OK
val res = Unmarshal(resp.entity).to[MyClass].futureValue
}
}
</code>
欢迎提出想法。