使用Spring WebClient记录响应时,请保留日志上下文

时间:2020-03-01 18:18:15

标签: spring logging spring-webclient

由于我即将弃用RestTemplate,因此我甚至在API中使用Spring WebClient进行同步调用。

当我的API收到任何HTTP调用时,我注册了将在所有日志中使用的接收到的request-id标头。类似于以下代码:

@Component
class HeadersFilter : GenericFilterBean() {
    override fun doFilter(request: ServletRequest, response: ServletResponse, chain: FilterChain) {
        val header = request.getHeader("X-Request-ID")
        MDC.put("request-id", header)

        chain.doFilter(request, response)
    }
}

使用WebClient时,我通过执行以下操作创建了过滤器来记录所有请求和响应:

// ommited code
        WebClient.builder()
            .baseUrl(baseUrl)
            .filter(logRequest(logger))
            .filter(logResponse(logger))
            .exchangeStrategies(exchangeStrategies)
            .build()
// ommited code

fun logRequest(logger: Logger): ExchangeFilterFunction {
    return ExchangeFilterFunction.ofRequestProcessor { clientRequest ->
        val headers = clientRequest.headers().map { "${it.key}=${it.value.joinToString(",")}" }

        logger.info(
            "OUTBOUND_REQUEST - method={} url={} headers={}",
            clientRequest.method(),
            clientRequest.url(),
            headers
        )

        Mono.just(clientRequest)
    }
}

fun logResponse(logger: Logger): ExchangeFilterFunction {
    return ExchangeFilterFunction.ofResponseProcessor { clientResponse ->
        logger.info("OUTBOUND_RESPONSE - url={} status={}", clientResponse.statusCode())

        Mono.just(clientResponse)
    }
}

但是当我检查日志时,只有请求似乎具有请求ID,对于所有响应,此字段为空,我不知道为什么。

{"log_level": "INFO ", "request_id": "e7384d81-f91d-476e-b2c5-e887fec76ad9,bb0b8b53-d408-497d-b72e-9d8d74a3edbf", "content": OUTBOUND_REQUEST - method=POST url=url headers=[header1=value1]}

{"log_level": "INFO ", "request_id": "", "content": OUTBOUND_RESPONSE - status=201 CREATED}

如何记录请求和响应的request_id?

0 个答案:

没有答案