Nginx 缓存命中状态可视化监控需配置 $upstream_cache_status 变量并写入日志:启用 proxy_cache、在 log_format 中添加该变量、应用自定义日志格式,再通过 ELK/Prometheus 等工具聚合分析 HIT 率。

要在 Nginx 中实现缓存命中状态的可视化监控,关键一步是让日志中真实记录每次请求的缓存行为。而 $upstream_cache_status 变量正是这个能力的核心——它能告诉你这次请求是 HIT(命中)、MISS(未命中)、EXPIRED(过期)、BYPASS(被绕过)还是 STALE(陈旧)等状态。
确认缓存配置已启用并正确设置 proxy_cache
该变量只有在使用 proxy_cache 指令且后端响应可缓存时才有效。确保你的 location 块中包含类似以下配置:
-
proxy_cache my_cache;—— 引用已定义的缓存区 -
proxy_cache_valid 200 302 10m;—— 明确指定哪些状态码可缓存及有效期 -
proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;—— 允许返回陈旧内容(影响 STALE 状态出现) -
add_header X-Cache-Status $upstream_cache_status;(可选)—— 方便调试时直接看到响应头
在 log_format 中加入 $upstream_cache_status 变量
修改 nginx.conf 的 http 块,定义一个带缓存状态的日志格式:
log_format cache_log '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$upstream_cache_status '
'$upstream_response_time $request_time';然后在 server 或 location 中应用该格式:
access_log /var/log/nginx/cache_access.log cache_log;
重启或重载 Nginx 后,日志行末尾就会多出类似 HIT、MISS、BYPASS 这样的字段。
采集日志并构建缓存命中率监控视图
有了结构化日志,就可以用常见可观测性工具做聚合分析:
-
ELK Stack(Elasticsearch + Logstash + Kibana):Logstash 解析日志时提取
upstream_cache_status字段;Kibana 中创建折线图,按分钟统计 HIT / (HIT + MISS + EXPIRED + STALE) 得到实时命中率 -
Prometheus + Grafana:用
mtail或nginxlog-exporter抓取日志,将不同 cache_status 计为计数器指标;Grafana 中用 PromQL 写表达式如:rate(nginx_http_upstream_cache_status_total{status="HIT"}[5m]) / rate(nginx_http_upstream_cache_status_total[5m]) -
简单脚本统计(临时验证):
tail -n 10000 /var/log/nginx/cache_access.log | awk '{print $12}' | sort | uniq -c | sort -nr快速查看各状态分布
注意变量生效的前提与常见陷阱
$upstream_cache_status 不是万能的,它只在启用 proxy_pass 且走缓存路径时才有值。以下情况会显示 -(短横线):
- 请求未进入带
proxy_cache的 location(比如静态文件直出、内部重定向未匹配) - 后端响应含
Cache-Control: no-store或Set-Cookie(默认不缓存) - 使用了
proxy_cache_bypass且条件满足,强制跳过缓存 - 请求方法不是 GET/HEAD(默认不缓存 POST 等)
建议搭配 $scheme://$host$request_uri 和 $upstream_addr 一起记录,便于定位为何某类请求始终 MISS。


















