nginx中$upstream_response_time可直接用于log_format实现毫秒级后端耗时监控,其值为秒级三位小数(如0.123即123ms),需确保请求经proxy_pass转发且upstream响应成功,否则为空或“-”。

要在 Nginx 中通过 log_format 引入 $upstream_response_time 实现毫秒级后端耗时监控,关键在于确保该变量在日志上下文中可用、格式化输出为可读毫秒值,并配合 access_log 正确启用。
确认 upstream 配置与请求路径
$upstream_response_time 仅在请求经过 proxy_pass(或 fastcgi/uwsgi/scgi)转发到 upstream 时才有值;若请求未走代理(如静态文件直出),该变量为空或“-”。因此需确保:
- 目标 location 使用了
proxy_pass指向有效的 upstream 块或后端地址 - 后端服务实际响应并返回了时间(Nginx 在收到完整响应头后才记录此值)
- 避免在无代理的 location(如
try_files静态服务)中误用该变量
定义支持毫秒精度的 log_format
Nginx 默认的 $upstream_response_time 已是秒为单位、保留三位小数的浮点数(如 0.123 表示 123ms)。无需额外转换,直接拼入日志格式即可。推荐写法:
log_format main '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$upstream_response_time';注意:
– 不要加引号包裹 $upstream_response_time,否则会输出字符串字面量而非数值
– 若需统一单位为毫秒整数(如 123 而非 0.123),Nginx 原生不支持四则运算,但可通过外部工具(如 awk、loki 插件、ELK pipeline)做乘1000处理
启用日志并验证变量是否生效
在 server 或 location 块中启用该格式:
access_log /var/log/nginx/access.log main;
重启 Nginx 后,发起一次真实代理请求(如 curl http://your-domain/api/test),然后检查日志:
192.168.1.100 - - [10/Jul/2024:14:22:33 +0800] "GET /api/test HTTP/1.1" 200 124 "-" "curl/7.68.0" 0.042
末尾 0.042 即表示后端耗时 42ms。若看到 -,说明该请求未进入 upstream 流程(如 404、内部重定向失败、或配置未命中 proxy_pass)
进阶:多 upstream 场景与空值处理
当一个请求可能经过多个 upstream(如 proxy_cache_use_stale + proxy_pass fallback),$upstream_response_time 会记录**最后一次成功 upstream 的耗时**;若全部失败,则为空。如需区分各次尝试,可用:
-
$upstream_connect_time:连接后端建立 TCP 的耗时 -
$upstream_header_time:接收后端响应头的时间(含 connect + send request + wait response header) -
$upstream_http_x_response_time:若后端主动返回X-Response-Time头,也可透传记录
对空值统一补 0 可用 map 指令预处理(Nginx ≥ 1.11.0):
map $upstream_response_time $urestime {
"" "0.000";
default $upstream_response_time;
}
log_format main ... $urestime;











