Logging Request and Response Body In Spring Boot

 

I recently read a Gain Java Knowledge article about logging Spring Boot Request and Response. I really like the idea so I decided to test it in practice.

How to logging Spring Boot Request and Response?

Request and response body for each endpoint we can print using Servlet Filter.

Inside our controller class we will not log any statement but our filter class will log the request and response body for each API call. So this approach will reduce the lines of code and we don’t need to worry about to add log statements in each API to print Request and response body.

The Filter class will be used to log requests and responses for each API. LoggingFilter class will extends OncePerRequestFilter class because this is Filter base class that aims to guarantee a single execution per request dispatch, on any servlet container. It provides a doFilterInternal method with HttpServletRequest and HttpServletResponse arguments.

Conclusion:

In my opinion, this is the best solution to log requests and responses for each API.

Go to source code

Comments

Popular posts from this blog

Debug Java Stream in Intellij Idea

Creating Efficient Docker Images with Spring Boot 2.3

CRUD Goes Even Easier With JPABuddy