在本教程中,我们将基于 ping_request_count
指标创建告警,该指标是在之前的 Instrumentation 用 Go 编写的 HTTP 服务器 教程中 instrumentation 的。
为了本教程的目的,当 ping_request_count
指标大于 5 时,我们将发出告警。查看真实的 最佳实践 以了解更多关于告警原则的信息。
从 此处 为您的操作系统下载最新版本的 Alertmanager。
Alertmanager 支持各种接收器,如 email
、webhook
、pagerduty
、slack
等,通过这些接收器,它可以在告警触发时发出通知。您可以在此处找到接收器列表以及如何配置它们。在本教程中,我们将使用 webhook
作为接收器,请访问 webhook.site 并复制 webhook URL,我们稍后将使用它来配置 Alertmanager。
首先,让我们设置带有 webhook 接收器的 Alertmanager。
alertmanager.yml
global:
resolve_timeout: 5m
route:
receiver: webhook_receiver
receivers:
- name: webhook_receiver
webhook_configs:
- url: '<INSERT-YOUR-WEBHOOK>'
send_resolved: false
将 <INSERT-YOUR-WEBHOOK>
替换为我们之前在 alertmanager.yml 文件中复制的 webhook,并使用以下命令运行 Alertmanager。
alertmanager --config.file=alertmanager.yml
一旦 Alertmanager 启动并运行,请导航到 http://localhost:9093,您应该能够访问它。
现在我们已经配置了带有 webhook 接收器的 Alertmanager,让我们将规则添加到 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"]
如果您注意到 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
现在让我们使用以下命令运行 Prometheus。
prometheus --config.file=./prometheus.yml
在您的浏览器中打开 http://localhost:9090/rules 以查看规则。接下来,运行 instrumented 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 可以配置其他接收器,以便在告警触发时发出通知。
本文档是开源的。请通过提交 issue 或 pull request 来帮助改进它。