I need to log akka http client requests as well as their responses. While there seems to be a hint of API for logging these requests, there is no clear documentation on how
For another solution, this code logs the request IP and associates a random number with each request and response so they can be associated in the logs. It also records the response time.
Since the request may take awhile to process, and may fail, I wanted to see the request immediately, and see the response if and when it returns.
RequestFields is just the data I care about from the request. There's a lot of noise by default.
val logRequestResponse: Directive0 =
extractRequestContext flatMap { ctx =>
extractClientIP flatMap { ip =>
val id = scala.math.abs(rand.nextLong).toString
onSuccess(RequestFields.fromIdIpAndRequest(id, ip, ctx.request)) flatMap { req =>
logger.info("request", req.asJson)
val i = Instant.now()
mapRouteResultWith { result =>
Result.fromIdStartTimeAndRouteResult(id, i, result) map { res =>
logger.info("response", res.asJson)
result
}
}
}
}
}