在大部分的项目中都有自定义告警规则的需求,目前市面上都是基于Prometheus实现的监控告警。但是Prometheus本身并不支持修改告警规则自动生效,我们可以通过下面这些步骤实现告警规则动态配置。
1. 启动Promethues并指定参数--web.enable-lifecycle
nohup ./prometheus --web.enable-lifecycle &
2. 配置告警规则文件
rule_files:- "alert-rules.yml"
3. 业务代码生成PromQL告警规则,写入alert-rules.yml文件
groups:
- name: examplerules:- alert: HighHTTPRequestLatencyexpr: job:request_latency_seconds:mean5m{job="myjob"} > 0.5for: 10mlabels:severity: pageannotations:summary: High request latencydescription: "99th percentile latency for job {{ $labels.job }} is above 0.5 seconds for the last 10 minutes."
4. 动态加载告警规则
业务通过Restful接口触发prometheus告警规则动态加载curl -XPOST http://ip:9090/-/reload
注意:prometheus配置文件必须和业务服务使用同一文件,可以通过NFS或者PVC(k8s环境下)等方式实现。