Nginx 日志量大时,不要直接 cat 或 vim 硬看,而是按“定位问题 → 聚合统计 → 深入排查”的思路来分析。下面给你一套实用方法,从简单到进阶。
先确认你用的是哪种日志格式(默认是 combined):
log_format combined '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';
常见字段含义:
$remote_addr:客户端 IP$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
常见异常:
404 → 爬虫 / 路径错误500 → 后端程序问题499 → 客户端主动断开(常见于超时)awk '{print $4}' access.log | cut -d: -f1-2 | sort | uniq -c
输出示例:
1200 [10/Oct/2024:10
3400 [10/Oct/2024:11
awk '$9 == 500 {print}' access.log
grep '1.2.3.4' access.log
如果你日志里有:
$request_time
统计最慢的 10 个请求:
awk '{print $NF, $0}' access.log | sort -nr | head
用 logrotate:
/etc/logrotate.d/nginx
示例:
/var/log/nginx/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
create 0640 nginx nginx
sharedscripts
postrotate
kill -USR1 `cat /var/run/nginx.pid`
endscript
}
适合:
goaccess access.log -o report.html --log-format=COMBINED
特点:
减少日志量:
access_log /var/log/nginx/access.log combined if=$loggable;
map $status $loggable {
default 1;
404 0;
}
或只记录错误:
error_log /var/log/nginx/error.log warn;
如果你愿意,可以告诉我:
我可以直接给你定制化分析命令或架构建议。