Prometheus基于指标的告警

基于指标的告警

在本教程中,我们将在之前在用Go编写的HTTP服务器教程
中添加的
ping_request_count
指标上创建告警。

为了本教程的目的,当
ping_request_count
指标大于5时,我们将发出告警。查看现实世界的最佳实践以了解更多关于告警原则的信息
https://prometheus.io/docs/practices/alerting/。

从这里下载适用于您操作系统的最新版本的Alertmanager:
https://github.com/prometheus/alertmanager/releases

Alertmanager支持多种接收器,如
email

webhook

pagerduty

slack
等,当告警触发时可以通过这些接收器进行通知。您可以在这里找到接收器列表以及如何配置它们
https://prometheus.io/docs/alerting/latest/configuration/。我们将在本教程中使用
webhook
作为接收器,前往webhook.site并复制稍后用于配置Alertmanager的webhook URL
https://webhook.site/。

首先,让我们使用webhook接收器设置Alertmanager。

alertmanager.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
```
global:
  resolve_timeout: 5m
route:
  receiver: webhook_receiver
receivers:
    - name: webhook_receiver
      webhook_configs:
        - url: '<INSERT-YOUR-WEBHOOK>'
          send_resolved: false
```

```


`<INSERT-YOUR-WEBHOOK>`
替换为我们之前复制的webhook,然后在alertmanager.yml文件中运行Alertmanager,使用以下命令。

```

alertmanager --config.file=alertmanager.yml

1
2
3
4
5
6
7
8
9
10
11
  
```

一旦Alertmanager运行起来,导航到http://localhost:9093,您应该能够访问它。

现在我们已经配置了Alertmanager和webhook接收器,让我们将规则添加到Prometheus配置中。

>
prometheus.yml

```

global:
 scrape_interval: 15s
 evaluation_interval: 10s
rule_files:
  - rules.yml
alerting:
  alertmanagers:
  - static_configs:
    - targets:
       - localhost:9093
scrape_configs:
 - job_name: prometheus
   static_configs:
       - targets: [“localhost:9090”]
 - job_name: simple_server
   static_configs:
       - targets: [“localhost:8090”]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  
```

如果您注意到
`evaluation_interval`

`rule_files`

`alerting`
部分已添加到Prometheus配置中,
`evaluation_interval`
定义了规则评估的间隔,
`rule_files`
接受定义规则的yaml文件数组,
`alerting`
部分定义了Alertmanager配置。正如教程开头提到的,我们将创建一个基本规则,当
`ping_request_count`
值大于5时发出告警。

>
rules.yml

```

groups:
 - name: Count greater than 5
   rules:
   - alert: CountGreaterThan5
     expr: ping_request_count > 5
     for: 10s

1
2
3
4
5
6
  
```

现在让我们使用以下命令运行Prometheus。

```

prometheus --config.file=./prometheus.yml

  

打开浏览器中的http://localhost:9090/rules查看规则。接下来,运行已添加指标的ping服务器并访问http://localhost:8090/ping端点,至少刷新页面6次。您可以通过导航到http://localhost:8090/metrics端点来检查ping计数。要查看告警状态,请访问http://localhost:9090/alerts。一旦条件
ping_request_count > 5
持续超过10秒,
state
将变为
FIRING
。现在如果您返回到您的
webhook.site
URL,您将看到告警消息。

同样,Alertmanager可以配置其他接收器,在告警触发时进行通知。

江达小记