使用body记录过滤器响应以进行REST

时间:2018-03-24 13:51:55

标签: java spring rest spring-boot logging

我正在尝试使用正文来记录我的REST服务的所有请求和响应。 到目前为止,对于日志记录请求,我使用Spring内置解决方案来记录有效负载RequestLoggingFilterConfig,并且它运行良好。

现在我正在为日志响应寻找类似的解决方案。 问题是我如何从REST身份记录整个响应,并且只能通过配置文件来完成?

我对请求的配置

@Configuration
public class RequestLoggingFilterConfig {

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

和application.properties

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

1 个答案:

答案 0 :(得分:0)

application.properties logging.level。* help刚刚配置了日志记录级别,用于处理日志记录响应, 您需要某种可以拦截您的响应的中间件

1:自定义过滤器过滤器是处理此问题的最佳方法之一 例如:

    @Component
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public class WebFilter implements Filter {

        private static final Logger logger = LoggerFactory.getLogger(WebFilter.class);

        private static final boolean CONDITION = true;

        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
            logger.debug("Initiating WebFilter >> ");
        }

        @Override
        public void doFilter(ServletRequest request, ServletResponse response,
                FilterChain chain) throws IOException, ServletException {

                chain.doFilter(requestWrapper, response); 

                // log your response here
        }

        @Override
        public void destroy() {
            logger.debug("Destroying WebFilter >> ");
        }
    }

register your filter 
@Bean
public FilterRegistrationBean someFilterRegistration() {

    FilterRegistrationBean registration = new FilterRegistrationBean();
    registration.setFilter(someFilter());
    registration.addUrlPatterns("/api/*");
    registration.addInitParameter("paramName", "paramValue");
    registration.setName("someFilter");
    registration.setOrder(1);
    return registration;
} 

public Filter someFilter() {
    return new WebFilter();
}


2:InterceptorAdapter

您可以扩展HandlerInterceptorAdapter并覆盖afterCompletion方法 公开无效,完成后,

@Component
public class LogginInterceptor 
  extends HandlerInterceptorAdapter {

    @Override
    public void afterCompletion(
      HttpServletRequest request, 
      HttpServletResponse response, 
      Object handler, 
      Exception ex) {
        // log your response here
    }
}

3:AOP 您还可以使用神奇的AOP来处理使用@After的响应 IMPL