我正在创建一个简单的SpringMVC项目,并希望记录所有传入的请求,包括uri / query / payload / clientIp ...,所有信息。

我可以找到的所有资源都与Spring Boot有关,例如:
https://www.javadevjournal.com/spring/log-incoming-requests-spring/

我还阅读了官方文档,并找到了“ enableLoggingRequestDetails”选项,但是没有任何详细信息,我尝试了但不起作用。
https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-logging

那么,如何在纯SpringMVC框架(没有Spring Boot)中实现呢?

有SpringMVC内置方法吗?

最佳答案

1.您可以实现从OncePerRequestFilter扩展的Filter类,然后每个请求都将通过您的过滤器。然后,您可以在该类中记录所需的内容。

    @Slf4j
    @Component
    public class RequestLoggingFilter extends OncePerRequestFilter {
        @Override
        protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
            log.debug(
                    String.format("FILTERED URL: %s", request.getRequestURI())
            );

            //continue filtering
            filterChain.doFilter(request, response);
        }
    }


2.另一种方法是实现从HandlerInterceptorAdapter扩展的Interceptor类。

    @Slf4j
    @Component
    public class RequestLoggingHandler extends HandlerInterceptorAdapter {

        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            log.debug(
                    String.format("HANDLER(pre) URL: %s", request.getRequestURI())
            );

            return super.preHandle(request, response, handler);
        }

        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
            log.debug(
                    String.format("HANDLER(post) URL: %s", request.getRequestURI())
            );

            super.postHandle(request, response, handler, modelAndView);
        }
    }


但是您必须通过通过配置显式添加它来启用此拦截器。

    @Configuration
    public class WebApplicationConfiguration implements WebMvcConfigurer {

        @Setter(onMethod_ = @Autowired)
        private RequestLoggingHandler requestLogger;

        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(requestLogger);
        }
    }


3.另一种方法是使用标准的CommonsRequestLoggingFilter。

这样,您应该使用以下配置对其进行配置:

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


然后将其启用到logback.xml中:

<logger name="org.springframework.web.filter.CommonsRequestLoggingFilter">
    <level value="DEBUG" />
</logger>

07-27 18:10