监控 Nginx 访问日志(access log)通常有实时查看、统计分析、集中采集、告警几种层次,下面按“从简单到生产级”的方式给你一套可落地方案。
tail -f /var/log/nginx/access.log
tail -f /var/log/nginx/access.log | grep "404"
tail -f /var/log/nginx/access.log | grep "192.168.1.10"
$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent"
awk '{print $1}' access.log | sort | uniq -c | sort -nr | head
awk '{print $9}' access.log | sort | uniq -c | sort -nr
awk '{print $7}' access.log | sort | uniq -c | sort -nr | head
awk '{print $4}' access.log | cut -c 2-18 | uniq -c
# Ubuntu
apt install goaccess
# CentOS
yum install goaccess
goaccess /var/log/nginx/access.log -o /var/www/html/report.html --log-format=COMBINED
或实时终端:
goaccess access.log -c
✅ 适合:单机、快速看流量、IP、状态码、UA
Nginx → Filebeat → Elasticsearch → Kibana
优点
Filebeat 示例配置
filebeat.inputs:
- type: log
paths:
- /var/log/nginx/access.log
output.elasticsearch:
hosts: ["http://localhost:9200"]
适合“监控 QPS、错误率”,不是看原始日志
nginx-prometheus-exporter \
-nginx.scrape-uri=http://localhost/nginx_status
Grafana 可画:
Nginx → Promtail → Loki → Grafana
✅ 比 ELK 轻
✅ 查询语法简单
✅ 适合 Kubernetes / 云原生
count=$(awk '$9 ~ /5[0-9][0-9]/' access.log | wc -l)
if [ $count -gt 100 ]; then
echo "Nginx 5xx 错误过多" | mail admin@xx.com
fi
log_format json escape=json '{'
'"time":"$time_local",'
'"ip":"$remote_addr",'
'"method":"$request_method",'
'"url":"$request_uri",'
'"status":$status,'
'"size":$body_bytes_sent'
'}';
logrotate /etc/logrotate.d/nginx
| 场景 | 推荐 |
|---|---|
| 临时排查 | tail / awk |
| 单机可视化 | GoAccess |
| 公司级日志 | ELK / Loki |
| 指标监控 | Prometheus + Grafana |
如果你愿意,可以告诉我:
我可以直接给你完整配置示例。