温馨提示×

centos怎样监控apache日志

小樊
52
2026-09-30 06:57:21
栏目: 智能运维

在 CentOS 上监控 Apache 日志,常见做法有命令行实时查看、日志分析工具、以及监控告警系统三类。下面按使用频率和场景给你一个较完整的方案。


一、最基础:实时查看 Apache 日志

1. Apache 日志位置(默认)

# CentOS + Apache(httpd)
/var/log/httpd/access_log
/var/log/httpd/error_log

2. 实时查看访问日志

tail -f /var/log/httpd/access_log

3. 实时查看错误日志

tail -f /var/log/httpd/error_log

4. 过滤关键信息

# 只看 404
tail -f /var/log/httpd/access_log | grep 404

# 只看某个 IP
tail -f /var/log/httpd/access_log | grep 192.168.1.100

# 只看错误
tail -f /var/log/httpd/error_log | grep -i error

二、常用分析命令(排查问题)

1. 统计访问最多的 IP

awk '{print $1}' /var/log/httpd/access_log | sort | uniq -c | sort -nr | head

2. 统计状态码分布

awk '{print $9}' /var/log/httpd/access_log | sort | uniq -c | sort -nr

3. 统计访问最多的 URL

awk '{print $7}' /var/log/httpd/access_log | sort | uniq -c | sort -nr | head

三、使用日志分析工具(推荐)

1. GoAccess(实时可视化,强烈推荐)

yum install -y goaccess
goaccess /var/log/httpd/access_log -o /var/www/html/report.html --log-format=COMBINED

实时终端模式:

goaccess /var/log/httpd/access_log --log-format=COMBINED

四、系统级监控(长期运行)

1. 确保 Apache 日志在轮转

cat /etc/logrotate.d/httpd

手动测试:

logrotate -d /etc/logrotate.d/httpd

五、异常告警(进阶)

1. 用 fail2ban 防暴力/异常访问

yum install -y epel-release
yum install -y fail2ban

示例:监控 404 暴力扫描

[apache-404]
enabled = true
filter = apache-404
logpath = /var/log/httpd/access_log
maxretry = 50

2. Prometheus + Node Exporter(企业级)

  • node_exporter 监控磁盘
  • 自定义脚本监控日志大小 / 错误频率
  • Grafana 展示

六、简单自动化监控脚本示例

#!/bin/bash
COUNT=$(grep -c "500" /var/log/httpd/error_log)
if [ "$COUNT" -gt 10 ]; then
    echo "Apache 500 错误过多" | mail -s "Apache 告警" admin@xxx.com
fi

总结建议

  • 临时排查:tail -f
  • 日常分析:GoAccess
  • 长期监控:logrotate + 告警
  • 安全:fail2ban

如果你能说一下是 CentOS 几 + Apache 版本 + 使用场景(排查 / 安全 / 性能),我可以给你更精确的方案。

0 踩