Log every rest request in spring boot

Most of the time we came to the scenario where we need to log every request came to the controller in spring boot.

Log every request of Controller in spring boot

There are some ways to tackle this thing, We can use LoggerFactory and create one UTIL class which will write the request body for the log file.

Read Also: Log4j2 in Spring boot Application

But In this article, we will learn about any ready-made Log Writer in Spring boot Framework?

Let’s Start

Objective

We need to write the config for the logging of every Request came to Controller.

Solution

Spring boot provides Filter for Writing every Request in Log files.

Follow below steps

We first need to Create one Java config for the Request Logging Filter.

@Configuration
public class RequestLoggingFilterConfig {
  
   @Bean
      public CommonsRequestLoggingFilter logFilter() {
          CommonsRequestLoggingFilter filter
            = new CommonsRequestLoggingFilter();
          filter.setIncludeQueryString(true);
          filter.setIncludePayload(true);
          filter.setMaxPayloadLength(10000);
          filter.setIncludeHeaders(false);
          filter.setAfterMessagePrefix("REQUEST DATA : ");
          return filter;
      }

}

Now we need to Enable the Logging Level as DEBUG for the Bean.

In property file, we need to add below line

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

Doing the above things will enable to log every request came to the controller in the log file.

The console would look like as below

2018-08-29 00:27:56.015 DEBUG 18780 --- [nio-8080-exec-8] o.s.w.f.CommonsRequestLoggingFilter      : Before request [uri=/api/v1/product]
2018-08-29 00:27:56.220 ERROR 18780 --- [nio-8080-exec-8] c.w.a.controller.ProductRestController   : addProduct: Bad Request: Mandatory Inputs are not present
2018-08-29 00:27:56.220 DEBUG 18780 --- [nio-8080-exec-8] o.s.w.f.CommonsRequestLoggingFilter      : REQUEST DATA : uri=/api/v1/product;payload={
  "active": true,
  "basePrice": 0,
  "description": "string",
  "endDate": "2018-08-28T18:57:51.680Z",
  "id": 0,
  "imageUrl": "string",
  "productName": "string",
  "serviceId": 0,
  "startDate": "2018-08-28T18:57:51.680Z"
}]

I hope this will help you in saving your time not to write a Util for doing this work in spring boot

If you have any issue please leave us a comment. If you like this post please share it with your friends

 

You may also like...

1 Response

  1. whippet says:

    I’ve leаrn several good stuff here. Definitely price bookmarқing for revisitіng.
    I ѡonder how muϲh effort you place to ⅽreate the sort
    of fantastic informativе weƅ site.

Leave a Reply

Your email address will not be published. Required fields are marked *