3

基本上,我想在一个日志中记录请求/响应信息,其中包含带有 Spring 的正文/标题WebClient

使用 Spring RestTemplate,我们可以使用ClientHttpRequestInterceptor. 我ExchangeFilterFunction为 Spring找到了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!"}"
}

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

4

2 回答 2

1

您可以使用 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);
    });
}
于 2019-05-21T22:07:12.583 回答
0

我不认为您可以调用.bodyToMono两次(一次在过滤器中,然后在您使用客户端的地方再次调用),因此您可能无法在过滤器中记录它。至于其他细节……

WebClient 配置:

@Configuration
class MyClientConfig {

    @Bean
    fun myWebClient(): WebClient {
        return WebClient
            .builder()
            .baseUrl(myUrl)
            .filter(MyFilter())
            .build()
    }
}

过滤器:

class MyFilter : ExchangeFilterFunction {

    override fun filter(request: ClientRequest, next: ExchangeFunction): Mono<ClientResponse> {
        return next.exchange(request).flatMap { response ->

            // log whenever you want here...
            println("request: ${request.url()}, response: ${response.statusCode()}")

            Mono.just(response)
        }
    }
}
于 2021-04-27T06:20:07.940 回答