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;
}
You don't necessarily need to roll your own logger,
reactor.ipc.netty.channel.ChannelOperationsHandler
does it for you. Just configure your logging system for that class to log at DEBUG level:One way to have fewer bugs is to not write code whenever possible.
Nov 2018:
With
spring-webflux:5.1.2.RELEASE
, the above no longer works. Use the following instead:To log headers or form body, set the above to
TRACE
level; however, that's not enough:Mar 2019:
In response to a question in the comment that asked how to log request and response body, I don’t know if Spring has such a logger but
WebClient
is built on Netty, so enabling debug logging for packagereactor.ipc.netty
should work, along with this answer.You can have netty do logging of the request/responses with by asking it todo wiretaping, if you create your Spring WebClient like this then it enables the wiretap option.
and then have your logging setup:
this will log everything for the request/response (including bodies), but the format is not specific to HTTP so not very readable.
You can easily do it using ExchangeFilterFunction
Just add the custom
logRequest
filter when you create yourWebClient
usingWebClient.Builder
.Here is the example of such filter and how to add it to the
WebClient
.Then just call
myClient.send("get");
and log messages should be there.Output example:
@Matthew Buckett answer shows you how to get Netty wire logging. However, the format is not very fancy (it includes hex dump). But it can be easily customized via extending
io.netty.handler.logging.LoggingHandler
Then include it in your
WebClient
configuration:Example:
If you want to suppress useless (for you) log entries like (note
ACTIVE
at the end):You can override
channelActive
and others like so:The answer is based on https://www.baeldung.com/spring-log-webclient-calls
If you don't want to log the body, then this is really easy.
Spring Boot >= 2.1.0
Add the following to application.properties:
The second line causes headers to be included in the log.
Spring Boot < 2.1.0
Add the following to application.properties:
Instead of the second line above, you need to declare a class like this:
Courtesy of this Brian Clozel answer