6

How can we log request payload/parameters before and after processing in filter of spring boot application.

For example:

/api/users/auth Body: `name:Vijay, place:bangalore...`

I have to log request body in filter before and after processing the request.

1
  • you can use java logging utility or other frameworks such as log4j or logback Commented Sep 19, 2017 at 3:09

1 Answer 1

7

Spring Boot provides the CommonsRequestLoggingFilter for this purpose.

You configure it like so:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.CommonsRequestLoggingFilter;


@Configuration
public class RequestLoggingFilterConfigurer {

    @Bean
    public CommonsRequestLoggingFilter requestLoggingFilter() {
        CommonsRequestLoggingFilter filter = new CommonsRequestLoggingFilter();
        filter.setIncludeQueryString(true);
        filter.setIncludePayload(true);
        // truncate payloads
        filter.setMaxPayloadLength(1000);
        filter.setIncludeHeaders(false);
        filter.setAfterMessagePrefix("Request received: ");
        return filter;
    }
}

And add a logger definition to your logback.xml like so:

<logger name="org.springframework.web.filter.CommonsRequestLoggingFilter" level="DEBUG">
    <appender-ref ref="REQUEST_RESPONSE_FILE_APPENDER"/>
</logger> 
Sign up to request clarification or add additional context in comments.

2 Comments

Doesn't seem to work for Spring Boot 2 Webflux with Netty: Error:(13, 15) java: cannot access javax.servlet.Filter class file for javax.servlet.Filter not found
CommonsRequestLoggingFilter also puts the request payload in the "after request" log line. Kinda confusing matters if I want to log the response body/payload too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.