针对大规模日志分析,Linux系统提供了丰富的工具链和高效的组合方案。以下从不同场景出发,给出专业级解决方案:
- AWK高级用法(处理结构化日志):
# 分析Nginx日志统计HTTP状态码分布
awk '{a[$9]++} END {for(code in a) print code, a[code]}' access.log | sort -nr -k2
# 多条件统计(状态码+请求方法)
awk '{count[$9,$6]++} END {for(k in count) split(k,keys,SUBSEP); print keys[1],keys[2],count[k]}' access.log
# 使用LC_ALL=C加速ASCII日志搜索
LC_ALL=C grep -P 'ERROR|CRITICAL' application.log
# 并行grep(利用parallel)
find /var/log -name "*.log" | parallel -j+0 'grep -H "SEARCH_TERM" {}'
- 实时错误监控管道:
tail -F application.log | \
grep --line-buffered "ERROR" | \
awk '{print $1,$3}' | \
while read -r timestamp message; do
echo "[$(date)] $message" >> error_alert.log
# 可集成curl发送告警
done
cat access.log | \
cut -d' ' -f1,4,7,9 | \
awk '{
ip[$1]++;
endpoint[$3]++;
status[$4]++
} END {
print "Top IPs:";
sort_and_print(ip);
print "\nTop Endpoints:";
sort_and_print(endpoint)
}'
- 使用ripgrep替代grep:
# 比grep快5-10倍的替代方案
rg -N -A2 "transaction failed" --stats *.log
# 每1000行采样1行进行快速分析
awk '!(NR%1000)' large.log | analyzer_script.sh
- jq处理JSON日志:
# 提取嵌套JSON字段并统计
cat app.json.log | jq -r '.error.type' | sort | uniq -c | sort -nr
# 安装:pip install logreduce
logreduce diff /var/log/nginx/access.log
- MapReduce式处理:
# 使用xargs并行处理分割后的日志
find /logs -name "*.log" | xargs -P8 -I{} sh -c 'process_log "{}" > {}.processed'
# 使用Filebeat收集日志
filebeat.prospectors:
- type: log
paths:
- /var/log/*.log
json.keys_under_root: true
- 时间序列分析:
# 统计每分钟请求量
awk -F'[:[]' '{print $2":"$3}' access.log | uniq -c
# 关联错误日志与访问日志
join -j1 -o 1.1,2.2 <(grep -n "ERROR" app.log | cut -d: -f1) <(cat -n access.log)
- 使用less -S
查看宽行日志
- 对大文件使用split -l 1000000
分割处理
- 对GZIP压缩日志使用zcat
或zgrep
- 使用ts
命令(from moreutils)添加时间戳
# 生成ASCII直方图
awk '{print $1}' access.log | sort | uniq -c | sort -nr | head -20 | \
gnuplot -p -e 'set boxwidth 0.5; plot "-" using 1:xtic(2) with boxes'
对于TB级日志,建议采用:
1. 预处理:使用logstash
或fluentd
进行字段提取
2. 存储:导入ClickHouse或Elasticsearch
3. 分析:使用Presto/Trino执行分布式查询
4. 可视化:Grafana或Kibana展示
注:以上命令可根据实际日志格式调整字段分隔符(-F参数)和匹配模式。对于生产环境,建议通过logrotate
配置合理的日志轮转策略。