Displays log of request and response in Spring Boot

Tram Ho

Show log of request and response in Spring Boot

 

I. Introduction

 

For you as a backend, writing API is no longer strange. But when it comes to problems, log checking is mandatory and indispensable. With the API, viewing log requests and responses is also a powerful way to help develop investigate the cause of bugs. So in this article, I will guide you to the config project so that the show is the most visible and easy to do log.

 

II. Installation and demo example

 

You initialize the spring boot + project and implement some simple API heads as a visual example

 

 

1. Configure Spring Boot Application

This is the most basic way to display log requests and responses

You add the following classes to conduct a demo:

 

 

Project structure:

RequestLoggingFilterConfig Class:

Class UserController:

UserDto Class:

Class UserService:

DemoLoggingApplication Class:

File application.properties:

logging.level.org.springframework.web.filter.CommonsRequestLoggingFilter=DEBUG

Logback.xml file:

You use postman to check the API and show log:

 

 

Observing the console log in the IDE will see that the log is displayed with all requests and responses:

 

 

But you notice the requests and responses have not been “beautiful” and very detailed. So I will go to part 2 to create a full log and more favorable offline.

 

2. Customize the Log show with Controller Advice

 

You add the following class:

*** Class CustomURLFilter: ***

RequestLoggingFilterConfig Class:

Class CustomRequestBodyAdviceAdapter:

Class CustomResponseBodyAdviceAdapter:

LoggingService Class:

Class GsonParserUtils

Results after you run the test here:

 

 

The results display log extremely easy to see and convenient for you to investigate logs

My guide here is the end. Thank you for watching.

Share the news now

Source : Viblo