在nginx中记录请求路径和后端响应时间,需在http块定义log_format包含$request_uri和$upstream_response_time,并在启用proxy_pass的location中通过access_log引用;该变量仅在代理生效时输出毫秒级秒数(如0.042),静态服务等非代理场景为空或“-”。

在 Nginx 中记录请求路径(`$request_uri` 或 `$uri`)和后端响应时间(即 upstream 响应耗时),关键在于配置 log_format 并使用合适的变量,同时确保代理配置中启用了 upstream 记录。
定义包含路径与响应时间的日志格式
Nginx 提供了多个内置变量用于日志记录。要记录客户端请求路径和后端真实响应时间,推荐使用:
-
$request_uri:完整原始请求路径(含 query string),如/api/user?id=123 -
$uri:规范化后的路径(无 query string),如/api/user -
$upstream_response_time:后端服务器返回响应所用时间(秒,精度毫秒,多值时以逗号分隔) -
$upstream_connect_time:与 upstream 建立 TCP 连接耗时(可选) -
$upstream_header_time:从发送请求到收到 upstream 响应头的时间(常接近总响应时间)
在 http 块中定义日志格式:
log_format main_with_time '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$request_uri $upstream_response_time;'注意:$upstream_response_time 仅在使用 proxy_pass、fastcgi_pass 等 upstream 指令时有效;若直接服务静态文件,该值为空或为“-”。
启用 upstream 相关计时并确保 proxy_pass 正确配置
确保你的 server 或 location 块中使用了反向代理,并开启必要的 upstream 计时支持(Nginx 1.9.1+ 默认开启,无需额外指令):
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
# 可选:传递请求开始时间,便于后端对齐日志
proxy_set_header X-Request-Start $msec;
}如果 backend 是多个服务器(如 upstream 块定义),$upstream_response_time 会记录本次实际转发的那台服务器的响应时间。若需更细粒度(如每个 upstream 的耗时),需结合 map 或 Lua 模块处理。
将自定义格式应用到 access_log
在 server 或 http 块中指定日志使用刚定义的格式:
access_log /var/log/nginx/access.log main_with_time;
重启或重载 Nginx 生效:
nginx -t && nginx -s reload
日志样例:
192.168.1.100 - - [10/Jul/2024:14:22:35 +0800] "GET /api/order?uid=789 HTTP/1.1" 200 1245 "-" "curl/7.68.0" /api/order?uid=789 0.042;
其中 /api/order?uid=789 是完整路径,0.042 表示后端响应耗时 42ms。
注意事项与常见问题
- 若
$upstream_response_time显示为“-”,说明未走 upstream(如匹配了 root 静态服务),或 upstream 不可用导致 fallback 到 error_page - 使用
try_files或内部重定向时,$upstream_response_time可能不生效,因其非 proxy 场景 - 高并发下日志可能丢失毫秒精度,如需微秒级,需配合 OpenResty + Lua 或外部 tracing 工具
- 避免在 log_format 中误用
$request_time(Nginx 处理总耗时,含排队、读请求体等,≠ 后端响应时间)











