Lejdi Prifti

0 %
Lejdi Prifti
Software Engineer
Web3 Developer
ML Practitioner
  • Residence:
    Albania
  • City:
    Tirana
  • Email:
    info@lejdiprifti.com
English
Italian
French
Spring
React & Angular
Machine Learning
Docker & Kubernetes
AWS & Cloud
Team Player
Communication
Time Management
  • Java, JavaScript, Python
  • AWS, Kubernetes, Azure
  • Bootstrap, Materialize
  • Stylus, Sass, Less
  • Blockchain, Ethereum, Solidity
  • React, React Native, Flutter
  • GIT knowledge
  • Machine Learning, Deep Learning
0

No products in the basket.

Log HTTP requests with RestTemplate

19. October 2023

In this short article, I want to emphasise how important it is to log the HTTP requests when using RestTemplate or WebClient. Logging HTTP requests 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.

Buy Me A Coffee
Posted in SpringBootTags:
Write a comment