'Spring WebClient - how to log sucessfull and failed response?
I'm trying to create a REST call using WebClient
statusWebClient.post()
.uri(url)
.bodyValue(createBody(state, number))
.retrieve()
.bodyToFlux(String.class)
.doOnEach(response -> log.debug("Notification was sent to {}, response {}", url, response.get()))
.doOnError(exception -> log.warn("Failed to send notification to {}, cause {}", url, exception.getMessage()))
.subscribe();
I only want to log the call result. On success - log successful message with response body, on 5XX or timeout or other - log the error message. The log should be created in the background (not by the thread that created the call)
But doOnEach is executed each time, doOnError works fine, but there is also
reactor.core.Exceptions$ErrorCallbackNotImplemented: org.springframework.web.reactive.function.client.WebClientResponseException$InternalServerError: 500 Internal Server Error from POST
logged in the logfile.
I've I also seen in few tutorials onSuccess method, but in my setup there is such method.
How can I log success and fail messages?
Solution 1:[1]
This is what I created. Seems that works fine
statusWebClient.post()
.uri(url)
.bodyValue(createTerminalStatusBody(state, msisdn))
.retrieve()
.bodyToMono(String.class)
.subscribeOn(Schedulers.boundedElastic())
.doOnSuccess(response -> log.debug("Notification was sent to {}, response {}", url, response))
.doOnError(exception -> log.warn("Failed to send notification to {}, cause {}", url, exception.getMessage()))
.onErrorResume(throwable -> Mono.empty())
.subscribe();
Solution 2:[2]
You could setup custom filters for the WebClient
WebClient.builder()
.filter(logRequest())
.filter(logResponse());
private ExchangeFilterFunction logRequest() {
return (clientRequest, next) -> {
log.debug("Request: {} {}", clientRequest.method(), clientRequest.url());
return next.exchange(clientRequest);
};
}
private ExchangeFilterFunction logResponse() {
return ExchangeFilterFunction.ofResponseProcessor(clientResponse -> {
log.debug("Response Status: {}", clientResponse.statusCode());
return Mono.just(clientResponse);
});
}
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 | Mateusz |
| Solution 2 | Alex |
