Nginx通过map指令将$request_time映射为耗时等级和告警标识,结合自定义日志格式实现按区间记录与外部告警联动,告警需依赖日志采集系统或定时脚本触发。

Nginx 本身不直接记录请求耗时到日志中用于条件判断,但可通过 $request_time 变量结合 map 指令实现“按耗时区间映射等级”,进而驱动差异化日志写入与外部告警触发。关键在于:map 是运行时变量映射,不执行命令,告警需靠日志采集端(如 Filebeat + Logstash / Prometheus + Alertmanager)或定时脚本联动实现。
一、定义耗时等级变量(map 块核心)
在 http 块中定义 map,将 $request_time 映射为可读等级和对应动作标识:
map $request_time $rt_level {
default "normal";
~^[0-9]\.[0-9]{3}$ "normal"; # 小于 1s(正则覆盖 0.001–0.999)
~^1\.[0-9]{3}$ "slow"; # 1.000–1.999s
~^2\.[0-9]{3}$ "slow"; # 2.000–2.999s
~^[3-9]\.[0-9]{3}$ "critical"; # ≥3.000s(含 3.x, 4.x…9.x)
~^[1-9][0-9]\.[0-9]{3}$ "critical"; # ≥10.000s(如 10.001, 15.234)
}
map $request_time $rt_alert_flag {
default 0;
~^[3-9]\.[0-9]{3}$ 1;
~^[1-9][0-9]\.[0-9]{3}$ 1;
}
说明:
- 使用正则匹配而非数值比较,因 map 不支持 >、
- $rt_level 用于日志格式分类,$rt_alert_flag 用于后续 if 判断是否触发告警标记;
- 注意小数位固定为三位(Nginx 默认精度),避免 0.9999 被截为 0.999 导致误判。
二、配置分级日志格式与输出
定义不同 level 对应的日志格式,并通过 access_log 的 if 条件控制写入:
log_format slow_log '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$request_time $upstream_response_time $rt_level';
<p>log_format critical_log '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$request_time $upstream_response_time $rt_level '
'ALERT=HIGH';</p><p>access_log /var/log/nginx/access.log main;
access_log /var/log/nginx/slow.log slow_log if=$rt_alert_flag;
access_log /var/log/nginx/critical.log critical_log if=$rt_alert_flag;</p>说明:
- main 日志保持全量记录;
- slow.log 和 critical.log 共享同一 if 条件($rt_alert_flag == 1),实际内容由 log_format 区分;
- 若需更细粒度(如仅记录 ≥5s 才告警),可新增 map 分支并调整 if 条件变量。
三、联动外部告警(以 Filebeat + Alertmanager 为例)
Nginx 不主动发告警,需由日志收集器识别关键行后触发:
- 在 Filebeat 配置中为 critical.log 启用 multiline 或自定义 regexp 提取 ALERT=HIGH 行;
- 添加 processor 添加字段 tag: "nginx_critical_latency";
- Logstash 或 Promtail 将该 tag 转为指标(如 nginx_latency_critical_total),暴露给 Prometheus;
- Alertmanager 配置规则:
alert: NginxHighLatency<br>expr: nginx_latency_critical_total[5m] > 3<br>for: 2m
; - 也可用简单方案:crontab 每分钟执行
grep -q "ALERT=HIGH" /var/log/nginx/critical.log && echo "$(date) HIGH LATENCY!" | mail -s "Nginx Alert" admin@ex.com。
四、验证与调试要点
上线前务必验证 map 映射逻辑和日志落盘行为:
- 临时加一条 location,用 return 499 并 sleep 控制耗时:
location /test-slow { add_header X-Rt $request_time; return 499; },配合 curl -I 测试响应头; - 检查 error_log 中是否有 map 相关警告(如正则语法错误);
- 确认日志文件权限为 nginx worker 进程可写(chown nginx:nginx /var/log/nginx/*.log);
- 使用 tail -f + grep 实时观察 slow.log/critical.log 是否按预期写入;
- 注意:$request_time 是从接收首字节到发送完响应的总时间,不含 TCP 握手和客户端接收时间。











