如何记录 spring-webflux WebClient 请求+响应详细信息(正文、标头、elasped_time)?

nsp*_*ung 9 logging spring-boot spring-web spring-webflux spring-webclient

基本上,我想在一个包含 Spring 的主体/标头的日志中记录请求/响应信息WebClient

有了 Spring,RestTemplate我们就可以用ClientHttpRequestInterceptor. 我找到了ExchangeFilterFunctionSpring 的相关内容WebClient,但还没有设法以干净的方式做类似的事情。我们可以使用此过滤器并记录请求,然后记录响应,但我需要在同一日志跟踪上两者。

此外,我还没有设法用ExchangeFilterFunction.ofResponseProcessor方法获取响应正文。

我期望这样的日志(当前的实现与 ClientHttpRequestInterceptor 一起使用)包含我需要的所有信息:

{
    "@timestamp": "2019-05-14T07:11:29.089+00:00",
    "@version": "1",
    "message": "GET https://awebservice.com/api",
    "logger_name": "com.sample.config.resttemplate.LoggingRequestInterceptor",
    "thread_name": "http-nio-8080-exec-5",
    "level": "TRACE",
    "level_value": 5000,
    "traceId": "e65634ee6a7c92a7",
    "spanId": "7a4d2282dbaf7cd5",
    "spanExportable": "false",
    "X-Span-Export": "false",
    "X-B3-SpanId": "7a4d2282dbaf7cd5",
    "X-B3-ParentSpanId": "e65634ee6a7c92a7",
    "X-B3-TraceId": "e65634ee6a7c92a7",
    "parentId": "e65634ee6a7c92a7",
    "method": "GET",
    "uri": "https://awebservice.com/api",
    "body": "[Empty]",
    "elapsed_time": 959,
    "status_code": 200,
    "status_text": "OK",
    "content_type": "text/html",
    "response_body": "{"message": "Hello World!"}"
}
Run Code Online (Sandbox Code Playgroud)

有人设法用 Spring WebClient 做这样的事情吗?或者如何继续使用 Spring WebClient 跟踪请求/响应问题?

小智 3

您可以使用filter(),如下所示:

this.webClient = WebClient.builder().baseUrl("your_url")
            .filter(logRequest())
            .filter(logResponse())
            .build();

private ExchangeFilterFunction logRequest() {
    return (clientRequest, next) -> {
        log.info("Request: {} {}", clientRequest.method(), clientRequest.url());
        clientRequest.headers()
                .forEach((name, values) -> values.forEach(value -> log.info("{}={}", name, value)));
        return next.exchange(clientRequest);
    };
}

private ExchangeFilterFunction logResponse() {
    return ExchangeFilterFunction.ofResponseProcessor(clientResponse -> {
        log.info("Response: {}", clientResponse.headers().asHttpHeaders().get("property-header"));
        return Mono.just(clientResponse);
    });
}
Run Code Online (Sandbox Code Playgroud)

  • 我知道这一点,但这不会生成在同一日志中包含请求信息和响应信息的日志。我正在寻找一种同时记录两者的方法。该答案生成一份请求日志和一份响应日志。 (4认同)
  • 您无法使用 Exchange 筛选器记录请求正文 (4认同)