温馨提示×

如何过滤centos apache日志

小樊
42
2026-09-21 10:03:46
栏目: 智能运维

在 CentOS 上过滤 Apache 日志,通常是对 访问日志(access log) 或 错误日志(error log) 进行筛选。下面按常见场景给你一套实用方法。


一、Apache 日志位置(CentOS 常见路径)

# 访问日志
/var/log/httpd/access_log

# 错误日志
/var/log/httpd/error_log

(如果你用 mod_ssl,还有 ssl_access_log 等)


二、基础过滤(grep)

1. 按 IP 过滤

grep "192.168.1.100" /var/log/httpd/access_log

2. 按状态码过滤(如 404)

grep " 404 " /var/log/httpd/access_log

3. 按 URL 过滤

grep "/login.php" /var/log/httpd/access_log

4. 按时间过滤(某一天)

grep "10/Apr/2024" /var/log/httpd/access_log

三、高级过滤(awk / sed)

1. 只看访问 IP

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

2. 统计 404 最多的 URL

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

3. 查看某 IP 的访问时间分布

grep "192.168.1.100" /var/log/httpd/access_log | awk '{print $4}' | cut -d: -f2 | sort | uniq -c

四、使用 logrotate + 压缩日志

CentOS 默认已启用 logrotate:

/etc/logrotate.d/httpd

查看旧日志:

ls /var/log/httpd/
zcat /var/log/httpd/access_log-20240410.gz | grep "404"

五、实时过滤(tail + grep)

tail -f /var/log/httpd/access_log | grep "503"

六、按虚拟主机过滤(多站点)

如果你用了 CustomLog 分文件:

/var/log/httpd/www.example.com-access_log

直接过滤对应文件即可。


七、推荐工具(进阶)

  • GoAccess(实时可视化)
yum install goaccess
goaccess /var/log/httpd/access_log -o report.html
  • awk + sort + uniq(轻量分析)
  • ELK / Loki(大规模日志)

如果你有 具体过滤需求(如:统计爬虫、封 IP、分析慢请求),可以告诉我,我可以直接给你命令。

0 踩