nginx分析特定接口耗时需先确保log_format包含$request_time,再用awk按$request_uri筛选日志并提取$nf(即耗时),最后统计均值、分位数或定位慢请求。

要分析 Nginx 访问日志中特定接口的访问耗时,核心是两步:确保日志里记录了请求时间($request_time),再按接口路径($request_uri)精准筛选并统计耗时分布。
确认日志格式已包含 request_time
检查你的 nginx.conf 中是否已启用 $request_time 字段。推荐使用如下精简格式:
log_format main '$remote_addr - [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" $request_time $upstream_response_time';
其中 $request_time 是 Nginx 处理该请求的总耗时(单位:秒,精度为毫秒),必须出现在日志行末尾或易定位位置。配置后需重载 Nginx:nginx -s reload。
提取指定接口的耗时数据
假设你要分析 /api/user/profile 这个接口,可用以下命令快速提取其所有请求耗时:
- 只看耗时值(便于后续统计):
awk '$7 ~ /^\/api\/user\/profile($|\?)/ {print $NF}' /var/log/nginx/access.log - 同时输出 URL 和耗时(方便人工核对):
awk '$7 ~ /^\/api\/user\/profile($|\?)/ {print $7, $NF}' /var/log/nginx/access.log
注意:$7 是默认 combined 格式中 request 字段的位置;若你自定义了 log_format,需用 awk '{print $1,$2,...}' 先确认 $request_uri 和 $request_time 分别在第几列。
统计与定位慢请求
对提取出的耗时数据做进一步分析:
- 查看耗时 Top 10 请求:
awk '$7 ~ /^\/api\/user\/profile($|\?)/ {print $7, $NF}' /var/log/nginx/access.log | sort -k2 -nr | head -10 - 统计平均/最大/95 分位耗时(需安装
datamash):awk '$7 ~ /^\/api\/user\/profile($|\?)/ {print $NF}' /var/log/nginx/access.log | datamash mean 1 max 1 percentile 95 1 - 找出超过 2 秒的请求(可配合排查):
awk '$7 ~ /^\/api\/user\/profile($|\?)/ && $NF > 2 {print $0}' /var/log/nginx/access.log
结合时间或 IP 进一步下钻
单一接口慢,可能和时段、来源有关。例如:
- 查该接口在晚间高峰(20:00–22:00)的平均耗时:
awk '$4 ~ /\[.*:2[0-2]:[0-5][0-9]:[0-5][0-9]/ && $7 ~ /^\/api\/user\/profile($|\?)/ {sum += $NF; cnt++} END {print "avg:", sum/cnt}' /var/log/nginx/access.log - 看哪个 IP 调用该接口最慢(取单次最慢):
awk '$7 ~ /^\/api\/user\/profile($|\?)/ {if ($NF > max) {max=$NF; slowest_ip=$1}} END {print slowest_ip, max}' /var/log/nginx/access.log











