Logging all request and responses using Spring Boot Actuator

Viewed 17303

I am using Spring Boot and REST services using @RestController. I want to log all requests and responses with a payload. How can I do this using Spring Boot Actuator? When I using:

    @Bean
    public ServletContextRequestLoggingFilter requestLoggingFilter() {
        ServletContextRequestLoggingFilter loggingFilter = new ServletContextRequestLoggingFilter();
        loggingFilter.setIncludeClientInfo(true);
        loggingFilter.setIncludeQueryString(true);
        loggingFilter.setIncludePayload(true);
        loggingFilter.setIncludeHeaders(true);
        loggingFilter.setMaxPayloadLength(10000);
        loggingFilter.setAfterMessagePrefix("REQUEST DATA : ");
        return loggingFilter;
    }

I get only Requests, but not Responses.

2 Answers

See baeldung Spring – Log Incoming Requests guide, specifically the 5th section Spring Built-In Request Logging

TL;DR If you are using Spring Boot you can configure that easily like this:

@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;
    }
}

General note: In production application you should be careful logging payloads as they may contain private user data that should not be logged from privacy considerations.

You can use addInterceptors method of WebMvcConfigurer

@Configuration
@EnableWebMvc
class WebMvcConfiguration : WebMvcConfigurer {

  override fun addInterceptors(registry: InterceptorRegistry) {
      registry.addInterceptor(LoggingInterceptor())
  }
}

And here is good example for interceptor.

UPDATED

You can override the Spring LoggingFilter

public class CustomLoggingFilter extends LoggingFilter
{
     @Override
     protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException
     {
          super.doFilterInternal(request, response, filterChain);
     }
}

@Configuration
public Config {
    @Bean
    public CustomLoggingFilter loggingFilter()
    {
        return new CustomLoggingFilter();
    }
}

Not sure about your format, but you can try to use:

logging:
  level: 
    org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor: debug //response
    org.apache.coyote.http11.Http11InputBuffer: debug //request
Related