Apache 日志的导入与分析通常分为 日志获取 → 导入 → 解析 → 分析/可视化 几个步骤。下面按 常见场景 给你一个完整、实用的说明。
常见日志格式有两种:
127.0.0.1 - - [10/Oct/2024:13:55:36 +0800] "GET /index.html HTTP/1.1" 200 1024
127.0.0.1 - - [10/Oct/2024:13:55:36 +0800] "GET /index.html HTTP/1.1" 200 1024 "https://example.com/" "Mozilla/5.0"
默认路径一般在:
/var/log/apache2/access.log # Debian/Ubuntu
/var/log/httpd/access_log # CentOS/RHEL
awk '{print $1}' access.log | sort | uniq -c | sort -nr | head
awk '{print $7}' access.log | sort | uniq -c | sort -nr | head
awk '{print $9}' access.log | sort | uniq -c | sort -nr
awk '{print $4}' access.log | cut -d: -f2 | sort | uniq -c
✅ 适合:快速排查、临时分析
CREATE TABLE apache_log (
ip VARCHAR(50),
datetime DATETIME,
method VARCHAR(10),
url TEXT,
protocol VARCHAR(10),
status INT,
size INT,
referer TEXT,
useragent TEXT
);
goaccess 或脚本转换后导入(Apache 日志不适合直接用 LOAD DATA INFILE,推荐用 Python 解析)
✅ 最省事、最专业
# Ubuntu
apt install goaccess
# CentOS
yum install goaccess
goaccess /var/log/apache2/access.log
goaccess /var/log/apache2/access.log \
-o /var/www/html/report.html \
--log-format=COMBINED
浏览器打开 report.html 即可看到:
✅ 适合:运维、安全、日常监控
Apache → Filebeat → Logstash → Elasticsearch → Kibana
- type: log
paths:
- /var/log/apache2/access.log
grok {
match => {
"message" => "%{COMBINEDAPACHELOG}"
}
}
✅ 适合:日志量大、多服务器、安全分析
import re
pattern = re.compile(
r'(?P<ip>[\d\.]+) .* \[(?P<time>.*?)\] "(?P<method>\w+) (?P<url>.*?)" (?P<status>\d+)'
)
with open("access.log") as f:
for line in f:
m = pattern.search(line)
if m:
print(m.group("ip"), m.group("url"))
✅ 适合:定制分析、AI/安全检测
| 目标 | 工具 |
|---|---|
| 访问量统计 | goaccess / awk |
| 异常 IP | ELK / Python |
| 爬虫识别 | User-Agent |
| 攻击检测 | ELK / 正则 |
| 性能分析 | 响应码 + URL |
| 场景 | 推荐 |
|---|---|
| 快速查看 | awk + goaccess |
| 日常运维 | goaccess |
| 企业级 | ELK |
| 二次开发 | Python |
如果你愿意,我可以:
只要告诉我你的 使用场景和日志量 即可。