处理 Apache 日志通常会用到 shell 脚本 + awk / sed / grep,或者直接上 Python / Go 做更复杂的分析。下面按“常见需求 + 示例脚本”来讲。
常见的是 combined 格式:
127.0.0.1 - - [10/Oct/2024:13:55:36 +0800] "GET /index.html HTTP/1.1" 200 2326 "https://example.com" "Mozilla/5.0"
字段含义:
awk '{print $1}' access.log | sort | uniq -c | sort -rn | head -10
脚本封装:
#!/bin/bash
LOG=$1
awk '{print $1}' "$LOG" | sort | uniq -c | sort -rn | head -10
awk '{print $9}' access.log | sort | uniq -c | sort -rn
awk '$9 == 404 {print $1, $7}' access.log
awk '$7 == "/login" {count++} END {print count}' access.log
awk '{print substr($4, 2, 14)}' access.log | sort | uniq -c
输出示例:
100 10/Oct/2024:13
120 10/Oct/2024:14
from collections import Counter
ip_counter = Counter()
status_counter = Counter()
with open("access.log") as f:
for line in f:
parts = line.split()
if len(parts) < 9:
continue
ip = parts[0]
status = parts[8]
ip_counter[ip] += 1
status_counter[status] += 1
print("Top IPs:")
for ip, count in ip_counter.most_common(10):
print(ip, count)
print("Status:")
for s, c in status_counter.items():
print(s, c)
/etc/logrotate.d/apache2
/var/log/apache2/access.log {
daily
rotate 30
missingok
notifempty
compress
postrotate
/usr/bin/python3 /opt/scripts/analyze_log.py
endscript
}
%D 响应时间)如果你有具体需求(比如“我想统计某个接口的平均响应时间”或“找出攻击 IP”),可以直接告诉我,我给你写完整脚本。