SorryToPerson logo
返回
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;
  • errorwarn 适合生产环境。
  • debug 仅在排查问题时使用。

3. 日志切割与归档

  • 使用 logrotate 或系统自带日志管理工具。
  • 变更日志文件后运行:
bash
nginx -s reopen
  • reopen 让 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 connectionsrequests per secondupstream response time
  • 配置告警,及时响应 5xx、超时、连接失败等异常。

7. 排查日志方法

  • tail -f /var/log/nginx/error.log 实时观察错误。
  • 访问日志配合 grepawk 过滤异常请求。
  • 对慢请求可记录 request_timeupstream_response_time
Nginx日志监控