'How to log every response from WebClient?

WebClient in spring webflux offers three different ways to hook on end of the response:

webClient.post().uri().body().retrieve().bodyToMono(String.class)
...
.doOnTerminte()
.doAfterTerminate()
.doFinally();

My goal is to log every response (headers + statuscode), regardless of the outcome.

How can I know which method states above is correct for this purpose?



Solution 1:[1]

I've always found this API a bit cumbersome indeed, but I think relying on ResponseEntity could simplify your case:

.retrieve()
.toEntity(String.class)
// 4xx and 5xx responses result in a WebClientResponseException:
.onErrorResume(WebClientResponseException.class, e -> Mono.just(toEntity(e)))
.doOnNext(entity -> log.info(/* entity.getHeaders(), entity.getStatusCode(), etc. */))

With toEntity(e) roughly like below:

static <T> ResponseEntity<T> toEntity(WebClientResponseException e) {
    return ResponseEntity
            .status(e.getStatusCode())
            .headers(e.getHeaders())
            .build();
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 sp00m