7.6.1 Nginx日志类型与格式配置
Nginx 日志分为访问日志与错误日志。访问日志用于流量分析与问题追溯;错误日志记录启动、运行及请求处理异常。默认路径常见于 /var/log/nginx/access.log 与 /var/log/nginx/error.log,可在 http 或更细粒度的 server/location 中自定义。
1. 日志格式与输出位置配置(含示例)#
在 http 块定义格式,在 server/location 指定输出位置:
# /etc/nginx/nginx.conf
http {
log_format main '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'rt=$request_time urt=$upstream_response_time '
'host=$host';
access_log /var/log/nginx/access.log main;
error_log /var/log/nginx/error.log warn;
server {
listen 80;
server_name example.com;
# 单独为静态资源定义精简日志
location /static/ {
log_format static '$remote_addr "$request" $status $body_bytes_sent';
access_log /var/log/nginx/static.log static;
}
location / {
proxy_pass http://127.0.0.1:8080;
}
}
}
关键变量说明
- $remote_addr:客户端IP
- $request:请求行(方法/URI/协议)
- $status:状态码
- $body_bytes_sent:响应大小
- $request_time:请求耗时
- $upstream_response_time:上游响应耗时
- $host:请求主机名
应用配置并验证
# 语法检查
nginx -t
# 平滑重载
nginx -s reload
# 观察是否写入访问日志
tail -f /var/log/nginx/access.log
2. 针对真实客户端IP的日志增强#
若 Nginx 处于反向代理后,需要 realip 配置后使用 $realip_remote_addr 记录真实IP:
# /etc/nginx/nginx.conf
http {
set_real_ip_from 10.0.0.0/8;
real_ip_header X-Forwarded-For;
real_ip_recursive on;
log_format main '$realip_remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';
access_log /var/log/nginx/access.log main;
}
3. 错误日志级别与排障示例#
常用级别:warn、error。排查时可临时调高至 info 或 debug(需编译支持 debug)。
# /etc/nginx/nginx.conf
error_log /var/log/nginx/error.log info;
常见错误与排查
# 端口占用
ss -lntp | grep :80
# 配置引用文件不存在
grep -n "include" -n /etc/nginx/nginx.conf
# 观察错误日志
tail -n 50 /var/log/nginx/error.log
4. 实战命令示例(分析与验证)#
# 统计 5xx 错误次数
awk '$9 ~ /^5/ {cnt++} END{print "5xx:", cnt}' /var/log/nginx/access.log
# 查看耗时超过 1s 的请求
awk 'match($0,/rt=([0-9.]+)/,a){if(a[1]>1)print $0}' /var/log/nginx/access.log
# 模拟请求并验证日志字段
curl -H 'User-Agent: test-agent' http://example.com/
tail -n 1 /var/log/nginx/access.log
5. 练习(动手验证)#
- 在
http中定义main格式,增加rt与urt字段。 - 为
/static/单独输出日志到/var/log/nginx/static.log。 - 访问
/static/与/,分别验证日志写入是否正确。 - 将错误日志级别改为
info,触发一个配置语法错误(如缺少分号),观察日志输出。
6. 常见问题与修复#
- 访问日志为空:检查
access_log off;是否被覆盖;确认server与location级别是否关闭日志。 - 权限不足:确保 Nginx 运行用户对日志目录有写权限。
- 时间错乱:统一系统时区与 Nginx 日志时间(
$time_local)。
通过以上配置与演练,你可以实现可分析、可追溯、可排障的 Nginx 日志体系。