如何使用 MDC + Logbook 在 WebFlux 中记录请求和响应正文

问题描述 投票:0回答:2

我有一个 Spring Boot 应用程序,这是一个通过 WebClient 调用外部系统的反应式服务。我还有一些非反应性服务。已经使用

MDC
+
Logbook
Feign
客户端实现了日志记录。非常希望重用现有的类,或者至少使日志记录看起来与非响应式服务日志相同。

RESPONSE_CODE=200, RESPONSE_HEADERS=[transfer-encoding:"chunked"], METHOD=POST, REQUEST_QUERY={}, REQUEST_BODY=FluxMap, RESPONSE_BODY=, REQUEST_PATH=/ping, REQUEST_HEADERS=[Session:"11111abcd", Content-Type:"application/json", ..., Content-Length:"37"], TYPE=INREQ

当前日志看起来像这样。有问题的部分是

REQUEST_BODY=FluxMap
RESPONSE_BODY=

我设法在 WebClient 上使用

wiretap()
记录正文,但它不可自定义,因此不适合。

作为参考,我使用了这篇文章中的示例代码 我在这个 Github discussion

中找到了它

我尝试了不同的方法:使用

ExchangeFilterFunction
WebFilter
+
ServerHttpRequestDecorator
(和其他装饰器),我尝试从
DataBuffer
获取主体。还是没有运气。

logging spring-webflux spring-webclient mdc
2个回答
1
投票

对我有用的解决方案:

  1. 添加此依赖项
<dependency>
   <groupId>org.zalando</groupId>
   <artifactId>logbook-spring-boot-webflux-autoconfigure</artifactId>
</dependency>
  1. 创建
    Logbook
     时传递 
    WebClient
  2. 对象
private WebClient getWebClient(Logbook logbook) {
    HttpClient httpClient = HttpClient.create()
            .doOnConnected(connection -> {
                connection.addHandlerLast(new LogbookClientHandler(logbook));
            });

    return WebClient.builder()
            .baseUrl(myUrl)
            .clientConnector(new ReactorClientHttpConnector(httpClient))
            .build();
}

0
投票

它确实有效,但部分有效。 交换WebClient实际上开始记录。 但MDC也存在问题。 MDC 上下文未传递。 我正在寻找摆脱这种情况的方法。

© www.soinside.com 2019 - 2024. All rights reserved.