how to log Spring 5 WebClient call

Seb picture Seb · Sep 11, 2017 · Viewed 43.6k times · Source

I'm trying to log a request using Spring 5 WebClient. Do you have any idea how could I achieve that?

(I'm using Spring 5 and Spring boot 2)

The code looks like this at the moment:

try {
    return webClient.get().uri(url, urlParams).exchange().flatMap(response -> response.bodyToMono(Test.class))
            .map(test -> xxx.set(test));
} catch (RestClientException e) {
    log.error("Cannot get counter from opus", e);
    throw e;
}

Answer

Ruslan Stelmachenko picture Ruslan Stelmachenko · Oct 21, 2017

You can easily do it using ExchangeFilterFunction

Just add the custom logRequest filter when you create your WebClient using WebClient.Builder.

Here is the example of such filter and how to add it to the WebClient.

@Slf4j
@Component
public class MyClient {

    private final WebClient webClient;

    // Create WebClient instance using builder.
    // If you use spring-boot 2.0, the builder will be autoconfigured for you
    // with the "prototype" scope, meaning each injection point will receive
    // a newly cloned instance of the builder.
    public MyClient(WebClient.Builder webClientBuilder) {
        webClient = webClientBuilder // you can also just use WebClient.builder()
                .baseUrl("https://httpbin.org")
                .filter(logRequest()) // here is the magic
                .build();
    }

    // Just example of sending request
    public void send(String path) {
        ClientResponse clientResponse = webClient
                .get().uri(uriBuilder -> uriBuilder.path(path)
                        .queryParam("param", "value")
                        .build())
                .exchange()
                .block();
        log.info("Response: {}", clientResponse.toEntity(String.class).block());
    }

    // This method returns filter function which will log request data
    private static ExchangeFilterFunction logRequest() {
        return ExchangeFilterFunction.ofRequestProcessor(clientRequest -> {
            log.info("Request: {} {}", clientRequest.method(), clientRequest.url());
            clientRequest.headers().forEach((name, values) -> values.forEach(value -> log.info("{}={}", name, value)));
            return Mono.just(clientRequest);
        });
    }

}

Then just call myClient.send("get"); and log messages should be there.

Output example:

Request: GET https://httpbin.org/get?param=value
header1=value1
header2=value2