温馨提示×

如何监控nginx访问日志

小樊
42
2026-10-24 22:05:22
栏目: 编程语言

监控 Nginx 访问日志(access log)通常有实时查看、统计分析、集中采集、告警几种层次,下面按“从简单到生产级”的方式给你一套可落地方案。


一、基础:实时查看访问日志

1. 实时跟踪日志

tail -f /var/log/nginx/access.log

2. 只看特定请求

tail -f /var/log/nginx/access.log | grep "404"
tail -f /var/log/nginx/access.log | grep "192.168.1.10"

3. 常用字段说明(默认格式)

$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent"

二、常用分析命令(快速定位问题)

1. 统计访问最多的 IP

awk '{print $1}' access.log | sort | uniq -c | sort -nr | head

2. 统计状态码分布

awk '{print $9}' access.log | sort | uniq -c | sort -nr

3. 查看访问最多的 URL

awk '{print $7}' access.log | sort | uniq -c | sort -nr | head

4. 统计每分钟请求数

awk '{print $4}' access.log | cut -c 2-18 | uniq -c

三、进阶:使用 GoAccess(可视化)

安装(CentOS / Ubuntu)

# 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


四、生产级:日志采集 + 监控(推荐)

方案 1:Filebeat + Elasticsearch + Kibana(ELK)

Nginx → Filebeat → Elasticsearch → Kibana

优点

  • 集中日志
  • 可视化仪表盘
  • 支持告警

Filebeat 示例配置

filebeat.inputs:
- type: log
  paths:
    - /var/log/nginx/access.log

output.elasticsearch:
  hosts: ["http://localhost:9200"]

方案 2:Prometheus + Nginx Exporter(指标监控)

适合“监控 QPS、错误率”,不是看原始日志

nginx-prometheus-exporter \
  -nginx.scrape-uri=http://localhost/nginx_status

Grafana 可画:

  • QPS
  • 5xx 错误率
  • 响应时间

方案 3:Loki + Promtail(轻量级日志监控)

Nginx → Promtail → Loki → Grafana

✅ 比 ELK 轻
✅ 查询语法简单
✅ 适合 Kubernetes / 云原生


五、异常告警示例

1. 5xx 过多告警(Shell)

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

2. 防爬/攻击监控

  • 单 IP 短时高频访问
  • UA 异常(curl、python)
  • 扫描路径(/admin、/.env)

六、日志优化建议

1. 使用 json 日志格式(方便采集)

log_format json escape=json '{'
  '"time":"$time_local",'
  '"ip":"$remote_addr",'
  '"method":"$request_method",'
  '"url":"$request_uri",'
  '"status":$status,'
  '"size":$body_bytes_sent'
'}';

2. 日志切割

logrotate /etc/logrotate.d/nginx

七、我该怎么选?

场景 推荐
临时排查 tail / awk
单机可视化 GoAccess
公司级日志 ELK / Loki
指标监控 Prometheus + Grafana

如果你愿意,可以告诉我:

  • 单机还是集群?
  • 是否用 Docker / K8s?
  • 想看“日志内容”还是“监控指标”?

我可以直接给你完整配置示例。

0 踩