在Spring Boot中仅在请求日志CommonsRequestLoggingFilter之前设置

时间:2019-02-04 11:28:35

标签: java spring spring-boot logging

CommonsRequestLoggingFilter在记录请求方面非常出色,但就我而言,它在处理请求之前和之后都记录相同的内容,这是重复的和冗余的。我想摆脱请求处理后的日志,但找不到方法。有什么想法吗?

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

@Configuration
public class RequestLoggingFilterConfig {

    @Bean
    public CommonsRequestLoggingFilter logFilter() {
        CommonsRequestLoggingFilter filter = new CommonsRequestLoggingFilter();
        filter.setIncludeClientInfo(true);
        filter.setIncludeHeaders(true);
        filter.setIncludePayload(false);
        filter.setIncludeQueryString(true);
        return filter;
    }
}

我从here.开始

2 个答案:

答案 0 :(得分:0)

org.springframework.web.filter.CommonsRequestLoggingFilter只是org.springframework.web.filter.AbstractRequestLoggingFilter的子类。因此,跳过CommonsRequestLoggingFilter并编写您自己的子类,然后将覆盖的方法floor保留为空。

Unit: milliseconds
 expr      min       lq    mean   median       uq      max neval
 alko 74.08931 83.40157 99.1486 88.61729 116.0893 166.8620   100
  iod 71.12178 78.14680 94.3105 84.97214 111.4073 156.0593   100

使用此类代替org.springframework.web.filter.CommonsRequestLoggingFilter

答案 1 :(得分:0)

为避免重复记录,在实例化 CommonsRequestLoggingFilter 时,您必须覆盖两者之一:

  • beforeRequest()
  • afterRequest()

要禁用 afterRequest() 中的登录,可以将 OP 的代码更改如下:

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

@Configuration
public class RequestLoggingFilterConfig {

    @Bean
    public CommonsRequestLoggingFilter logFilter() {
        CommonsRequestLoggingFilter filter = new CommonsRequestLoggingFilter() {
            @Override
            public void afterRequest(HttpServletRequest request, String message) {
                // No body, we are just overriding the default behavior
            }
        };

        filter.setIncludeClientInfo(true);
        filter.setIncludeHeaders(true);
        filter.setIncludePayload(false);
        filter.setIncludeQueryString(true);
        return filter;
    }
}