教程 nginx tutorial

日志与监控

日志和监控是 Nginx 运维的重要部分,通过合理配置日志和监控模块,可以快速排查问题并优化性能。

一、访问日志配置

nginx
http {
    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:自定义日志格式
  • access_log:指定日志文件和格式

二、错误日志配置

nginx
error_log /var/log/nginx/error.log warn;
  • error_log:指定错误日志文件
  • 日志级别:debug, info, notice, warn, error, crit, alert, emerg

三、实时监控

  1. stub_status 模块:查看 Nginx 运行状态
nginx
location /nginx_status {
    stub_status on;
    allow 127.0.0.1;
    deny all;
}

访问 http://127.0.0.1/nginx_status 可查看:

  • Active connections:当前活跃连接数
  • accepts / handled / requests:请求处理统计
  • Reading / Writing / Waiting:连接状态
  1. 监控工具:结合 Prometheus、Grafana 或 Zabbix,可实时监控 Nginx 性能指标

四、日志优化与管理

  1. 定期轮换日志文件,避免占满磁盘
  2. 配置 access_log off; 对某些静态资源禁用访问日志
  3. 使用日志分析工具(如 GoAccess、AWStats)统计访问数据
  4. 对高并发场景,可设置日志缓冲,减少磁盘 I/O

通过合理配置日志与监控,Nginx 可以实时掌握服务器运行状态,快速排查问题并优化网站性能。