Apache access_log中提取状态码分布需先确认LogFormat含%s字段,定位为第9列,再用awk过滤非数字项并分类统计,支持按类占比、小时切片及对接ELK/Prometheus监控。
直接从 Apache 的 access_log 中提取状态码分布,关键在于准确定位字段、过滤干扰项、分类统计。Apache 默认在日志中记录状态码(对应 %>s),但必须确认日志格式已启用该字段,且解析时避开缺失值(如“-”)和非数字项。
检查 Apache 配置中的 LogFormat,确保包含 %>s(最终响应状态码)。推荐使用或自定义为:
LogFormat "%h %l %u %t "%r" %>s %b "%{Referer}i" "%{User-Agent}i" %D" combinedCustomLog 引用了该格式,例如:CustomLog /var/log/apache2/access.log combined
head -1 access.log 看一行示例,数清空格分隔的字段位置——状态码通常是第9列(常见于 combined 格式)适合日常巡检或低流量场景,无需部署额外工具:
awk '$9 != "-" && $9 ~ /^[0-9]+$/ {print $9}' /var/log/apache2/access.log | sort | uniq -c | sort -nr
awk '$9 ~ /^4[0-9]{2}|^5[0-9]{2}$/ {print $9}' /var/log/apache2/access.log | sort | uniq -c | sort -nr
awk -F'[' '{gsub(/]/,"",$2); print $2,$9}' /var/log/apache2/access.log | awk '$2 != "-" && $2 ~ /^[0-9]+$/ {hour=substr($1,1,13); count[hour,$2]++} END {for (k in count) print k, count[k]}' | sort
单纯计数不够直观,结合总量算百分比更能反映健康度:
awk '$9 != "-" && $9 ~ /^[0-9]+$/ {total++; if($9 ~ /^2[0-9]{2}/) s2xx++; else if($9 ~ /^3[0-9]{2}/) s3xx++; else if($9 ~ /^4[0-9]{2}/) s4xx++; else if($9 ~ /^5[0-9]{2}/) s5xx++} END {print "2xx:", s2xx/total*100 "%; 3xx:", s3xx/total*100 "%; 4xx:", s4xx/total*100 "%; 5xx:", s5xx/total*100 "%"}' /var/log/apache2/access.log
printf 格式化输出,例如:printf "%s,%dn", $9, count[$9]
生产环境建议把状态码统计纳入监控闭环,避免人工翻查:
filebeat 抓取日志,通过 grok 过滤器提取 response_code 字段,写入 Elasticsearchresponse_code 聚合,并支持按 vhost 或 path 下钻apache_exporter 可直接采集 apache_httpd_request_duration_seconds_count{code="200"} 类指标,Grafana 中配置告警:5xx 占比超 1% 触发通知