How to output logs at a different level then intended by spring?

242 Views Asked by At

I can log every incoming request by setting

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

The requests will then be logged at level DEBUG. But I want them to be logged at level INFO instead. I don't think there is a flag for it but the loglevel is hardcoded by spring. But is there maybe some kind of filter that can intercept these logs and change their log level?

1

There are 1 best solutions below

0
Angshuman On

You can use a filter that catches the request and logs it at the appropriate log level. Also, it would be wise to set it to HIGHEST_PRECEDENCE so that it is executed before any other filters in the filter chain and logs the requests before some other filter modifies it.

@Order(Ordered.HIGHEST_PRECEDENCE)
public class CustomRequestLoggingFilter extends CommonsRequestLoggingFilter {
    private static final Logger logger = LoggerFactory.getLogger(CustomRequestLoggingFilter.class);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        // you have access to the HttpServletRequest obj so log whatever you want
        logger.info("Request:" + request.getMethod() + " " + request.getRequestURI());
        super.doFilterInternal(request, response, filterChain);

    }

}

Register it as a spring bean in your configuration class.

@Configuration
public class AppConfig {

    @Bean
    public FilterRegistrationBean<CustomRequestLoggingFilter> loggingFilter() {
        FilterRegistrationBean<CustomRequestLoggingFilter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new CustomRequestLoggingFilter());
        registrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE);
        return registrationBean;
    }

}