Nginx 访问日志记录请求耗时需使用 $request_time 变量,配置 log_format(如 timed)并搭配 access_log 指令启用,再通过 nginx -t 和 nginx -s reload 生效;配合 $upstream_response_time 等变量可定位瓶颈。

在 Linux 系统的 Nginx 访问日志中记录请求处理耗时,核心是使用内置变量 $request_time,它能精确反映 Nginx 从接收请求首字节到发送完响应末字节的总耗时(单位:秒,精度毫秒)。
配置 log_format 添加 $request_time
在 nginx.conf 的 http 块内定义或修改日志格式,确保包含 $request_time,且不加引号、不包裹空格:
- 推荐写法(清晰、兼容性好):
log_format timed '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" $request_time'; - 不能复用
combined等内置名称覆盖,必须另起格式名(如timed) -
$request_time只能在log_format中使用,不可用于if或重写规则
绑定 access_log 并启用该格式
在 http 块或具体 server 块中,将 access_log 指令指向你定义的格式名:
- 例如:
access_log /var/log/nginx/access.log timed; - 路径建议用绝对路径(如
/var/log/nginx/access.log),便于统一管理与日志轮转 - 若需对比后端性能,可一并加入
$upstream_response_time:... $request_time $upstream_response_time';
验证配置并确认日志生效
保存配置后,必须执行以下两步才能让耗时字段出现在日志中:
- 运行
nginx -t检查语法是否正确 - 执行
nginx -s reload重新加载配置(无需重启进程) - 发起一次 HTTP 请求后,查看
access.log,末尾应出现类似0.042的数值——这就是本次请求在 Nginx 内部的完整耗时(三位小数即毫秒级)
区分关键耗时变量辅助定位瓶颈
单看 $request_time 只知“总共多慢”,要判断慢在哪,需结合其他变量:
-
$upstream_response_time:Nginx 发完请求到收到后端响应头的时间(仅代理场景有效) -
$upstream_connect_time:与后端建立 TCP 连接(含 TLS 握手)耗时 -
$upstream_header_time:从连接完成到收到响应首行的时间(含请求发出 + 后端处理) - 若
$request_time − $upstream_response_time > 0.2,说明延迟集中在 Nginx 本机(如 rewrite 复杂、SSL 开销大、日志写入慢) - 若
$upstream_response_time为空或为-,需检查proxy_pass是否配置正确、后端是否可达、超时参数是否合理


















