日志配置在/etc/nginx/nginx.conf
中有log_format的配置。
nginx服务器日志相关指令有两条:一个是log_format
设置日志格式,另一个是access_log
,记录接入日志状态,日志文件存放的路径,格式 和缓存大小。nginx.conf里的log_format的默认配置。
http {
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
......
}
开头的log_format main意思是: 定义日志输出格式main后面开始添加变量;
access_log后跟的main是指:access_log日志里调用日志格式main。
nginx记录的每次信息都可以当做一个变量,log_format就是把这些变量组合起来,记录到日志中去。
nginx日志变量格式如下:
$remote_addr #记录客户端的ip地址
$remote_user #记录客户端的用户名
$time_local #通用的时间格式
$time_iso8601 #iso8601时间格式
$request #请求的方法和请求的HTTP协议
$status #请求状态码
$body_bytes_sent #服务器回应的字节数,不包含头部大小
$bytes_sent #服务器回应的总字节数
$msec #日志写入时间,单位为秒,精度为毫秒
$http_referer #记录链接访问源地址
$http_user_agent #记录客户端浏览器信息
$http_x_forwarded_for #跨越代理服务器,记录客户机的原始ip
$request_length #请求包的长度(请求头+请求正文)
$request_time #请求花费的时间,单位为秒,精度为毫秒
测试变量,开启nginx服务后,用客户机多次访问,查看日志情况
第一次默认格式:
[root@localhost ~]# tail -f /var/log/nginx/access.log
192.168.10.3 - - [28/Mar/2020:20:55:35 -0700] "GET /img/centos-logo.png HTTP/1.1" 304 0 "http://192.168.10.2/" "Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/45.0" "-"
192.168.10.3 - - [28/Mar/2020:20:55:35 -0700] "GET /img/header-background.png HTTP/1.1" 304 0 "http://192.168.10.2/" "Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/45.0" "-"
192.168.10.3 - - [28/Mar/2020:20:56:25 -0700] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/45.0" "-"
192.168.10.3 - - [28/Mar/2020:20:56:25 -0700] "GET /img/centos-logo.png HTTP/1.1" 304 0 "http://192.168.10.2/" "Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/45.0" "-"
第二次修改时间格式,换用iso8601再次测试
[root@localhost ~]# tail -f /var/log/nginx/access.log
192.168.10.3 - - [2020-03-28T21:02:21-07:00] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/45.0" "-"
192.168.10.3 - - [2020-03-28T21:02:21-07:00] "GET /favicon.ico HTTP/1.1" 404 3650 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/45.0" "-"
192.168.10.3 - - [2020-03-28T21:02:23-07:00] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/45.0" "-"
192.168.10.3 - - [2020-03-28T21:02:24-07:00] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/45.0" "-"
可以看出时间换成了咱们中国人喜欢看的形式。
其他的变量需要时可以自行添加到/etc/nginx/nginx.conf里的log_format定义的变量里面。
That’s all !