如何记录spring-webflux WebClient请求+响应详细信息(实体,标头和elasped_time)?

时间:2019-05-15 08:35:29

标签: spring-boot logging spring-webflux spring-web spring-webclient

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

使用Spring RestTemplate,我们可以使用ClientHttpRequestInterceptor。我发现ExchangeFilterFunction是春季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来跟踪请求/响应问题?

2 个答案:

答案 0 :(得分:0)

您可以使用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);
    });
}

答案 1 :(得分: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)
        }
    }
}
相关问题