Log HTTP requests with RestTemplate
In this short article, I want to emphasise how important it is to log the HTTP request when using RestTemplate or WebClient. This could save you a lot of time when debugging your application.
Typically within a microservice architecture, synchronous communication between microservices is facilitated through the use of HTTP requests. They communicate with each other quite a bit most of the time. If logging is not configured correctly, debugging may be challenging.
That is the reason why I encourage you to use interceptors with RestTemplate.
private ClientHttpRequestInterceptor interceptor() {
return new ClientHttpRequestInterceptor() {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
throws IOException {
LogUtil.debug(log, Boolean.TRUE, "SENDING REQUEST");
LogUtil.debug(log, Boolean.TRUE, "URI ====> %s", request.getURI());
LogUtil.debug(log, Boolean.TRUE, "METHOD ====> %s", request.getMethod());
LogUtil.debug(log, Boolean.TRUE, "BODY ====> %s", new String(body, StandardCharsets.UTF_8));
LogUtil.debug(log, Boolean.TRUE, "HEADERS ====> %s", request.getHeaders());
return execution.execute(request, body);
}
};
}
An interceptor is defined in the code above. The uri, method, content, and headers of each request that is made from the RestTemplate bean it is configured upon will be logged.
@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
if (log.isDebugEnabled()) {
restTemplate.setInterceptors(List.of(interceptor()));
}
return restTemplate;
}
We use the method setInterceptors
and provide it an array containing our newly constructed interceptor to add it to the RestTemplate bean.
We only take this action in the event that debugging is enabled, limiting its use to local development environments.