必须通过日志采集Agent解析Nginx error.log异常并转为Prometheus Counter指标,如nginx_error_upstream_timeout_total{type="upstream_timed_out"},推荐使用prometheus-nginx-exporter或Vector实现结构化解析与指标暴露。

直接采集 Nginx 错误日志(error.log)中的关键异常频次,不能靠 Prometheus 原生抓取,因为 error.log 是非结构化文本,而 Prometheus 只能采集指标型数据(如 counter、gauge)。必须通过“日志采集 Agent → 解析提取 → 转为 Prometheus 指标 → 抓取告警”这条链路来实现。
错误日志需先结构化解析再暴露为指标
Nginx error.log 默认格式不带固定分隔符,内容混杂(如 [error]、[warn]、[crit] 级别,含不同上下文),Prometheus 无法直接识别。必须用日志采集工具做两件事:
- 按行匹配关键异常模式,例如:
upstream timed out、connect() failed、no live upstreams、host not found in upstream、recv() failed - 将每次匹配计为一个事件,并按类型聚合为 Prometheus Counter 指标,如
nginx_error_upstream_timeout_total{type="upstream_timed_out"}
推荐方案:用 prometheus-nginx-exporter 或 Vector 解析 error.log
官方 prometheus-nginx-exporter(注意不是 nginx-prometheus-exporter)支持 error.log 解析,但仅限普通文本格式(不支持 JSON)。配置示例:
- 在 exporter 配置中启用 error log 输入:
error_log_path: "/var/log/nginx/error.log" - 定义正则规则提取异常类型:
error_patterns: { "upstream_timeout": "upstream timed out", "connect_fail": "connect\(\) failed", "no_upstream": "no live upstreams" } - 启动后,访问
http://localhost:9113/metrics即可看到类似:nginx_error_total{type="upstream_timeout"} 42nginx_error_total{type="connect_fail"} 7
更灵活的替代:Fluentd/Vector + Prometheus Exporter 插件
若需更高控制力(比如按时间窗口统计每分钟异常次数、关联客户端 IP 或 upstream 名称),可用 Fluentd 或 Vector 做预处理:
- Fluentd 使用
@type grep+@type prometheus插件,将匹配行转为指标并暴露/metrics - Vector 配置 filter 匹配 error 日志中的关键词,再用
prometheus_exportersink 输出指标,支持标签动态注入(如upstream="backend-api") - 优势:可与 access.log 关联分析(例如某 upstream 异常时是否伴随大量 502 请求)
告警设置建议:聚焦突增与持续性异常
不要只看绝对数值,应监控“异常频次的速率变化”。在 Prometheus 中写如下告警规则:
- 过去 5 分钟内,
upstream_timeout类异常每秒超过 0.5 次:rate(nginx_error_total{type="upstream_timeout"}[5m]) > 0.5 - 同一类型异常连续 3 个周期(如每 1 分钟采样)均高于阈值,避免毛刺误报
- 组合判断:若
connect_fail+no_upstream同时上升,可能指向上游服务整体宕机,触发高优告警


















