关键是要将灰度标识(如version=beta)提取为结构化变量$logfile_version并写入日志,再通过elk、prometheus或awk按版本分组统计$request_time;需在http块用map提取、定义含$log_version的日志格式、在server中启用access_log,并验证各版本平均响应时间。

要分析灰度路径的平均响应时间表现,关键不是只记下原始 Cookie 字符串,而是把灰度标识(如 version=beta、gray=on)提取为结构化变量,再写入日志——这样后续用 ELK、Prometheus + Grafana 或简单 awk + sort 就能按版本分组统计 $request_time。
一、在 http 块中用 map 提取灰度标识为日志可用变量
必须在 http{} 块顶层定义,不能放在 server 或 location 里:
- 用
$cookie_version读取名为version的 Cookie 值(注意:Nginx 自动将 Cookie 名转为$cookie_*变量,但仅限字母数字,含下划线需开启underscores_in_headers on) - 匹配时加
~*实现大小写不敏感,用(;|$)边界避免误匹配(例如version=beta_test不被~*beta错抓) - 务必设
default,否则未命中时变量为空,日志字段会缺失或报错
http {
map $cookie_version $log_version {
default "stable";
"~*beta(;|$)" "beta";
"~*v2(;|$)" "v2";
"~*canary(;|$)" "canary";
}
}
二、定义带灰度标识的日志格式
在 http{} 块中新增 log_format,把提取出的 $log_version 和 $request_time 一起记录:
log_format gray_metrics
'$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'$request_time $upstream_response_time '
'"$http_referer" "$http_user_agent" '
'$log_version; # ← 关键:灰度分组标签'
注意:$request_time 是 Nginx 接收完整请求到发出响应的总耗时(秒,精度毫秒),适合做端到端灰度性能对比;若要看后端真实处理时间,应同时保留 $upstream_response_time。
三、在 server 或 location 中启用该日志
只需在对应作用域添加 access_log 指令,指向你定义的格式名:
server {
listen 80;
server_name example.com;
access_log /var/log/nginx/gray-metrics.log gray_metrics;
location / {
proxy_pass http://backend_$log_version;
proxy_set_header X-Gray-Version $log_version;
}
}
⚠️ 不要重复定义同名 log_format;确保日志路径目录存在且 Nginx 有写权限;高流量场景建议加 buffer=64k flush=5s 减少 I/O。
四、快速验证与基础分析示例
发几个带不同 Cookie 的请求测试:
curl -H "Cookie: version=beta" http://example.com/apicurl -H "Cookie: version=v2" http://example.com/api-
curl http://example.com/api(无 Cookie,走 default stable)
查看日志片段:
192.168.1.100 - - [19/Jun/2026:06:12:33 +0000] "GET /api HTTP/1.1" 200 124 0.248 0.245 "-" "curl/7.68.0" beta
192.168.1.100 - - [19/Jun/2026:06:12:34 +0000] "GET /api HTTP/1.1" 200 124 0.312 0.309 "-" "curl/7.68.0" v2
192.168.1.100 - - [19/Jun/2026:06:12:35 +0000] "GET /api HTTP/1.1" 200 124 0.187 0.184 "-" "curl/7.68.0" stable
用 shell 快速算各版本平均响应时间:
awk '$NF=="beta" {sum+=$7; n++} END {print "beta avg:", sum/n}' /var/log/nginx/gray-metrics.log
更进一步可导出到 Prometheus(配合 nginx-lua-prometheus 模块)或接入 OpenTelemetry,实现实时 P95/P99 灰度对比看板。











