Prometheus技术系列文章——prometheus自定义告警规则解析和配置

prometheus自定义告警规则解析和配置



文章目录

  • Prometheus技术系列文章——prometheus自定义告警规则解析和配置
  • 前言
  • 1. 标准告警规则样例以及各组件作用
  • 2. 模板化告警规则
  • 3. 修改Prometheus配置文件prometheus.yml
  • 总结



前言

本文主要教大家如何prometheus自定义告警规则解析和配置

1. 标准告警规则样例以及各组件作用

代码如下

groups:
- name: example
rules:
- alert: HighErrorRate
expr: job:request_latency_seconds:mean5m{job="myjob"} > 0.5
for: 10m
labels:
severity: page
annotations:
summary: High request latency
description: description info

在告警规则文件中,我们可以将一组相关的规则设置定义在一个group下。在每一个group中我们可以定义多个告警规则(rule)。一条告警规则主要由以下几部分组成:

alert:告警规则的名称。

expr:基于PromQL表达式告警触发条件,用于计算是否有时间序列满足该条件。

for:评估等待时间,可选参数。用于表示只有当触发条件持续一段时间后才发送告警。在等待期间新产生告警的状态为pending。

labels:自定义标签,允许用户指定要附加到告警上的一组附加标签。

2. 模板化告警规则

一般来说,在告警规则文件的annotations中使用summary描述告警的概要信息,description用于描述告警的详细信息。同时Alertmanager的UI也会根据这两个标签值,显示告警信息。为了让告警信息具有更好的可读性,Prometheus支持模板化label和annotations的中标签的值。通过

$ labels.<labelname>

变量可以访问当前告警实例中指定标签的值。

$value

则可以获取当前PromQL表达式计算的样本值。

代码如下

# To insert a firing element's label values:
2
{{ $labels.<labelname> }}
3
# To insert the numeric expression value of the firing element:
4
{{ $value }}

例如,可以通过模板化优化summary以及description的内容的可读性:

代码如下

groups:
- name: example
rules:

# Alert for any instance that is unreachable for >5 minutes.
- alert: InstanceDown
expr: up == 0
for: 5m
labels:
severity: page
annotations:
summary: "Instance {{ $labels.instance }} down"
description: "{{ $labels.instance }} of job {{ $labels.job }} has been down for more than 5 minutes."

# Alert for any instance that has a median request latency >1s.
- alert: APIHighRequestLatency
expr: api_http_request_latencies_second{quantile="0.5"} > 1
for: 10m
annotations:
summary: "High request latency on {{ $labels.instance }}"
description: "{{ $labels.instance }} has a median request latency above 1s (current value: {{ $value }}s)"

3. 修改Prometheus配置文件prometheus.yml

rule_files:
- /etc/prometheus/rules/*.rules

在目录/etc/prometheus/rules/下创建告警文件hoststats-alert.rules内容如下:

代码如下

groups:
- name: hostStatsAlert
rules:
- alert: hostCpuUsageAlert
expr: sum(avg without (cpu)(irate(node_cpu{mode!='idle'}[5m]))) by (instance) > 0.85
for: 1m
labels:
severity: page
annotations:
summary: "Instance {{ $labels.instance }} CPU usgae high"
description: "{{ $labels.instance }} CPU usage above 85% (current value: {{ $value }})"
- alert: hostMemUsageAlert
expr: (node_memory_MemTotal - node_memory_MemAvailable)/node_memory_MemTotal > 0.85
for: 1m
labels:
severity: page
annotations:
summary: "Instance {{ $labels.instance }} MEM usgae high"
description: "{{ $labels.instance }} MEM usage above 85% (current value: {{ $value }})"

总结

以上就是prometheus自定义告警规则解析和配置的全部内容,如果对你有所帮助的话请点个关注,我会不定时更新技术分享,对于文章中内容有问题的地方可以在下面留言,看到我会及时回复。