Nginx反向代理中记录后端真实处理耗时需使用$upstream_response_time变量,配合自定义log_format输出,该变量反映Nginx到后端网络传输与业务处理总时间,单位秒、精度毫秒;需确保proxy_pass生效,避免提前终止请求,并注意多实例重试时耗时以逗号分隔。

在 Nginx 反向代理中记录后端真实处理耗时(即 upstream 响应耗时),关键是要使用 $upstream_response_time 变量,并配合自定义日志格式输出。它能精确反映 Nginx 与后端服务器之间网络传输 + 后端业务处理的总时间,单位为秒,精度可达毫秒(如 0.032 表示 32ms)。
配置自定义日志格式,包含 upstream 耗时字段
在 http 块中定义 log_format,显式加入 $upstream_response_time(注意:该变量在请求未发往 upstream 时为空或“-”,多个 upstream 会以逗号分隔):
log_format main_with_upstream '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$request_time $upstream_response_time $upstream_addr';
说明:
-
$request_time:客户端到 Nginx 的整体请求耗时(含接收请求、转发、等待 upstream、发送响应全过程) -
$upstream_response_time:Nginx 发起请求到收到 upstream 完整响应的时间(核心指标) -
$upstream_addr:实际通信的后端地址(便于排查具体哪台机器慢)
确保 proxy_pass 正确启用并触发 upstream 记录
只有实际执行了反向代理(即命中 proxy_pass 指令),$upstream_response_time 才有值。需确认:
- location 块中明确使用了
proxy_pass(而非return、rewrite或静态文件服务) - 避免在 proxy 配置前用
return或deny提前终止流程,否则 upstream 变量为空 - 若用 if 判断再 proxy_pass,需注意 if 在 location 中限制多,建议改用 map 或 try_files
处理多实例/重试场景下的耗时记录
当配置了 proxy_next_upstream 并发生重试时,$upstream_response_time 会记录所有尝试的耗时,用逗号分隔(如 0.012, 0.045)。如需单次最短/最长/平均耗时,需在日志分析阶段处理。若只关心最后一次成功响应耗时,可搭配 $upstream_http_x_request_id 等自定义 header,在后端统一注入更精确的 server 处理时间。
验证日志是否生效
重启 Nginx 后发起一次代理请求,检查 access.log 是否出现类似行:
192.168.1.100 - - [10/Jul/2024:14:22:33 +0800] "GET /api/user HTTP/1.1" 200 124 "-" "curl/7.68.0" 0.048 0.045 10.0.2.5:8080
其中 0.048 是 $request_time,0.045 是 $upstream_response_time,10.0.2.5:8080 是真实后端地址 —— 数据存在即配置成功。


















