模板示例

Prometheus 支持在告警的注解(annotations)和标签(labels)中以及在提供的控制台页面中使用模板。模板能够对本地数据库运行查询、迭代数据、使用条件逻辑、格式化数据等。Prometheus 模板语言基于 Go 模板(templating) 系统。

简单的告警字段模板

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."

告警字段模板将在每个触发的告警的每次规则迭代中执行,因此请保持所有查询和模板的轻量级。如果告警需要更复杂的模板,建议改为链接到控制台。

简单的迭代

这会显示一个实例列表,以及它们是否处于正常状态。

{{ range query "up" }}
  {{ .Labels.instance }} {{ .Value }}
{{ end }}

特殊的 . 变量包含每次循环迭代中当前样本的值。

显示一个值

{{ with query "some_metric{instance='someinstance'}" }}
  {{ . | first | value | humanize }}
{{ end }}

Go 及其模板语言都是强类型的,因此必须检查样本是否已返回,以避免执行错误。例如,如果抓取(scrape)或规则评估尚未运行,或主机宕机,就可能发生这种情况。

包含的 prom_query_drilldown 模板处理了这一点,它允许格式化结果,并链接到表达式浏览器

使用控制台 URL 参数

{{ with printf "node_memory_MemTotal{job='node',instance='%s'}" .Params.instance | query }}
  {{ . | first | value | humanize1024 }}B
{{ end }}

如果作为 console.html?instance=hostname 访问,.Params.instance 将被评估为 hostname

高级迭代

<table>
{{ range printf "node_network_receive_bytes{job='node',instance='%s',device!='lo'}" .Params.instance | query | sortByLabel "device"}}
  <tr><th colspan=2>{{ .Labels.device }}</th></tr>
  <tr>
    <td>Received</td>
    <td>{{ with printf "rate(node_network_receive_bytes{job='node',instance='%s',device='%s'}[5m])" .Labels.instance .Labels.device | query }}{{ . | first | value | humanize }}B/s{{end}}</td>
  </tr>
  <tr>
    <td>Transmitted</td>
    <td>{{ with printf "rate(node_network_transmit_bytes{job='node',instance='%s',device='%s'}[5m])" .Labels.instance .Labels.device | query }}{{ . | first | value | humanize }}B/s{{end}}</td>
  </tr>{{ end }}
</table>

这里我们迭代所有网络设备,并显示每个设备的网络流量。

由于 range 操作未指定变量,.Params.instance 在循环内部不可用,因为 . 现在是循环变量。

定义可重用模板

Prometheus 支持定义可重用的模板。当与 控制台库 支持结合使用时,这会特别强大,允许在不同控制台之间共享模板。

{{/* Define the template */}}
{{define "myTemplate"}}
  do something
{{end}}

{{/* Use the template */}}
{{template "myTemplate"}}

模板仅限一个参数。可以使用 args 函数包装多个参数。

{{define "myMultiArgTemplate"}}
  First argument: {{.arg0}}
  Second argument: {{.arg1}}
{{end}}
{{template "myMultiArgTemplate" (args 1 2)}}

本文档是开源的。请通过提交 issue 或 pull request 帮助改进它。