需在nginx中使用log_format定义含$request_time和$upstream_response_time的日志格式,并在access_log中引用;前者为总处理时间,后者为上游通信时间,重启后日志末尾将显示两个毫秒级数值。

要在 Nginx 中记录响应时间,需使用 log_format 指令定义一个包含 $request_time(或 $upstream_response_time)的自定义日志格式,并在 access_log 中引用它。
定义含响应时间的日志格式
在 http 块中(通常位于 /etc/nginx/nginx.conf 或 /etc/nginx/conf.d/xxx.conf)添加 log_format 指令:
示例:
log_format main_with_time '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$request_time $upstream_response_time';
其中:
-
$request_time:客户端请求从接收第一个字节到发送完响应的总时间(单位:秒,精度为毫秒) -
$upstream_response_time:Nginx 与上游服务器(如 FastCGI、proxy)交互所花的时间,多个 upstream 时用逗号分隔(如负载均衡场景) - 注意:
$upstream_response_time在未启用代理或 FastCGI 时可能为空或“-”,建议搭配$request_time使用更稳妥
启用该日志格式
在 server 或 location 块中指定 access_log,并引用你定义的格式名(如 main_with_time):
server {
listen 80;
server_name example.com;
access_log /var/log/nginx/access.log main_with_time;
# 其他配置...
}
确保日志路径有写入权限,且 Nginx 配置语法正确(可用 nginx -t 测试)。
常见注意事项
-
$request_time是请求处理总耗时,包括读取请求头/体、执行处理逻辑、生成响应、发送响应等全部阶段 -
$upstream_response_time只统计与后端通信时间,不含 Nginx 自身处理开销,适合排查后端性能瓶颈 - 若需更高精度(如微秒级),Nginx 默认不支持;可通过
$msec(秒级时间戳,精度毫秒)配合自定义计算间接估算,但不推荐替代$request_time - 日志中数值为字符串格式,如
0.023表示 23 毫秒;分析时可用工具(如 awk、goaccess、ELK)解析浮点字段
验证是否生效
重启或重载 Nginx 后发起一次请求,然后查看日志:
tail -n 1 /var/log/nginx/access.log
应看到类似:
127.0.0.1 - - [10/Jul/2024:15:22:33 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.68.0" 0.012 0.011
最后两个数字即 $request_time 和 $upstream_response_time。











