日志与监控 日志和监控是 Nginx 运维的重要部分,通过合理配置日志和监控模块,可以快速排查问题并优化性能。
一、访问日志配置 nginxhttp {
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:指定日志文件和格式二、错误日志配置 nginxerror_log /var/log/nginx/error.log warn;error_log:指定错误日志文件日志级别:debug, info, notice, warn, error, crit, alert, emerg三、实时监控 stub_status 模块:查看 Nginx 运行状态nginxlocation /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:连接状态监控工具:结合 Prometheus、Grafana 或 Zabbix,可实时监控 Nginx 性能指标四、日志优化与管理 定期轮换日志文件,避免占满磁盘配置 access_log off; 对某些静态资源禁用访问日志使用日志分析工具(如 GoAccess、AWStats)统计访问数据对高并发场景,可设置日志缓冲,减少磁盘 I/O通过合理配置日志与监控,Nginx 可以实时掌握服务器运行状态,快速排查问题并优化网站性能。