Spring Boot配置access log
Spring Boot集成logback可以解决大部分日志需求,但是缺少访问日志,这在生产环境也是一种隐患。配合Tomcat Access Log可以完美解决这个问题
配置
在Spring boot中使用了内嵌的tomcat,可以通过server.tomcat.accesslog配置tomcat 的access日志
默认日志如下:
1 | server.tomcat.accesslog.buffered=true # 缓存日志定期刷新输出(建议设置为true,否则当有请求立即打印日志对服务的响应会有影响) |
pattern的配置:
%a- 远程ip地址,注意不一定是原始ip地址,中间可能经过nginx等的转发%A- 本地ip%b- 发送的字节数,不包括HTTP标头,或者如果没有字节发送则使用’ - ‘%B- 发送的字节数,不包括HTTP标头%h- 远程主机名(或IP地址,如果连接器的enableLookups为false)%H- 请求协议%l- Remote logical username from identd (always returns ‘-‘)%m- 请求方法(GET,POST)%p- 接受请求的本地端口%q- 查询字符串(如果存在则用’?’作为前缀,否则为空字符串)%r- HTTP请求的第一行(包括请求方法,请求的URI)%s- HTTP的响应代码,如:200,404%S- User session ID%t- 日期和时间,Common Log Format格式%u- 被认证的远程用户%U- Requested URL path%v- Local server name%D- Time taken to process the request, in millis%T- Time taken to process the request, in seconds%I- 当前请求的线程名,可以和打印的log对比查找问题
Access log 也支持将cookie、header、session或者其他在ServletRequest中的对象信息打印到日志中,其配置遵循Apache配置的格式({xxx}指值的名称):
%{xxx}ifor incoming headers,request header信息%{xxx}ofor outgoing response headers,response header信息%{xxx}cfor a specific cookie%{xxx}rxxx is an attribute in the ServletRequest%{xxx}sxxx is an attribute in the HttpSession%{xxx}txxx is an enhanced SimpleDateFormat pattern (see Configuration Reference document for details on supported time patterns)
内置模板
server.tomcat.accesslog.pattern中内置了两个日志格式模板,分别是common和combined
common:%h %l %u %t "%r" %s %bcombined:%h %l %u %t "%r" %s %b "%{Referer}i" "%{User-Agent}i"