本教程展示了如何使用CommonsRequestLoggingFilter 跟踪传入的 HTTP 请求。
有几个选项可以跟踪Spring Boot 2.x应用程序的传入HTTP 请求。最简单的选择之一是使用CommonsRequestLoggingFilter它可以作为 Bean 添加到任何配置类中。请参阅以下示例:
package com.example.testrest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.CommonsRequestLoggingFilter;
@Configuration
public class RequestLoggerFilter {
@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;
}
}
您还需要在 application.properties 文件中设置 CommonsRequestLoggingFilter 的日志记录级别:
logging.level.org.springframework.web.filter.CommonsRequestLoggingFilter=DEBUG
或者作为替代方案,在登录中.xml:
<?xml version="1.0" encoding="UTF-8"?><logger name="org.springframework.web.filter.CommonsRequestLoggingFilter">
<level value="DEBUG"/>
</logger>
添加后,您将能够在 Spring 引导控制台中看到传入的请求:
2020-04-09 15:53:06.554 DEBUG 13536 --- [nio-8080-exec-1] o.s.w.f.CommonsRequestLoggingFilter : Before request [uri=/list] 2020-04-09 15:53:06.630 DEBUG 13536 --- [nio-8080-exec-1] o.s.w.f.CommonsRequestLoggingFilter : REQUEST DATA : uri=/list]
另一方面,如果要以流的形式接收HTTP请求,可以通过扩展HandlerInterceptorAdapter类来实现:
@Component public class CustomHandlerInterceptorAdapter extends HandlerInterceptorAdapter {
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
ServletRequest servletRequest = new ContentCachingRequestWrapper(request);
servletRequest.getParameterMap();
// Read inputStream and log it
return true;
}
}
请注意,当您处理输入流时,您不能将它们读取两次!