在 Linux 下分析 Nginx 日志,通常分为 查看日志位置 → 了解日志格式 → 用命令行工具分析 → 进阶工具/可视化 几个步骤。下面给你一套实用方案。
通常默认路径:
/var/log/nginx/access.log
/var/log/nginx/error.log
也可以在配置中查看:
nginx -T 2>/dev/null | grep -E "access_log|error_log"
常见格式(combined):
$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent"
示例:
192.168.1.10 - - [10/Apr/2024:12:00:01 +0800] "GET /index.html HTTP/1.1" 200 1024 "https://example.com/" "Mozilla/5.0"
tail -n 100 /var/log/nginx/access.log
实时查看:
tail -f /var/log/nginx/access.log
awk '{print $1}' access.log | sort | uniq -c | sort -nr | head
awk '{print $9}' access.log | sort | uniq -c | sort -nr
只看 4xx / 5xx:
awk '$9 ~ /^4|^5/ {print $9, $1}' access.log
awk '{print $7}' access.log | sort | uniq -c | sort -nr | head
grep "192.168.1.10" access.log
awk '{print $4}' access.log | cut -d: -f1-2 | sort | uniq -c
awk '{print $NF, $7}' access.log | sort -nr | head
tail -n 50 /var/log/nginx/error.log
常见关键词:
permission deniedupstream timed out502 Bad GatewayNginx 日志会越来越大,建议用 logrotate:
cat /etc/logrotate.d/nginx
示例:
/var/log/nginx/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
create 0640 www-data adm
sharedscripts
postrotate
nginx -s reload
endscript
}
apt install goaccess
goaccess access.log -o report.html --log-format=COMBINED
可写 shell 脚本每天统计并发邮件。
适合生产环境、集群日志分析。
| 目的 | 命令 |
|---|---|
| 访问最多 IP | `awk ‘{print $1}’ |
| 错误最多的 URL | `awk ‘$9 ~ /^5/ {print $7}’ |
| 爬虫识别 | grep -i bot access.log |
| 某天日志 | grep "10/Apr/2024" access.log |
如果你愿意,可以:
我可以直接帮你写 精确命令或脚本。