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.
