Nginx 通过 $upstream_response_time 等变量记录后端真实处理耗时,需配合 proxy_pass 使用 upstream 模块,并在 log_format 中引入该变量及 $upstream_addr、$upstream_status 等辅助字段实现精准日志追踪。

在 Nginx 中,要记录后端真实节点(即 upstream server)的处理耗时,关键不是靠 log_format 单独实现,而是结合 upstream 模块的变量(如 $upstream_response_time)来完成。这个变量会自动记录 Nginx 与上游服务器通信过程中,每个请求的实际响应时间(单位:秒,精度为毫秒,用小数表示),包括连接、发送请求、等待响应、接收响应的全过程。
确认 upstream 配置并启用响应时间采集
Nginx 默认就支持 $upstream_response_time,但前提是请求确实经过了 proxy_pass(或 fastcgi_pass 等)转发到 upstream。确保你的配置中包含类似如下结构:
upstream backend {
server 10.0.1.10:8080;
server 10.0.2.20:8080;
}
<p>server {
location / {
proxy_pass <a href="https://www.php.cn/link/65b5b8d1f89bf53a5713bc3afdd83e9e">https://www.php.cn/link/65b5b8d1f89bf53a5713bc3afdd83e9e</a>;
proxy_set_header Host $host;
}
}只要用了 proxy_pass 指向一个 upstream 块,Nginx 就会在每次转发后自动填充 $upstream_response_time(多个后端则以逗号分隔,例如 "0.002, 0.004")。
定义 log_format 包含 upstream 耗时变量
在 http 或 server 块中定义日志格式,加入 $upstream_response_time。推荐同时带上 $upstream_addr(实际通信的后端地址)和 $upstream_status(后端返回状态码),便于排查:
log_format main '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$upstream_addr $upstream_response_time $upstream_status';注意:
– $upstream_response_time 在未走 upstream(如静态文件直出)时值为空,日志中对应位置会显示“-”;
– 若使用了重试(proxy_next_upstream),该变量会记录所有尝试的时间,用逗号拼接;
– 如需只取第一个成功后端的耗时,可用 $upstream_response_time 的第一个值(需配合 Lua 或后期日志解析),纯 Nginx 不支持切片。
可选:记录更细粒度的耗时(如 connect、header、response 分段)
Nginx 1.19.1+ 支持更精确的 upstream 时间变量(需开启 proxy_http_version 1.1 并确保后端支持):
-
$upstream_connect_time:与后端建连耗时(含 DNS 解析、TCP 握手) -
$upstream_header_time:从发送完请求到收到后端响应头的时间(即首字节时间) -
$upstream_response_time:完整响应耗时(等价于 header_time + body 接收时间)
这些变量同样可直接用于 log_format,例如:
log_format detail '$upstream_addr [$upstream_connect_time|$upstream_header_time|$upstream_response_time]';
验证与注意事项
修改配置后执行 nginx -t 测试语法,再 nginx -s reload 生效。查看 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" 10.0.1.10:8080 0.023 200
说明该次请求由 10.0.1.10:8080 处理,总耗时 0.023 秒,返回状态 200。
⚠️ 注意:
– 这些变量仅对代理请求有效,不适用于 return、try_files 直出或 error_page 内部跳转;
– 若使用了负载均衡策略(如 least_conn),$upstream_addr 可帮你确认具体打到了哪台机器;
– 日志中若出现“-”或“0.000”,可能是请求未发往 upstream,或后端快速返回空响应,需结合业务逻辑判断。


















