





















标签重写(Relabeling)是Prometheus一个非常有用的功能,它可以在任务拉取(scraping)阶段前,修改target和它的labels。
该功能在日常的监控中常常会使用到,值得我们好好了解。
默认情况下,Prometheus加载targets后,都会包含一些默认的标签,其中以__作为前置的标签是在系统内部使用的,因此这些标签不会写入到样本数据中。

如:
上面这些标签将会告诉Prometheus如何从该目标实例中获取监控数据,而通过标签重写功能,我们可以对这些标签进行重写,从而实现对Target目标的控制。
标签重写的配置参数为relabel_config,其完整的配置格式如下 :
#源标签,需要在现有标签中已存在
[ source_labels: '[' <labelname> [, ...] ']' ]
# 多个源标签的分隔符;
[ separator: <string> | default = ; ]
# 要替换的目标标签;
[ target_label: <labelname> ]
# 正则表达式,用于匹配源标签的值
[ regex: <regex> | default = (.*) ]
# 源标签值取hash的模块;
[ modulus: <uint64> ]
# 当正则表达式匹配时,用于替换的值,$1代替正则匹配到的值;
[ replacement: <string> | default = $1 ]
# 基于正则匹配的动作
[ action: <relabel_action> | default = replace ]其中,相关的action类型有如下几种:
注意:重定义标签并应用后,__开头的标签会被删除; 要临时存储值用于下一阶段的处理,使用__tmp开头的标签名,这种标签不会被Prometheus使用;
在开始测试前,我们先配置一个测试Job,该Job包含两个实例,实例分别包含了两个标签,__machine_hostname和__machine_idc__。
yaml
scrape_configs:
- job_name: 'myjob'
static_configs:
- targets:
- '10.12.61.1:9100'
labels:
__machine_hostname__: 'node-01'
__machine_idc__: 'idc-01'
- targets:
- '10.12.61.2:9100'
labels:
__machine_hostname__: 'node-02'
__machine_idc__: 'idc-02'将__machine_hostname__的值替换到新标签hostname
yaml
scrape_configs:
- job_name: 'myjob'
static_configs:
- targets:
- '10.12.61.1:9100'
labels:
__machine_hostname__: 'node-01'
__machine_idc__: 'idc-01'
- targets:
- '10.12.61.2:9100'
labels:
__machine_hostname__: 'node-02'
__machine_idc__: 'idc-02'
relabel_configs:
- source_labels: [__machine_hostname__]
regex: "(.*)"
target_label: "hostname"
action: replace
replacement: '$1'重启Prometheus后,查看target信息如下:

排除标签值不匹配正则的targets 目标,此处正则匹配__machine_hostname__: 'node-01' 。
yaml
scrape_configs:
- job_name: 'myjob'
static_configs:
- targets:
- '10.12.61.1:9100'
labels:
__machine_hostname__: 'node-01'
__machine_idc__: 'idc-01'
- targets:
- '10.12.61.2:9100'
labels:
__machine_hostname__: 'node-02'
__machine_idc__: 'idc-02'
relabel_configs:
- source_labels: [__machine_hostname__]
regex: "(.*)-01"
target_label: "hostname"
action: keep
replacement: '$1'重启后,会发现只有一个__machine_hostname__: 'node-01'的实例了
如果将上面配置的action改为drop,则结果相反,将删除正则匹配到标签的实例。
重写新的标签hostname和idc,使用原有__machine_hostname__和__machine_idc__标签的值。
yaml
scrape_configs:
- job_name: 'myjob'
static_configs:
- targets:
- '10.12.61.1:9100'
labels:
__machine_hostname__: 'node-01'
__machine_idc__: 'idc-01'
- targets:
- '10.12.61.2:9100'
labels:
__machine_hostname__: 'node-02'
__machine_idc__: 'idc-02'
relabel_configs:
- action: labelmap
regex: __machine_(.+)__查看target信息,可看到重写的新标签。
两个实例的标签
hostname="node-01",idc="idc-01",instance="10.12.61.1:9100",job="myjob"
hostname="node-02",idc="idc-02",instance="10.12.61.2:9100",job="myjob"此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。