在 Linux 下分析 Nginx 日志,通常分为 日志位置确认 → 日志格式理解 → 常用分析命令 → 可视化/工具 几个步骤。下面系统地讲一下。
默认路径一般在:
/var/log/nginx/access.log # 访问日志
/var/log/nginx/error.log # 错误日志
如果找不到,可以查配置:
nginx -T | grep -E 'access_log|error_log'
$remote_addr - $remote_user [$time_local] "$request"
$status $body_bytes_sent "$http_referer"
"$http_user_agent"
示例:
192.168.1.10 - - [10/Oct/2024:14:22:01 +0800] "GET /index.html HTTP/1.1" 200 2326 "https://example.com/" "Mozilla/5.0"
remote_addr:客户端 IPtime_local:访问时间request:请求方法 + URL + 协议status:HTTP 状态码body_bytes_sent:返回字节数http_user_agent:客户端类型awk '{print $1}' access.log | sort | uniq -c | sort -nr | head
awk '{print $7}' access.log | sort | uniq -c | sort -nr | head
awk '{print $9}' access.log | sort | uniq -c | sort -nr
grep -E ' 404 | 500 ' access.log
awk '$4 >= "[10/Oct/2024:14:00:00" && $4 <= "[10/Oct/2024:15:00:00"' access.log
# PV
wc -l access.log
# UV
awk '{print $1}' access.log | sort -u | wc -l
tail -n 100 error.log
connect() failed:后端服务异常upstream timed out:代理超时Permission denied:权限问题No such file or directory:路径错误goaccess access.log -o report.html --log-format=COMBINED
适合:
适合自动化统计脚本。
防止日志过大:
# 使用 logrotate
cat /etc/logrotate.d/nginx
示例:
/var/log/nginx/*.log {
daily
rotate 14
compress
missingok
notifempty
sharedscripts
postrotate
systemctl reload nginx
endscript
}
| 场景 | 方法 |
|---|---|
| 被刷流量 | 统计 IP |
| 接口慢 | 分析响应时间(需自定义日志) |
| 爬虫 | 统计 User-Agent |
| 异常报错 | error.log + status |
| 安全防护 | fail2ban + 日志 |
如果你有 具体日志样例 或 想分析某类问题(如慢请求、攻击、502),可以直接发出来,我可以帮你写具体命令。