springboot 1.x 内置tomcat服务器,其中的access log日志可以记录每次请求、响应的一些关键信息,这为我们排查分析系统性能有很大的帮助。
但springboot默认是不开启access log的,下面介绍下access log的开启方式和一些日志格式配置。
springboot的每个yml文件中的配置项,都会有与之对应的一个java对象与之对应,对象上一般使用@ConfigurationProperties注解自动加载配置,如果没有在yml中显示的加入配置项,该类也可以提供默认的阈值。tomcat的access log配置也有相应的配置类。如下:
package org.springframework.boot.autoconfigure.web;
...
@ConfigurationProperties(prefix = "server", ignoreUnknownFields = true)
public class ServerProperties
implements EmbeddedServletContainerCustomizer, EnvironmentAware, Ordered {
public static class Tomcat {
public static class Accesslog {
...
}
}
}
通过分析ServerProperties对象,我们可以知道access log在yml中的配置路径,即:server.tomcat.accesslog 。
| 属性 | 默认值 | 说明 |
|---|---|---|
| enabled | false | 开启访问日志。 |
| pattern | “common” | 访问日志的格式模式。 |
| directory | “logs” | 创建日志文件的目录。可以是相对于tomcat基本目录或绝对目录。 |
| prefix | “access_log” | 日志文件名前缀。 |
| suffix | “.log” | 日志文件名后缀。 |
| rotate | true | 默认为true。这个参数决定是否需要切换切换日志文件,如果被设置为false,则日志文件不会切换,即所有文件打到同一个日志文件中,并且fileDateFormat参数也会被忽略。小心使用这个参数。 |
| renameOnRotate | false | 是否推迟将日期戳包含在文件名中,为true的情况下当天的日志文件是没有日期后缀的(如:access_log.txt),每天日期切换时,当天文件重命名为前一天日期后缀,同时新生成当天文件。 |
| fileDateFormat | “.yyyy-MM-dd” | 日志文件名称中的日期格式,默认为.yyyy-MM-dd。 |
| requestAttributesEnabled | false | 为请求设置IP地址、主机名、协议和端口的请求属性。 |
| buffered | true | 缓冲输出,使其只定期刷新。 |
server:
tomcat:
accesslog:
enabled: true
pattern: '%{yyyy-MM-dd HH:mm:ss}t %a %A %m %s %D %b %I %U%q %{User-Agent}i'
directory: D:\logs\projectName\
prefix: accesslog
suffix: .log
fileDateFormat: _yyyyMMdd
rotate: true
renameOnRotate: false
buffered: true
requestAttributesEnabled: true
pattern属性由一系列的字符串参数组成,每个参数都有前缀"%",目前支持下面这些参数:
其中pattern参数有两个默认模式common、combined模式,使用方式为:
server:
tomcat:
accesslog:
pattern: combined #或common
Access Log中也支持cookie,请求header,响应headers,Session或者其他在ServletRequest中的对象的信息,下面的xxx为有效的参数名。
如输出User-Agent要写成%{User-Agent}i。
通过记录access log,可以排查每个请求的一些关键信息。分析出那些地址是常用的请求,那些服务耗时严重,那些时间段的请求量大等信息。
这些信息可以通过日志分析工具去分析,也可以使用awk命令实时统计。