Prometheus 可以使用$value变量将当前告警规则表达式的数值输出到告警信息里。但是有些浮点数值位数相当长,非常不便于阅读,对于强迫症患者来说更是不可接受的。
如何让告警数值变得“人类可读”呢?
有如下告警规则,对网卡流量进行监控,流量超过200MB/s且持续1分钟以上则发送告警:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| - name: network_receive.rules rules: - alert: 网卡接收流量异常 expr: irate(node_network_receive_bytes_total{device!~"lo|qb.*|qv.*|tap.*"}[5m])/1024/1024 > 200 for: 1m labels: severity: warning annotations: summary: "{{$labels.instance}} {{$labels.device}} 网卡接收流量异常" description: "{{$labels.instance}} {{$labels.device}} 流量 {{$value}}MB/s"
- name: network_transmit.rules rules: - alert: 网卡流出流量异常 expr: irate(node_network_transmit_bytes_total{device!~"lo|qb.*|qv.*|tap.*"}[5m])/1024/1024 > 200 for: 1m labels: severity: warning annotations: summary: "{{$labels.instance}} {{$labels.device}} 网卡流出流量异常" description: "{{$labels.instance}} {{$labels.device}} 流量 {{$value}}MB/s"
|
这是微信通知告警模板:
1 2 3 4 5
| {{ define "wechat.html" }}{{ range $i, $alert := .Alerts.Firing }} [报警名称]: {{ index $alert.Labels "alertname" }} [报警明细]: {{ $alert.Annotations.description }} [开始时间]: {{ $alert.StartsAt.Format "2006-01-02 15:03:05" }} {{ end }}{{ end }}
|
当流量超过200MB/s时,触发了告警通知。
微信收到的告警通知信息,可以看到流量数值的小数点后长达10几位:
1 2 3
| [报警名称]: 网卡接收流量异常 [报警明细]: nova26 bond0 流量 204.05376281738282MB/s [开始时间]: 2019-09-11 09:09:19
|
格式化下告警规则中的$value变量,有三种格式化数值的方法:
1 2 3 4 5
| {{ printf "%.2f" $value }} 或 {{ $value | printf "%.2f" }} 或 {{ humanize $value }}
|
调整后收到的告警通知信息:
1 2 3
| [报警名称]: 网卡接收流量异常 [报警明细]: nova26 bond0 流量 201.6MB/s [开始时间]: 2019-09-12 09:09:34
|
^-^