写一个 Nginx access log 分析脚本,五分钟定位线上慢请求
【摘要】 从日志字段到慢请求定位的脚本化方法。
写一个 Nginx access log 分析脚本,五分钟定位线上慢请求
为什么要自己写
现成的日志平台当然好用,但线上出问题时,把日志拉下来本地跑一遍往往最快。这篇文章给出一个不依赖任何第三方库的 Python 脚本,直接读 nginx 的 access.log,输出慢请求、错误率、Top IP 和 Top 接口。
日志格式
先确认你的 log_format,默认 combined 长这样:
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for" $request_time';
关键是最后加了 `$request_time`,没有这个字段就没法分析耗时。
解析脚本
import re
from collections import Counter, defaultdict
PATTERN = re.compile(
r'(?P<ip>[\d\.]+) .*?\[(?P<time>[^\]]+)\] "(?P<method>\w+) (?P<path>\S+) [^"]*" '
r'(?P<status>\d{3}) (?P<bytes>\d+) "[^"]*" "[^"]*" "[^"]*" (?P<rt>[\d\.]+)'
)
slow, ips, paths, status = [], Counter(), Counter(), Counter()
total = 0
for line in open('/var/log/nginx/access.log', errors='ignore'):
m = PATTERN.match(line)
if not m:
continue
total += 1
d = m.groupdict()
rt = float(d['rt'])
ips[d['ip']] += 1
paths[d['path'].split('?')[0]] += 1
status[d['status']] += 1
if rt > 1.0:
slow.append((rt, d['path'], d['status'], d['ip']))
print(f'总请求 {total}')
print('5xx 比例 %.2f%%' % (100 * sum(v for k, v in status.items() if k.startswith('5')) / max(total, 1)))
print('Top IP', ips.most_common(5))
print('Top 路径', paths.most_common(5))
for rt, p, s, ip in sorted(slow, reverse=True)[:10]:
print(f'{rt:.3f}s {s} {p} {ip}')
实际效果
上周一个接口 P99 突然从 80ms 涨到 1.2s,平台上看不出原因。把日志跑一遍,Top 慢请求集中在 `/api/v1/export`,而且全是 200,说明不是报错,是数据量变大导致的全表扫描。加了个时间范围限制之后恢复。
几个改进方向
• 按分钟聚合,画出耗时曲线,比单点数值直观
• 用 `gzip.open` 直接读 `access.log.gz`,避免解压占磁盘
• 把 IP 段聚合,识别是正常用户还是爬虫
小结
日志分析脚本的价值不在于多精巧,而在于你能在故障现场五分钟内拿到结论,而不是等平台出图。
【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)