配置格式
access_log log_file log_format;
以下是 Nginx 访问日志的默认配置
log_format combined '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';
access_log logs/access.log combined;
变量解释
默认配置的变量
combined 是系统预定义的日志格式,可根据需要自定义,但是名称不能重复。
log_format main '$request_time ...'
日志中各变量的含义
remote_addr
客户端 IP 地址。一般 addr 表示 IP, server_name 表示域名。remote_user
user name supplied with the Basic authenticationtime_local
local time in the Common Log Format. 服务器的本地时间,会带有时区信息request
full original request line. HTTP 请求行status
response status, HTTP 响应状态码body_bytes_sent
number of bytes sent to a client, not counting the response header; 而bytes_sent
包含 HTTP 响应的头部信息。http_referer
来源地址-
其他有用的变量
有时需要收集更多的访问信息,你可能自定义日志格式,并加入所需的变量。
request_length
request length (including request line, header, and request body)request_time
request processing time in seconds with a milliseconds resolution; time elapsed between the first bytes were read from the client and the log write after the last bytes were sent to the client-
日志示例
请求
curl http://suhua@localhost/index.html \
-H "Referer: http://example.com" \
-H "User-Agent: Mozilla/5.0"
日志
192.168.0.1 - suhua [06/Sep/2020:11:46:39 +0800] "GET /index.html HTTP/1.1" 200 9 "http://example.com" "Mozilla/5.0"
配置示例
记录上游的响应时间
log_format upstream_time '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"'
'rt=$request_time uct="$upstream_connect_time" uht="$upstream_header_time" urt="$upstream_response_time"';
配置成 json 格式的日志,可方便后续的分析,在添加新字段时也不需要修改日志解析规则。
log_format json_log escape=json '{"ip": "$remote_addr", "timestamp": "$time_iso8601", '
'"host": "http_host", "request": "$request", '
'"cookie": "$http_cookie", "req_time": "$request_time", '
'"uri": "$uri", "referer": "$http_referer" }';
注意事项
配置继承和覆盖
无论是 error_log 还是 access_log,子配置都会覆盖父配置,如子域中没有配置时才会使用父配置。
以下配置,access.log 会没有日志,只有 foo-access.log 才有日志。http {
error_log /var/log/nginx/error.log;
access_log /var/log/nginx/access.log;
server {
error_log /var/log/nginx/foo-error.log;
access_log /var/log/nginx/foo-access.log;
}
}
参考
- 5.1 Request-Line part of Hypertext Transfer Protocol — HTTP/1.1
- SP Char in HTTP Headers?
- Module ngx_http_log_module
- Embedded Variables
- Configuring Logging