应组合使用 error_log debug、自定义 log_format 和 location 标记实现精准日志追踪:在特定 server 或 location 块启用 debug 日志并限流,配合 debug_connection 控制范围,用 add_header 暴露阶段信息,再以 access_log 补充结构化快照。

要对特定请求阶段做详细日志追踪,不能只靠 access_log —— 它只在请求结束时写一次,看不到 rewrite、proxy_pass 前后的变量变化。真正有效的方式是组合使用 error_log debug + 自定义 log_format + 关键 location 标记,按需聚焦阶段,避免日志爆炸。
精准开启 debug 日志,只盯目标请求
全局开 debug 会撑爆磁盘,必须限流:
- 在具体 server 或 location 块里加
error_log /var/log/nginx/stage-debug.log debug;,不放 main 块 - 配合
debug_connection 192.168.1.50;只对投诉用户 IP 开启,或用网段如debug_connection 10.0.0.0/8; - 本地调试时加
daemon off; master_process off;,防止多进程日志混杂
识别各阶段的关键 debug 线索
debug 日志按处理流程输出,重点关注带 “[debug]” 前缀的行:
-
请求接入:看到
http header: "Host: api.example.com"和http process request line,说明已接收并解析首行 -
location 匹配:出现
using configuration "/api/v1/"或regex "^/user/.*",确认路由是否走对 -
rewrite 执行:含
rewrite phase: 2、test location: "/v2/"、using configuration "/v2/",判断是否发生内部跳转 -
转发上游:关键标志是
http proxy header: "GET /order HTTP/1.0"、upstream: "http://order-svc"、connect to 10.0.1.10:8080 -
子请求介入:如用
auth_request或 SSI,会出现http subrequest "/_auth"和subrequest done
用响应头直接暴露当前所处阶段
光看 debug 日志还不够直观,可在关键 location 中加响应头辅助定位:
-
add_header X-Debug-Location "$location";—— 返回头里直接标明匹配到的 location 路径 -
add_header X-Debug-Uri "$uri";和add_header X-Debug-Args "$args";—— 查看 rewrite 后的最终 URI 和参数 -
add_header X-Debug-Upstream "$upstream_addr";—— 确认实际转发到了哪个后端地址
搭配 access_log 补充结构化变量快照
debug 日志无结构、难过滤,access_log 可补上关键变量的“定格画面”:
- 定义专用 log_format:
log_format stage '$time_iso8601 | $status | $uri | $args | $upstream_addr | $upstream_response_time | $request_id'; - 在目标 location 中启用:
access_log /var/log/nginx/stage.log stage; - 若需子请求也记录,加
log_subrequest on;(必须放在 http 块) - 注意:access_log 写在请求结束时,适合看最终结果;debug 日志适合看中间过程











