温馨提示×

Debian如何监控Nginx日志

小樊
48
2026-07-13 10:48:20
栏目: 智能运维

在 Debian 系统上监控 Nginx 日志,常见做法从“实时查看”到“长期分析、告警”都有。下面按使用场景给你一个比较完整的方案。


一、Nginx 日志位置(先确认)

Debian 默认路径一般是:

/var/log/nginx/access.log
/var/log/nginx/error.log

如果你自定义过 nginx.conf,以实际配置为准:

access_log /var/log/nginx/access.log;
error_log  /var/log/nginx/error.log;

二、实时查看日志(最常用)

1️⃣ 实时跟踪日志(tail)

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

只看最新 100 行:

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

2️⃣ 同时监控多个日志

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

三、过滤和搜索日志

1️⃣ 查看指定 IP 访问

grep "1.2.3.4" /var/log/nginx/access.log

2️⃣ 查看 404 请求

awk '$9 == 404' /var/log/nginx/access.log

或:

grep " 404 " /var/log/nginx/access.log

3️⃣ 查看访问量最高的 IP

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

四、使用 journalctl(systemd)

如果 Nginx 是通过 systemd 启动的:

journalctl -u nginx -f

查看最近 100 条:

journalctl -u nginx -n 100

五、日志切割与长期监控(非常重要)

Debian 默认使用 logrotate 管理 Nginx 日志。

1️⃣ 查看 logrotate 配置

cat /etc/logrotate.d/nginx

常见配置:

/var/log/nginx/*.log {
    daily
    missingok
    rotate 7
    compress
    delaycompress
    notifempty
    create 0640 www-data adm
    sharedscripts
    postrotate
        systemctl reload nginx
    endscript
}

✅ 防止日志把磁盘写满
✅ 自动压缩历史日志


六、自动监控 & 告警(推荐)

✅ 方案 1:用 fail2ban(防攻击)

监控错误日志,封禁恶意 IP。

apt install fail2ban

示例(防止 404 扫描):

[nginx-badbots]
enabled = true
filter = nginx-badbots
logpath = /var/log/nginx/access.log
maxretry = 10
bantime = 3600

✅ 方案 2:GoAccess(网页可视化)

强烈推荐

apt install goaccess

实时分析:

goaccess /var/log/nginx/access.log -c

生成 HTML:

goaccess /var/log/nginx/access.log \
  -o /var/www/html/report.html \
  --log-format=COMBINED

浏览器访问:

http://服务器IP/report.html

✅ 方案 3:Prometheus + Grafana(生产环境)

适合服务器集群:

  • nginx-vts-exporter
  • node-exporter
  • Grafana 仪表盘

监控指标:

  • QPS
  • 延迟
  • 5xx 错误
  • 带宽

七、常见监控指标建议

指标 含义
5xx 错误 服务异常
慢请求 性能问题
单 IP 请求数 爬虫 / 攻击
404 数量 漏洞扫描
带宽 流量异常

八、推荐组合(按场景)

个人 / 小项目
tail -f + logrotate + GoAccess

生产环境
logrotate + fail2ban + Prometheus + Grafana

安全监控
fail2ban + 自定义脚本


如果你愿意,我可以:

  • ✅ 帮你写 Nginx 日志监控脚本
  • ✅ 给你一个 fail2ban 防 CC 攻击完整配置
  • ✅ 帮你搭建 Grafana Nginx 实时监控面板

你现在的使用场景是哪种?

0