Prometheus 支持在警报的注释(annotations)和标签(labels)以及服务的控制台页面中使用模板。模板能够针对本地数据库运行查询、遍历数据、使用条件、格式化数据等。Prometheus 模板语言基于 Go 模板系统。
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 和 Go 的模板语言都是强类型的,因此必须检查样本是否已返回,以避免执行错误。例如,如果抓取 或规则评估尚未运行,或者主机宕机,就可能发生这种情况。
{{ with printf "node_memory_MemTotal{job='node',instance='%s'}" .Params.instance | query }}
{{ . | first | value | humanize1024 }}B
{{ end }}如果以 console.html?instance=hostname 的方式访问,.Params.instance 将求值为主机名。
<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)}}