普罗米修斯支持在警报的注释和标签中使用模板,甚至服务控制台也可以使用。模板具有对本地数据库运行查询,迭代数据,使用条件,格式化数据等功能。Prometheus模板语言基于Go模板系统。
一个简单的警报模板
alert: InstanceDownexpr: up == 0for: 5mlabels:severity: pageannotations:summary: "Instance {{$labels.instance}} down"description: "{{$labels.instance}} of job {{$labels.job}} has been down for more than 5 minutes."
在每次触发的每个规则迭代的期间,就会执行报警模板(Alert filed template)。(每次触发都去执行一遍报警模板,会非常耗费性能)因此,请保证模板的查询的轻量级。如果需要更加复杂的报警模板,建议用控制台替代。
简单迭代
这将显示示例列表以及它们是否启动:
{{ range query "up" }}{{ .Labels.instance }} {{ .Value }}{{ end }}
特殊`.`变量包含每个循环迭代的当前样本的值。
显示一个值
{{ with query "some_metric{instance='someinstance'}" }}{{ . | first | value | humanize }}{{ end }}
Go和Go的模板语言都是强类型的,因此必须检查是否返回了样本以避免执行错误。 例如,如果抓取或规则评估尚未运行,或者主机已关闭,则可能会发生这种情况。
包含的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>
在这里,我们遍历所有网络设备并显示每个网络设备的网络流量。<br />由于该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)}}
