用脚本分析日志,核心思路一般是:读取日志 → 过滤/解析 → 统计或提取关键信息 → 输出结果。下面按常见场景给你一个实用指南,涵盖 Shell、Python 和 awk 三种最常用方式。
常见日志分析目标:
grep -c "ERROR" app.log
awk '{print $1}' access.log | sort | uniq -c | sort -nr
grep "2024-01-21 10:" app.log | grep "ERROR"
#!/bin/bash
LOG=$1
echo "总日志行数:"
wc -l < $LOG
echo "错误数量:"
grep -c "ERROR" $LOG
echo "Top 5 IP:"
awk '{print $1}' $LOG | sort | uniq -c | sort -nr | head -5
awk '{print substr($4, 2, 14)}' access.log | uniq -c
awk '$10 > 1 {print $0}' access.log
from collections import Counter
ip_counter = Counter()
with open("access.log") as f:
for line in f:
ip = line.split()[0]
ip_counter[ip] += 1
for ip, count in ip_counter.most_common(10):
print(ip, count)
import re
pattern = re.compile(r'(\d+\.\d+\.\d+\.\d+).*?"(\w+) (.*?) HTTP')
with open("access.log") as f:
for line in f:
m = pattern.search(line)
if m:
ip, method, url = m.groups()
tail -f app.log | grep "ERROR"
或 Python:
import time
with open("app.log") as f:
f.seek(0, 2)
while True:
line = f.readline()
if "ERROR" in line:
print(line)
time.sleep(0.1)
awk / grep 先过滤,再给 Pythonjq 或 Python json如果你能发一段日志样例 + 想分析的目标,我可以直接帮你写一整段可用脚本。