Nginx2026-04-15·7 分钟
Nginx 日志与监控
介绍 Nginx 日志配置、分析方法与服务健康监控的常见方案。
Nginx 日志与监控
1. 访问日志格式
nginx
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便于后续分析。 - 记录
X-Forwarded-For对于反向代理环境很重要。
2. 错误日志级别
nginx
error_log /var/log/nginx/error.log warn;error或warn适合生产环境。debug仅在排查问题时使用。
3. 日志切割与归档
- 使用
logrotate或系统自带日志管理工具。 - 变更日志文件后运行:
bash
nginx -s reopenreopen让 Nginx 重新打开日志文件句柄。
4. 实时监控方式
nginx_status模块提供基本活动连接与请求统计。stub_status常用于简单监控接入。
nginx
location /nginx_status {
stub_status on;
allow 127.0.0.1;
deny all;
}5. 持续指标采集
- 将
access.log输出汇入 ELK、Fluentd、Loki 等平台。 - 通过
Prometheus+nginx-exporter采集运行指标。
6. 健康检查与告警
- 定期检查
nginx -t与进程状态。 - 监控
active connections、requests per second、upstream response time。 - 配置告警,及时响应 5xx、超时、连接失败等异常。
7. 排查日志方法
tail -f /var/log/nginx/error.log实时观察错误。- 访问日志配合
grep、awk过滤异常请求。 - 对慢请求可记录
request_time和upstream_response_time。
Nginx日志监控