What Is The Approach For Logging All Requests, Responses, And Exceptions In A Single Place Using Spring Boot In Java?

In Spring Boot, you can log all requests and responses with exceptions in a single place by implementing a custom Filter or Interceptor.

  1. Create a class that extends OncePerRequestFilter for a Filter or implements HandlerInterceptor for an Interceptor.

Filter Example:

@Component
public class RequestResponseLoggingFilter extends OncePerRequestFilter {
    
    private static final Logger logger = LoggerFactory.getLogger(RequestResponseLoggingFilter.class);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        try {
            // Log the request
            logger.info("Request: {} {}", request.getMethod(), request.getRequestURI());

            // Continue the request processing
            filterChain.doFilter(request, response);

        } catch (Exception ex) {
            // Log any exceptions
            logger.error("Exception: {}", ex.getMessage());

            // Re-throw the exception
            throw ex;

        } finally {
            // Log the response
            logger.info("Response: {}", response.getStatus());
        }
    }
}

Interceptor Example:

@Component
public class RequestResponseLoggingInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(RequestResponseLoggingInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // Log the request
        logger.info("Request: {} {}", request.getMethod(), request.getRequestURI());

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        if (ex != null) {
            // Log any exceptions
            logger.error("Exception: {}", ex.getMessage());
        }

        // Log the response
        logger.info("Response: {}", response.getStatus());
    }
}
  1. Register the Filter or Interceptor in your application configuration class, such as WebMvcConfigurer for Interceptors or FilterRegistrationBean for Filters.

Filter Registration Example:

@Configuration
public class AppConfig {

    @Bean
    public FilterRegistrationBean<RequestResponseLoggingFilter> loggingFilter() {
        FilterRegistrationBean<RequestResponseLoggingFilter> registrationBean = new FilterRegistrationBean<>();

        registrationBean.setFilter(new RequestResponseLoggingFilter());
        registrationBean.addUrlPatterns("/*");

        return registrationBean;
    }
}

Interceptor Registration Example:

@Configuration
public class AppConfig implements WebMvcConfigurer {

    @Autowired
    private RequestResponseLoggingInterceptor loggingInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loggingInterceptor).addPathPatterns("/**");
    }
}

By adding either the Filter or Interceptor to your Spring Boot application, all requests and responses will be logged, including any exceptions that occur during request processing.

About the Author Rex

I'm a passionate tech blogger with an insatiable love for programming! From my early days tinkering with code, I've delved into web dev, mobile apps, and AI. Sharing insights and tutorials with the world is my joy, connecting me to a global community of like-minded tech enthusiasts. Python holds a special place in my heart, but I embrace all challenges. Constantly learning, I attend tech conferences, contribute to open-source projects, and engage in code review sessions. My ultimate goal is to inspire the next generation of developers and contribute positively to the ever-evolving tech landscape. Let's code together!