配置格式
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_useruser name supplied with the Basic authentication
- time_locallocal time in the Common Log Format. 服务器的本地时间,会带有时区信息
- requestfull original request line. HTTP 请求行
- statusresponse status, HTTP 响应状态码
- body_bytes_sentnumber of bytes sent to a client, not counting the response header; 而- bytes_sent包含 HTTP 响应的头部信息。
- http_referer来源地址
- 
其他有用的变量有时需要收集更多的访问信息,你可能自定义日志格式,并加入所需的变量。 
- request_lengthrequest length (including request line, header, and request body)
- request_timerequest 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
 
                         
                                

