如何使用时间单位在 Prometheus 中创建警报?喜欢 "average response time surpasses 5 seconds in the last 2 minutes"

How to create an alert in Prometheus with time units? Like "average response time surpasses 5 seconds in the last 2 minutes"

  - name: app
    rules:
      - alert: ServerHighLatency
        expr: sum by(applicationName) (rate(http_server_requests_seconds_sum{status!~"4..|5.."}[1m]))/sum by(applicationName) (rate(http_server_requests_seconds_count{status!~"4..|5.."}[1m])) >= 5s
        for: 5s
        labels:
          severity: critical
        annotations:
          summary: "{{ $labels.applicationName }} is responding with high latency(5s+)"
          description: "*Host*: {{ $labels.node }}\n*Datacenter*: {{ $labels.datacenter }}\n*Value*: {{ humanize $value }}\n"

但是我在表达式的最后一个 s 周围遇到了解析错误,所以我猜这是不允许的。当我删除 s 时它起作用,但从未被触发。我找不到任何警报示例来检查某个范围内的平均响应时间,但只能按值进行比较,如 "some percentile > 0.8",而不是时间单位。是否有意义?

旁注:我无法使 {{ $labels.datacenter }}{{ $labels.node }} 正常工作,但 {{ $labels.applicationName }} 正常工作,为什么?我在哪里可以找到 Prometheus 中警报语法的一些很好的示例和文档?

您不需要(实际上不能)将单位添加到表达式中,只需添加数字即可。如果您的警报从未被触发,可能是表达式有问题,或者结果总是小于 5。您是否在 Prometheus 控制台中测试过该表达式?

只是关于 "labels not showing" 的旁注:

如果我们使用 Prometheus 表达式控制台(在 /graph 下),我们会看到结果中包含的所有标签,以便快速调试。

如果我sum(rate(foo([1m]))/sum(rate(bar([1m])),我会看到这个:

但是如果我使用sum by(tag1, tag2, tag3),我可以在结果中看到标签:

然后,标签的值在最后的 annotation 部分不再为空:

    rules:
      - alert: HighLatency
        expr: sum by(productName,instance,datacenter) (rate(http_server_requests_seconds_sum{status!~"4..|5.."}[1m]))/sum by(productName,instance,datacenter) (rate(http_server_requests_seconds_count{status!~"4..|5.."}[1m])) >= 5
        for: 5s
        labels:
          severity: critical
        annotations:
          summary: "{{ $labels.productName }} is responding with high latency(5s+)"
          description: "*Instance*: {{ $labels.instance }}\n*Datacenter*: {{ $labels.datacenter }}\n*Value*: {{ humanize $value }}\n"

我可以在 Slack 频道中看到它们。