Spring Boot - How to log all requests and responses with exceptions in single place?

Matheus Mello
Matheus Mello
September 2, 2023
Cover Image for Spring Boot - How to log all requests and responses with exceptions in single place?

📝 How to Log All Requests and Responses with Exceptions in a Single Place with Spring Boot

Are you working on a REST API with Spring Boot? Do you need to log all requests, including input parameters, methods, and responses, in a single place? If so, this guide is for you! We'll explore the best practices and provide a concrete example using filters.

The Problem

Let's say you have an API endpoint at http://example.com/api/users/{id}. You want to log all incoming requests with the following details:

  • Method (e.g., GET, POST)

  • Path (e.g., api/users/{id})

  • Query string

  • Client IP

  • Access token (if applicable)

  • Corresponding class method handling the request

  • Request arguments

  • Response (both success and error)

  • Exceptions (if any)

For example, a successful request looks like this:

GET http://example.com/api/users/1

And the corresponding log would be:

{
   "HttpStatus": 200,
   "path": "api/users/1",
   "method": "GET",
   "clientIp": "0.0.0.0",
   "accessToken": "XHGu6as5dajshdgau6i6asdjhgjhg",
   "method": "UsersController.getUser",
   "arguments": {
     "id": 1 
   },
   "response": {
      "user": {
        "id": 1,
        "username": "user123",
        "email": "user123@example.com"   
      }
   },
   "exceptions": []       
}

On the other hand, an error request could look like this:

GET http://example.com/api/users/9999

And the corresponding log:

{
   "HttpStatus": 404,
   "errorCode": 101,                 
   "path": "api/users/9999",
   "method": "GET",
   "clientIp": "0.0.0.0",
   "accessToken": "XHGu6as5dajshdgau6i6asdjhgjhg",
   "method": "UsersController.getUser",
   "arguments": {
     "id": 9999 
   },
   "returns": {},
   "exceptions": [
     {
       "exception": "UserNotFoundException",
       "message": "User with id 9999 not found",
       "exceptionId": "adhaskldjaso98d7324kjh989",
       "stacktrace": "..................."    
   ]       
}

The Solution: Filters

To achieve logging of all requests and responses with exceptions in a single place, we recommend using filters in Spring Boot. Filters intercept incoming requests before they reach the controller and allow you to add custom logic.

Here's an example implementation of a filter that logs the desired information:

import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class RequestLoggingFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        String requestUrl = httpRequest.getRequestURI();
        String method = httpRequest.getMethod();
        String clientIp = httpRequest.getRemoteAddr();
        // Access token retrieval logic here

        // Log the request details

        try {
            chain.doFilter(request, response);
        } catch (Exception e) {
            // Log and handle exceptions
        }

        // Log the response details
    }

    // Other filter lifecycle methods
}

In this filter, we extract the necessary information from the HttpServletRequest, such as the request URL, method, and client IP. You can also include logic to retrieve the access token if needed.

Within the doFilter method, you can log the request details. You can use your preferred logging library, such as Log4j or SLF4J. Remember to catch any exceptions thrown during the filter chain processing and handle them accordingly.

After the chain.doFilter line, you can log the response details. You have access to the HttpServletResponse object, which contains the HTTP status code and the response body. Again, use your chosen logging library to log this information.

Wrapping Up

Logging all requests and responses with exceptions in a single place with Spring Boot is achievable using filters. By implementing a custom filter and adding the necessary logic, you can log the desired information and handle exceptions effectively.

Now it's your turn! Implement the filter in your Spring Boot application and enhance your logging capabilities. Share your experiences and thoughts in the comments below. Happy logging! 😄📝

Take Your Tech Career to the Next Level

Our application tracking tool helps you manage your job search effectively. Stay organized, track your progress, and land your dream tech job faster.

Your Product
Product promotion

Share this article

More Articles You Might Like

Latest Articles

Cover Image for How can I echo a newline in a batch file?
batch-filenewlinewindows

How can I echo a newline in a batch file?

Published on March 20, 2060

🔥 💻 🆒 Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Cover Image for How do I run Redis on Windows?
rediswindows

How do I run Redis on Windows?

Published on March 19, 2060

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! 🚀 Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Cover Image for Best way to strip punctuation from a string
punctuationpythonstring

Best way to strip punctuation from a string

Published on November 1, 2057

# The Art of Stripping Punctuation: Simplifying Your Strings 💥✂️ Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Cover Image for Purge or recreate a Ruby on Rails database
rakeruby-on-railsruby-on-rails-3

Purge or recreate a Ruby on Rails database

Published on November 27, 2032

# Purge or Recreate a Ruby on Rails Database: A Simple Guide 🚀 So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? 🤔 Well, my