我已经在Spring Boot中实现了 CommonsRequestLoggingFilter logFilter(),但是它在实际方法执行后记录了所需的信息。我希望所有这些日志在执行实际方法之前先打印出来。目前,我正在使用 Spring Boot 2.1.1 Release 版本。
我已经尝试过 HandlerInterceptor ,但是要准确打印CommonsRequestLoggingFilter所做的事情,需要付出很多努力。我虽然使用了Spring的内置功能。代码如下。
@Bean
public CommonsRequestLoggingFilter logFilter() {
CommonsRequestLoggingFilter filter = new CommonsRequestLoggingFilter();
filter.setIncludeQueryString(true);
filter.setIncludePayload(true);
filter.setIncludeHeaders(true);
filter.setIncludeClientInfo(true);
filter.setMaxPayloadLength(10000);
filter.setAfterMessagePrefix("\n-------setAfterMessagePrefix--------\n");
filter.setAfterMessageSuffix("\n-------------setAfterMessageSuffix-----------------\n");
filter.setBeforeMessagePrefix("\n=========setBeforeMessagePrefix========\n");
filter.setBeforeMessageSuffix("\n===============setBeforeMessageSuffix================\n");
return filter;
}
实际结果看起来像这样
========== setBeforeMessagePrefix ======== uri = / em / login; client = 0:0:0:0:0:0:0:1; headers = {host = [localhost:8080], 连接= [保持有效],内容长度= [95], accept = [application / json],origin = [http://localhost:8080], user-agent = [Mozilla / 5.0(Windows NT 10.0; Win64; x64) AppleWebKit / 537.36(KHTML,例如Gecko)Chrome / 72.0.3626.109 Safari / 537.36],referer = [http://localhost:8080/em/swagger-ui.html], accept-encoding = [gzip,deflate,br],accept-language = [zh-CN,en; q = 0.9], Content-Type = [application / json; charset = UTF-8]} =============== setBeforeMessageSuffix ===============
-----某些异常详细信息---------
------- setAfterMessagePrefix -------- uri = / em / login; client = 0:0:0:0:0:0:0:1; headers = {host = [本地主机:8080], 连接= [保持有效],内容长度= [95], accept = [application / json],origin = [http://localhost:8080], user-agent = [Mozilla / 5.0(Windows NT 10.0; Win64; x64) AppleWebKit / 537.36(KHTML,例如Gecko)Chrome / 72.0.3626.109 Safari / 537.36],referer = [http://localhost:8080/em/swagger-ui.html], accept-encoding = [gzip,deflate,br],accept-language = [zh-CN,en; q = 0.9], Content-Type = [application / json; charset = UTF-8]}; payload = {“ hostName”: “ string”,“ password”:“ string”,“ token”:“ string”,“ userName”: “字符串”} ------------- setAfterMessageSuffix -----------------
但是实际上,我希望将以下内容放在日志文件的顶部以进行分析,如下所述。
------- setAfterMessagePrefix -------- uri = / em / login; client = 0:0:0:0:0:0:0:1; headers = {host = [本地主机:8080], 连接= [保持有效],内容长度= [95], accept = [application / json],origin = [http://localhost:8080], user-agent = [Mozilla / 5.0(Windows NT 10.0; Win64; x64) AppleWebKit / 537.36(KHTML,例如Gecko)Chrome / 72.0.3626.109 Safari / 537.36],referer = [http://localhost:8080/em/swagger-ui.html], accept-encoding = [gzip,deflate,br],accept-language = [zh-CN,en; q = 0.9], Content-Type = [application / json; charset = UTF-8]}; payload = {“ hostName”: “ string”,“ password”:“ string”,“ token”:“ string”,“ userName”: “字符串”} ------------- setAfterMessageSuffix -----------------
-------------某些例外------------