在Prometheus监控体系中,标签 label 是一个非常重要的参数,使用标准的标签有利于我们对整个集群进行控制管理,便于我们在复杂的环境中能够精确查询metrics。

标签管理

honor_labels

在之前,我们使用pushgateway上报监控数据,在shell脚本里面我们发送数据给pushgateway时,其实标签也一并发了出去。

在element那里,有2个exported_*开头的labels,其实就是我们定义的labels。

honor_labels主要用于解决prometheus server的label与exporter端用户自定义label冲突的问题。honor_labels默认是false,当出现冲突,会将冲突的标签以exported重新命名;当honor_labels为true,只保留用户自定义的label。

- job_name: 'pushgateway'
honor_labels: true
static_configs:
- targets: ['localhost:9091','localhost:9092']

添加新标签

- job_name: 'pushgateway'
honor_labels: true
static_configs:
- targets: ['localhost:9091','localhost:9092']
labels:
area: 'nj'

prometheus支持热更新,使用 kill -hup 发送信号给prometheus进程

# 检查怕配置文件
./promtool check config prometheus.yml
# 发送hup信号
kill -hup 13070

等待一会,刷新prometheus页面,观察增加的标签

relabel_configs

relabel_configs字段支持更多的标签操作

relable_configs:
# 源标签
[ source_labels: '[' <labelname> [, ...] ']' ]

# 多个源标签时连接的分隔符
[ separator: <string> | default = ; ]

# 重新标记的标签
[ target_label: <labelname> ]

# 整则表达式匹配源标签的值
[ regex: <regex> | default = (.*) ]

# 用的少,占时略
[ modulus: <uint64> ]

# 替换正则表达式匹配的分组,分组引用 $1,$2,$3,....
[ replacement: <string> | default = $1 ]

# 基于正则表达式匹配执行的操作
[ action: <relabel_action> | default = replace ]

action支持的标签动作

replace:默认,通过regex匹配source_label的值,使用replacement来引用表达式匹配的分组
keep:删除regex与连接不匹配的目标 source_labels
drop:删除regex与连接匹配的目标 source_labels
labeldrop:删除regex匹配的标签
labelkeep:删除regex不匹配的标签
hashmod:设置target_label为modulus连接的哈希值source_labels
labelmap:匹配regex所有标签名称。然后复制匹配标签的值进行分组,replacement分组引用(${1},${2},…)替代

(1)我们将刚刚添加的 area: ‘nj’ 替换成 areas: ‘nj’

- job_name: 'pushgateway'
honor_labels: true
static_configs:
- targets: ['localhost:9091','localhost:9092']
labels:
area: 'nj'
relabel_configs:
- action: replace
source_labels: ['area']
target_label: areas
regex: (.*)
replacement: $1

更新prometheus配置

# 检查怕配置文件
./promtool check config prometheus.yml
# 发送hup信号
kill -hup 13070

刷新浏览器prometheus页面

(2)我们将 area: ‘nj’ 标签删掉

- job_name: 'pushgateway'
honor_labels: true
static_configs:
- targets: ['localhost:9091','localhost:9092']
labels:
area: 'nj'
relabel_configs:
- action: replace
source_labels: ['area']
target_label: areas
regex: (.*)
replacement: $1
- action: labeldrop
regex: area

labeldrop会将regex匹配的标签删掉;labelkeep则相反,删除regex不匹配的标签

(3)根据某个标签删除我们不想监控的数据

- job_name: 'pushgateway'
honor_labels: true
static_configs:
- targets: ['localhost:9091','localhost:9092']
labels:
area: 'nj'
relabel_configs:
- action: replace
source_labels: ['area']
target_label: areas
regex: (.*)
replacement: $1
- action: labeldrop
regex: area
- action: drop
source_labels: ['areas']
regex: (.*)

drop会删除regex与连接匹配的目标 source_labels,keep则相反。