Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:
Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.
Get started with mocking and improve your application tests using our Mockito guide:
Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.
Get started with understanding multi-threaded applications with our Java Concurrency guide:
Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:
Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.
But these can also be overused and fall into some common pitfalls.
To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:
Get started with Spring and Spring Boot, through the Learn Spring course:
>> LEARN SPRINGExplore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:
Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.
I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.
You can explore the course here:
Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.
Get started with Spring Data JPA through the guided reference course:
Refactor Java code safely β and automatically β with OpenRewrite.
Refactoring big codebases by hand is slow, risky, and easy to put off. Thatβs where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.
Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions β one for newcomers and one for experienced users. Youβll see how recipes work, how to apply them across projects, and how to modernize code with confidence.
Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.
1. Overview
In this tutorial, we are going to show how to customize Springβs WebClient β a reactive HTTP client β to log requests and responses.
2. WebClient
WebClient is a reactive and non-blocking interface for HTTP requests, based on Spring WebFlux. It has a functional, fluent API with reactive types for declarative composition.
Behind the scenes, WebClient calls an HTTP client. Reactor Netty is the default and reactive HttpClient of Jetty is also supported. Moreover, itβs possible to plug other implementations of HTTP client by setting up a ClientConnector for WebClient.
3. Logging Requests and Responses
The default HttpClient used by WebClient is the Netty implementation, so after we change the reactor.netty.http.client logging level to DEBUG, we can see some request logging, but if we need a customized log, we can configure our loggers via WebClient#filters:
WebClient
.builder()
.filters(exchangeFilterFunctions -> {
exchangeFilterFunctions.add(logRequest());
exchangeFilterFunctions.add(logResponse());
})
.build()
In this code snippet, weβve added two separate filters to log the request and the response.
Letβs implement logRequest by using ExchangeFilterFunction#ofRequestProcessor:
ExchangeFilterFunction logRequest() {
return ExchangeFilterFunction.ofRequestProcessor(clientRequest -> {
if (log.isDebugEnabled()) {
StringBuilder sb = new StringBuilder("Request: \n");
//append clientRequest method and url
clientRequest
.headers()
.forEach((name, values) -> values.forEach(value -> /* append header key/value */));
log.debug(sb.toString());
}
return Mono.just(clientRequest);
});
}
logResponse is the same, but we have to use ExchangeFilterFunction#ofResponseProcessor instead.
Now we can change the reactor.netty.http.client log level to INFO or ERROR to have a cleaner output.
4. Logging Request and Response with Body
HTTP clients have features to log the bodies of requests and responses. Thus, to achieve the goal, we are going to use a log-enabled HTTP client with our WebClient.
We can do this by manually setting WebClient.Builder#clientConnector β letβs see with Jetty and Netty HTTP clients.
4.1. Logging with Jetty HttpClient
First, letβs add the Maven dependency for jetty-reactive-httpclient to our pom:
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-reactive-httpclient</artifactId>
<version>1.1.6</version>
</dependency>
Then weβre going to create a customized Jetty HttpClient:
SslContextFactory.Client sslContextFactory = new SslContextFactory.Client();
HttpClient httpClient = new HttpClient(sslContextFactory) {
@Override
public Request newRequest(URI uri) {
Request request = super.newRequest(uri);
return enhance(request);
}
};
Here, weβve overridden HttpClient#newRequest, then wrapped the Request in a log enhancer.
Next, we need to register events with the request so that we can log as each part of the request becomes available:
Request enhance(Request request) {
StringBuilder group = new StringBuilder();
request.onRequestBegin(theRequest -> {
// append request url and method to group
});
request.onRequestHeaders(theRequest -> {
for (HttpField header : theRequest.getHeaders()) {
// append request headers to group
}
});
request.onRequestContent((theRequest, content) -> {
// append content to group
});
request.onRequestSuccess(theRequest -> {
log.debug(group.toString());
group.delete(0, group.length());
});
group.append("\n");
request.onResponseBegin(theResponse -> {
// append response status to group
});
request.onResponseHeaders(theResponse -> {
for (HttpField header : theResponse.getHeaders()) {
// append response headers to group
}
});
request.onResponseContent((theResponse, content) -> {
// append content to group
});
request.onResponseSuccess(theResponse -> {
log.debug(group.toString());
});
return request;
}
Finally, we have to build the WebClient instance:
WebClient
.builder()
.clientConnector(new JettyClientHttpConnector(httpClient))
.build()
Of course, as we did before, weβll need to set the log level of RequestLogEnhancer to DEBUG.
4.2. Logging with Netty HttpClient
First, letβs create a Netty HttpClient:
HttpClient httpClient = HttpClient
.create()
.wiretap(true)
Having enabled the wiretap, each request and response will be logged in full detail.
Next, we have to set the log level of Nettyβs client package reactor.netty.http.client to DEBUG:
logging.level.reactor.netty.http.client=DEBUG
Now, letβs build the WebClient:
WebClient
.builder()
.clientConnector(new ReactorClientHttpConnector(httpClient))
.build()
Our WebClient will log every request and response in full detail, but the default format of Netty built-in logger contains both Hex and Text representation of bodies and also a lot of data about request and response events.
So, if we need only the text logger for Netty, we can configure the HttpClient:
HttpClient httpClient = HttpClient
.create()
.wiretap("reactor.netty.http.client.HttpClient",
LogLevel.DEBUG, AdvancedByteBufFormat.TEXTUAL);
5. Conclusion
In this tutorial, weβve used several techniques for logging request and response data while using Spring WebClient.
