要明确记录Nginx负载均衡中请求转发的后端节点,需使用$upstream_addr变量自定义log_format,并在server或location中启用;该变量准确记录实际转发地址(含重试链路),配合$upstream_status、$upstream_response_time等可提升排障能力。

在 Nginx 负载均衡场景中,默认 access_log 只记录客户端发起的请求,不体现后端节点选择结果。要明确知道某次请求被转发到了哪台 upstream 服务器,需通过变量和日志格式定制实现。
启用 $upstream_addr 变量记录实际转发地址
Nginx 提供了多个内置变量用于记录上游通信细节,其中最关键的是 $upstream_addr:它会记录请求最终被转发到的后端地址(含 IP 和端口),支持多级代理(如使用 proxy_pass 指向另一个 upstream)时显示完整链路,若发生重试还会用逗号分隔多个地址。
- 若请求直接转发给 192.168.1.10:8080 → 日志中显示 192.168.1.10:8080
- 若第一次失败后重试到 192.168.1.11:8080 → 显示 192.168.1.10:8080, 192.168.1.11:8080
- 若使用 keepalive 或连接复用,该变量仍准确反映本次请求所用后端
自定义 log_format 并在 server 或 location 中启用
在 http 块中定义带 upstream 相关变量的日志格式,然后在需要监控的 server 或 location 块中引用:
http {
log_format upstream_log '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'upstream: $upstream_addr '
'upstream_response_time: $upstream_response_time '
'request_time: $request_time';
<pre class="brush:php;toolbar:false;">upstream backend {
server 192.168.1.10:8080;
server 192.168.1.11:8080;
}
server {
location / {
proxy_pass http://backend;
access_log /var/log/nginx/upstream_access.log upstream_log;
}
}}
补充关键变量提升排障能力
除 $upstream_addr 外,以下变量常配合使用,帮助定位转发行为异常:
- $upstream_status:后端返回的 HTTP 状态码(如 200、502、504),可识别后端错误类型
- $upstream_response_time:从建立连接到接收完响应头的时间(秒,精度毫秒),用于判断后端性能瓶颈
- $upstream_http_x_trace_id:若后端注入了 trace ID,可通过此变量透传并记录,便于全链路追踪
- $upstream_connect_time 和 $upstream_header_time:分别表示建连耗时与等待响应头时间,辅助区分网络延迟与后端处理慢
注意日志位置与权限问题
确保 Nginx 工作进程(通常是 nobody 或 nginx 用户)对日志路径有写入权限;避免将 upstream 日志与主 access_log 混用,建议独立文件便于 grep 或日志采集;高并发场景下可考虑开启 buffer 和 flush 机制防止 I/O 阻塞:
access_log /var/log/nginx/upstream_access.log upstream_log buffer=64k flush=5s;











