how to log Spring 5 WebClient call
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. This method is NOT part of the answer
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
Edit
Some people pointed out in comments that block()
is bad practice etc. I want to clarify: block()
call here is just for demo purposes. The request logging filter will work anyway. You will not need to add block()
to your code to make ExchangeFilterFunction
work. You can use WebClient
to perform a http-call in a usual way, chaining methods and returning Mono
up the stack until someone will subscribe to it. The only relevant part of the answer is logRequest()
filter. You can ignore send()
method altogether - it is not part of the solution - it just demonstrates that filter works.
Some people also asked how to log the response. To log the response you can write another ExchangeFilterFunction
and add it to WebClient
. You can use ExchangeFilterFunction.ofResponseProcessor
helper for this purpose just the same way as ExchangeFilterFunction.ofRequestProcessor
is used. You can use methods of ClientResponse
to get headers/cookies etc.
// This method returns filter function which will log response data
private static ExchangeFilterFunction logResponse() {
return ExchangeFilterFunction.ofResponseProcessor(clientResponse -> {
log.info("Response status: {}", clientResponse.statusCode());
clientResponse.headers().asHttpHeaders().forEach((name, values) -> values.forEach(value -> log.info("{}={}", name, value)));
return Mono.just(clientResponse);
});
}
Don't forget to add it to your WebClient
:
.filter(logResponse())
But be careful and do not try to read the response body here in the filter. Because of the stream nature of it, the body can be consumed only once without some kind of buffering wrapper. So, if you will read it in the filter, you will not be able to read it in the subscriber.
If you really need to log the body, you can make the underlying layer (Netty) to do this. See Matthew Buckett's answer to get the idea.
How to log Spring WebClient response
One option is to use the onStatus
function. The advantage is that you can react differently on different status codes:
.onStatus(HttpStatus::is4xxClientError, res -> {
res.toEntity(String.class).subscribe(
entity -> log.warn("Client error {}", entity)
);
return Mono.error(new HttpClientErrorException(res.statusCode()));}
)
But be aware that this will log asynchronously, that means it might log after you already logged something different. I'm using this way right now but I know it is not perfect, so I will be happy to see better suggestions.
Spring Web Client - How to get response string of failed request wrapped intro retrials
You would need to use response.bodyToMono
in the onStatus
to get response body. The following example shows how to deserialize body into String
but you could define POJO as well.
getClient()
.get()
.uri("http://example.com")
.retrieve()
.onStatus(HttpStatus::isError, response ->
response.bodyToMono(String.class)
.doOnNext(responseBody ->
log.error("Error response from server: {}", responseBody)
)
// throw original error
.then(response.createException())
)
.bodyToMono(ReportListResponse.class)
}
Related Topics
How to Add Button in a Row of Jtable in Swing Java
How to Change the Highlight Color of a Focused Jcombobox
How to Dynamically Build a Multi-Dimensional Array in Java
Converting String to Date Using Simpledateformat Is Returning Random Date
Java: Import Statement VS Fully Qualified Name
Good Examples Using Java.Util.Logging
How to Fix a Compilation Error for Unhandled Exception on Call to Thread.Sleep()
Should I Retrieve Database Record in Struts2 View Layer
How to Quickly Determine If a Method Is Overridden in Java
Changing Shape of Single Point in Jfreechart Xyplot
Try with Resources Introduce Unreachable Bytecode
Calendar.Month Gives Wrong Output
Difference Between Paint() and Paintcomponent()
How to Redirect to Another Action Class Without Using on Struts.Xml
Tablecellrenderer and How to Refresh Cell Background Without Using Jtable.Repaint()
Having a Column Name as Input Parameter of a Preparedstatement
Overriding Object.Equals VS Overloading It
Spring 3 MVC: One-To-Many Within a Dynamic Form (Add/Remove on Create/Update)