How does one log Akka HTTP client requests

后端 未结 3 1562
难免孤独
难免孤独 2020-12-23 21:10

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

3条回答
  •  借酒劲吻你
    2020-12-23 21:35

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

提交回复
热议问题