Logging Requests and Responses in Spring Boot Using Interceptors

Lakshya Bansal
3 min readOct 4, 2024

--

In microservices, understanding the data flow is crucial for troubleshooting and improving application performance. One effective way to achieve this is by implementing logging for incoming requests and outgoing responses. In Spring Boot, we can use Interceptors to intercept HTTP requests and responses. In this blog post, we will explore how to create a Spring Boot application that uses Interceptors for logging purposes.

What Are Spring Boot Interceptors?

Spring Boot Interceptors allow you to preprocess requests and responses before they reach the controller or after the controller has processed them. They are part of the Spring MVC framework and can be used to add custom behaviour, such as logging, authentication, or modifying requests and responses.

You can also find the introductory article related to Interceptors at the link below:

Setting Up a Spring Boot Project

To begin, create a new Spring Boot project using Spring Initializr with the following dependencies:

  • Spring Web

Project Structure

Once you have set up your project, the structure should look something like this:

src
└── main
├── java
│ └── com
│ └── example
│ └── logging
│ ├── LoggingApplication.java
│ ├── interceptor
│ │ └── LoggingInterceptor.java
│ └── controller
│ └── HelloController.java
└── resources
└── application.properties

Implementing the Logging Interceptor

Step 1: Create the Interceptor

Create a new class named LoggingInterceptor inside the interceptor package. This class will implement the HandlerInterceptor interface.

package com.example.logging.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoggingInterceptor implements HandlerInterceptor {
private static final Logger logger = LoggerFactory.getLogger(LoggingInterceptor.class);

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
logger.info("Incoming Request: Method = {}, URI = {}", request.getMethod(), request.getRequestURI());
return true; // Continue the request
}

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
logger.info("Outgoing Response: Status = {}", response.getStatus());
}
}

Step 2: Register the Interceptor

Next, you need to register the LoggingInterceptor in your Spring Boot application. Create a configuration class named WebConfig.

package com.example.logging.config;

import com.example.logging.interceptor.LoggingInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

@Autowired
private LoggingInterceptor loggingInterceptor;

@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(loggingInterceptor);
}
}

Step 3: Creating a Sample Controller

To test our interceptor, let’s create a simple REST controller named HelloController.

package com.example.logging.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

@GetMapping("/hello")
public String sayHello() {
return "Hello, World!";
}
}

Testing the Application

  1. Run your Spring Boot application.
  2. Open your web browser or a tool like Postman and make a GET request to http://localhost:8080/hello.

Expected Logs

In your console, you should see logs similar to the following:

INFO  com.example.logging.interceptor.LoggingInterceptor - Incoming Request: Method = GET, URI = /hello
INFO com.example.logging.interceptor.LoggingInterceptor - Outgoing Response: Status = 200

Conclusion

In this blog post, we learned how to use Spring Boot Interceptors to log incoming requests and outgoing responses. This approach provides a clean and modular way to handle logging across your application without cluttering your controller methods. By implementing logging at the interceptor level, you can gain better insights into your application’s behaviour and improve your debugging process.

Feel free to customize the logging information as per your needs, such as adding headers or request parameters.

If you found this story helpful, don’t forget to give it a 👏! Follow me for more insights on Spring Boot and Java development.

Happy coding! 🎉

--

--

No responses yet