如何监控Nginx的访问日志?
2025-04-14
18
参考资料
监控Nginx访问日志的方法
日志文件位置
默认路径:
/var/log/nginx/access.log
可通过Nginx配置文件(
nginx.conf
)中的access_log
指令确认路径实时监控命令
tail -f /var/log/nginx/access.log
常用分析工具
基础命令:
# 统计总访问量 wc -l /var/log/nginx/access.log # 查看独立IP数量 awk '{print $1}' access.log | sort | uniq | wc -l
高级工具:
# 使用GoAccess(实时可视化工具) goaccess /var/log/nginx/access.log -a
日志轮转配置
在/etc/logrotate.d/nginx
中配置自动轮转:/var/log/nginx/*.log { daily missingok rotate 14 compress delaycompress notifempty create 0640 www-data adm sharedscripts postrotate invoke-rc.d nginx rotate >/dev/null 2>&1 endscript }
监控脚本示例
#!/bin/bash LOGFILE="/var/log/nginx/access.log" ALERT_LEVEL=1000 # 每分钟警报阈值 while true do CURRENT=$(wc -l < $LOGFILE) sleep 60 NEW=$(wc -l < $LOGFILE) DIFF=$((NEW - CURRENT)) if [ $DIFF -gt $ALERT_LEVEL ]; then echo "High traffic detected: $DIFF requests/minute" | mail -s "NGINX Alert" admin@example.com fi done
日志格式示例
典型组合格式:log_format main '$remote_addr - $remote_user [$time_local] ' '"$request" $status $body_bytes_sent ' '"$http_referer" "$http_user_agent"';
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。