要在 nginx 中定位慢接口,需在 log_format 中记录 $request_time 和 $upstream_response_time,通过对比二者耗时判断瓶颈:均大则后端问题,$request_time 大而 $upstream_response_time 小则 nginx 或客户端问题,后者为空则排查静态处理或模块性能。

要在 Nginx 中通过访问日志定位慢接口,关键是在 log_format 中显式记录 $request_time 和 $upstream_response_time,并配合合理的时间阈值分析日志。
配置自定义日志格式,包含关键耗时字段
在 http 块中定义日志格式,确保同时捕获整体请求时间和上游响应时间:
log_format main '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$request_time $upstream_response_time';
access_log /var/log/nginx/access.log main;
注意:
- $request_time 是 Nginx 接收完整请求到发送完响应的总耗时(单位:秒,精度毫秒);
- $upstream_response_time 是 Nginx 与后端(如 PHP-FPM、Tomcat、Go 服务)交互的耗时,可能包含多个 upstream 的逗号分隔值(如 0.002, 0.004),只取第一个值通常代表主服务响应时间;
- 若后端是直连(非 proxy_pass),$upstream_response_time 会为空或为“-”,此时应重点关注 $request_time。
区分慢请求类型:网络层 vs 后端服务层
通过对比两个字段可快速判断瓶颈所在:
- 两者都大(如 >1s):问题大概率在后端服务逻辑或数据库查询,需检查应用代码和 DB 慢查日志;
- $request_time 大但 $upstream_response_time 很小(如 0.002):说明 Nginx 自身处理耗时高,可能是 SSL 握手、大文件上传、请求体解析、或者客户端网络差(如弱网上传慢);
- $upstream_response_time 大但 $request_time 接近它:典型后端响应慢,且 Nginx 转发开销低,优先排查 upstream 服务健康状态和性能;
- $upstream_response_time 为空或“-”但 $request_time 大:未走 proxy_pass,可能是静态文件处理慢(如磁盘 I/O)、gzip 压缩耗时、或使用了耗性能的模块(如复杂的 rewrite 规则)。
用命令行快速筛选慢请求(示例:耗时 ≥ 1 秒)
日志写入后,可用以下命令提取可疑请求:
# 提取 request_time ≥ 1s 的所有行(假设字段顺序固定)
awk '$(NF-1) >= 1 || $NF >= 1' /var/log/nginx/access.log
<h1>更精准:按空格切分,取倒数第二列($request_time)和最后一列($upstream_response_time)</h1><p>awk '{rt=$(NF-1); ut=$NF} rt>=1 || (ut!="-" && ut>=1)' /var/log/nginx/access.log</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill3427" title="Nginx Config Linter"><img
src="https://img.php.cn/upload/skill/000/000/081/178955659937208.jpg" alt="Nginx Config Linter" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill3427" title="Nginx Config Linter" class="overflowclass">Nginx Config Linter</a>
<p class="overflowclass">对 Nginx 配置文件进行语法检查、验证和安全、性能审计。</p>
</div>
<a rel="nofollow" href="/xiazai/skill3427" title="Nginx Config Linter" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div><h1>查看最慢的前 10 条(按 request_time 降序)</h1><p>awk '{print $(NF-1), $0}' /var/log/nginx/access.log | sort -nr | head -10</p>建议将结果重定向到临时文件,再结合 grep 过滤特定接口路径(如 grep '/api/order/submit')进一步聚焦。
进阶建议:按接口维度聚合统计平均耗时
若需长期监控,可用脚本或 ELK 对日志做聚合分析。简单场景下,可用 awk 统计某类接口的平均响应时间:
# 统计 /api/v1/user/info 接口的平均 request_time
awk '$7 ~ /^"GET \/api\/v1\/user\/info/ {sum += $(NF-1); cnt++} END {if(cnt) print "avg:", sum/cnt, "count:", cnt}' /var/log/nginx/access.log
其中 $7 是 $request 字段(因 log_format 中它排第 7 位),可根据实际字段位置调整编号。生产环境推荐接入 Prometheus + nginx-vts-exporter 或 OpenTelemetry 实现可视化监控。










