如何解析 Nginx 日志(提取字段做分析)?
解析 Nginx 访问日志的方法:awk/grep 命令行快速分析、Python 脚本批量处理、日志平台自动解析。本文对比各种方案及常用分析命令。
Nginx 访问日志默认是 Combined 格式(IP、时间、请求、状态码、大小、Referer、User-Agent)。快速排查用 awk/grep,批量分析用脚本,生产环境建议用日志平台自动解析。
日志格式示例
192.168.1.1 - - [15/Jan/2024:10:30:45 +0800] "GET /api/users HTTP/1.1" 200 1234 "https://example.com" "Mozilla/5.0 ..."
命令行快速分析
# 统计访问量 TOP 10 的 IP
awk '{print $1}' access.log | sort | uniq -c | sort -rn | head -10
# 统计各状态码数量
awk '{print $9}' access.log | sort | uniq -c | sort -rn
# 统计访问量 TOP 10 的 URL
awk '{print $7}' access.log | sort | uniq -c | sort -rn | head -10
# 查看所有 5xx 错误
awk '$9 >= 500 {print $1, $7, $9}' access.log
# 统计每秒请求量(QPS 趋势)
awk -F'[ :]' '{print $4":"$5":"$6}' access.log | uniq -c
Python 脚本解析
import re
pattern = re.compile(
r'(\S+) \S+ \S+ \[([^\]]+)\] "(\S+) (\S+) \S+" (\d+) (\d+) "([^"]*)" "([^"]*)"'
)
with open('/var/log/nginx/access.log') as f:
for line in f:
m = pattern.match(line)
if m:
ip, time_str, method, url, status, size, referer, ua = m.groups()
print(f"{ip} {method} {url} -> {status}")
自定义日志格式
如果 Nginx 配置了自定义 log_format(如加入 $request_time、$upstream_response_time),解析时需要对应调整字段位置或正则。
观测云对照
观测云提供 Nginx 集成,DataKit 自动采集访问日志并通过内置 Pipeline 模板解析出所有字段(含 request_time、upstream_time 等性能字段),在控制台直接查看 QPS、延迟分布、状态码统计、TOP URL 等,不需要手写解析脚本。
常见问题(FAQ)
Q:如何分析某个时间段内的日志?
A:awk '/15\/Jan\/2024:10:00/, /15\/Jan\/2024:11:00/' access.log 提取 10:00 到 11:00 之间的记录。
Q:日志文件很大(GB 级)怎么快速处理?
A:先用 grep 缩小范围再交给 awk;或按时间切割日志文件后分别处理。
Q:request_time 和 upstream_response_time 有什么区别?
A:request_time 是完整请求处理时间(含客户端传输),upstream_response_time 只是后端服务的响应时间。两者差距大说明瓶颈在网络或客户端。