应使用 $upstream_response_time 记录从 nginx 接收请求到返回响应的完整上游耗时,它包含网络传输、python 应用处理及数据库等全部环节;需通过反向代理(如 gunicorn/uvicorn)部署应用以启用该变量,并可选透传 python 内部耗时至响应头供 nginx 记录。

要在 Nginx 中记录 Python 应用(如 Flask、Django 或 FastAPI)的详细请求耗时,关键不是让 Nginx 直接测 Python 代码执行时间,而是利用 Nginx 自身的变量和反向代理上下文,结合合理的日志格式与后端配合,获取**从 Nginx 接收请求到返回响应的完整上游耗时**(即含网络传输、Python 应用处理、数据库等全部环节),这是最贴近真实用户感知的“请求耗时”。
1. 使用 $upstream_response_time 记录真实后端处理耗时
Nginx 提供 $upstream_response_time 变量,表示 Nginx 与 upstream(即你的 Python 应用)之间通信所花费的时间——从发送请求头开始,到接收完全部响应头为止。它以毫秒为单位,支持多段(如负载均衡多个实例时),默认取第一个成功响应的时间。
✅ 推荐配置示例(在 http 或 server 块中):
log_format detailed '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$request_time $upstream_response_time $upstream_connect_time $upstream_header_time';
access_log /var/log/nginx/app.log detailed;
说明:
- $request_time:整个请求在 Nginx 内部的总耗时(含等待、读请求体、转发、收响应等)
- $upstream_response_time:核心指标,反映 Python 应用实际处理 + 网络延迟的综合耗时
- $upstream_connect_time:Nginx 连接 upstream 的耗时(可判断连接是否慢或不稳定)
- $upstream_header_time:从发送请求头到收到响应头的时间(近似应用“首字节时间”,TTFB)
2. 确保 Python 应用正确部署在 upstream 中
Nginx 必须以反向代理方式将请求转给 Python 应用(不能是静态文件服务),否则 $upstream_* 变量全为空或“-”。常见部署方式:
- Gunicorn + Nginx(推荐):Gunicorn 启动 Flask/Django,Nginx proxy_pass 到
127.0.0.1:8000 - Uvicorn + Nginx(FastAPI/Starlette):同理,proxy_pass 到
127.0.0.1:8001 - 不要用 Nginx 的
fastcgi_pass或直接跑 Python 脚本——这些不触发 upstream 变量
示例 upstream 配置片段:
upstream python_app {
server 127.0.0.1:8000 max_fails=3 fail_timeout=30s;
}
server {
listen 80;
location / {
proxy_pass http://python_app;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
3. 补充:在响应头中透出 Python 应用内耗时(可选但实用)
若需区分“框架层耗时”和“纯业务逻辑耗时”,可在 Python 应用中计算并写入响应头(如 X-Process-Time: 124.56ms),再由 Nginx 记录:
log_format with_py_time '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'$request_time $upstream_response_time '
'$upstream_http_x_process_time'; // ← 捕获响应头
对应 Python(Flask 示例):
@app.after_request
def after_request(response):
response.headers["X-Process-Time"] = f"{time.time() - request.start_time:.2f}ms"
return response
⚠️ 注意:$upstream_http_x_process_time 是小写下划线命名,且仅当响应头存在时才生效。
4. 日志分析建议:避免只看平均值
单靠 $upstream_response_time 字段已足够定位慢请求,但要注意:
- 该字段可能含多个值(如
0.123, 0.456),表示重试;建议用日志采集工具(如 Filebeat + Elasticsearch)做分隔解析 - 设置 Nginx
log_subrequest on;可记录子请求(如 internal redirect),但通常不需要 - 配合监控:用 Prometheus + nginx-exporter 抓取
nginx_upstream_response_ms指标,做 P95/P99 耗时告警
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!











