分析 Nginx 日志是排查网站异常、性能瓶颈和安全问题的重要手段。下面从日志类型、常见异常、分析方法和实用工具几个方面系统说明。
默认路径:
/var/log/nginx/access.log
典型格式(combined):
$remote_addr - $remote_user [$time_local] "$request"
$status $body_bytes_sent "$http_referer" "$http_user_agent"
默认路径:
/var/log/nginx/error.log
日志级别:
debug < info < notice < warn < error < crit < alert < emerg
分析命令:
awk '{print $9}' access.log | sort | uniq -c | sort -rn
查看错误日志:
grep "502" /var/log/nginx/error.log
特征:
统计 IP 访问次数:
awk '{print $1}' access.log | sort | uniq -c | sort -rn | head
启用响应时间日志:
log_format main '$remote_addr - $request_time - $upstream_response_time';
分析慢请求:
awk '$NF > 2 {print}' access.log
cat access.log | awk '{print $9}' | sort | uniq -c | sort -rn
grep "1.2.3.4" access.log
awk '$4 >= "[10/Oct/2024:10:00:00" && $4 <= "[10/Oct/2024:11:00:00"' access.log
awk '{print $7}' access.log | sort | uniq -c | sort -rn | head
goaccess access.log -o report.html --log-format=COMBINED
ngxtop
如果你有具体日志内容或异常现象(比如 502、访问慢、被刷),可以直接贴出来,我可以帮你精准分析。