Prometheus标签重写与抓取配置全解析
立即解锁
发布时间: 2025-08-26 01:50:01 阅读量: 1 订阅数: 3 


Prometheus实战:监控系统部署与使用
### Prometheus 标签重写与数据采集全解析
#### 一、目标标签相关要点
1. **目标标签的唯一性与影响**
- 两个目标可能有相同的目标标签,但其他设置不同,不过应避免这种情况,因为像 `up` 这样的指标可能会冲突。
2. **正则表达式匹配规则**
| 正则表达式 | 含义 |
| --- | --- |
| `[0-9]` | 任意单个数字,0 - 9 |
| `\d` | 任意单个数字,0 - 9 |
| `\d*` | 任意数量的数字 |
| `[^0-9]` | 非数字的单个字符 |
| `ab` | 字符 `a` 后面跟着字符 `b` |
| `a(b|c*)` | 一个 `a` 后面跟着单个 `b` 或任意数量的 `c` 字符 |
- 括号可创建捕获组,例如模式 `(.)(\d+)` 匹配文本 `a123` 时,第一个捕获组包含 `a`,第二个包含 `123`,捕获组可用于提取字符串部分以便后续使用。
3. **目标标签的定义与作用**
- 目标标签是添加到每次抓取返回的时间序列标签中的标签,是目标的标识,通常不应随时间变化,如版本号或机器所有者。
- 目标标签改变会导致抓取的时间序列标识改变,可能造成图表不连续,影响规则和警报。
4. **优质目标标签的选择**
- 常见的目标标签有 `job` 和 `instance`。
- 还可添加应用范围的标签,如开发或生产环境、区域、数据中心、管理团队等。
- 应用内部结构的标签也有意义,如分片情况。
5. **目标标签的成本与层级结构**
- 添加标签资源成本低,但编写 PromQL 时会增加复杂度。例如添加唯一的 `host` 标签可能违反 `instance` 唯一性期望,破坏聚合操作。
- 目标标签应形成层级结构,如区域 - 数据中心 - 环境 - 服务 - 作业 - 实例,但并非严格规则。
6. **特殊标签处理方式**
- 应用已知但不适合作为目标标签的标签,如版本号,可通过信息指标暴露。
- 若希望所有目标共享某些标签,如区域,可使用外部标签。
#### 二、重写操作之 replace 动作
1. **基本原理**
- `replace` 动作可复制标签并应用正则表达式。
2. **具体示例**
- **团队名称替换**:将 `team="monitoring"` 替换为 `team="monitor"`。
```yaml
scrape_configs:
- job_name: file
file_sd_configs:
- files:
- '*.json'
relabel_configs:
- source_labels: [team]
regex: monitoring
replacement: monitor
target_label: team
action: replace
```
- **去除团队名称后缀**:去除团队名称末尾的 “ing”。
```yaml
scrape_configs:
- job_name: file
file_sd_configs:
- files:
- '*.json'
relabel_configs:
- source_labels: [team]
regex: '(.*)ing'
replacement: '${1}'
target_label: team
action: replace
```
- **移除团队标签**:移除 `team` 标签。
```yaml
scrape_configs:
- job_name: file
file_sd_configs:
- files:
- '*.json'
relabel_configs:
- source_labels: []
regex: '(.*)'
replacement: '${1}'
target_label: team
action: replace
```
- **使用 Consul IP 和端口 9100**:将 Consul 地址与端口 9100 组合。
```yaml
scrape_configs:
- job_name: node
consul_sd_configs:
- server: 'localhost:8500'
relabel_configs:
- source_labels: [__meta_consul_address]
regex: '(.*)'
replacement: '${1}:9100'
target_label: __address__
```
- 若重写产生相同目标,会自动去重。
#### 三、`job`、`instance` 和 `__address__` 标签
1. **`instance` 标签来源**
- 若目标无 `instance` 标签,默认使用 `__address__` 标签的值。
2. **`job` 和 `instance` 标签作用**
- `job` 标签默认来自 `job_name` 配置选项,指示一组具有相同目的的实例。
- `instance` 标签标识作业中的一个实例。
3. **`__address__` 标签用途**
- 是 Prometheus 抓取时连接的主机和端口,可与 `instance` 标签值不同。例如使用 Consul 节点名作为 `instance` 标签,地址指向 IP 地址。
```yaml
scrape_configs:
- job_name: consul
consul_sd_configs:
- server: 'localhost:8500'
relabel_configs:
- source_labels: [__meta_consul_address]
regex: '(.*)'
replacement: '${1}:9100'
target_label: __address__
- source_labels: [__meta_consul_node]
regex: '(.*)'
replacement: '${1}:9100'
target_label: instance
```
- Prometheus 会对 `__address__` 进行 DNS 解析,使用 `host:port` 可使 `instance` 标签更易读。
#### 四、labelmap 动作
1. **动作特点**
- `labelmap` 动作作用于标签名而非标签值。
2. **应用场景**
- 当服务发现机制有键值标签,想将部分用作目标标签时,
0
0
复制全文
相关推荐







