You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何更简洁地白名单1000+个Prometheus指标?

Prometheus 大量指标白名单的原生优化配置方案

针对单个任务需要保留数百甚至上千个指标的场景,以下是几种Prometheus原生的优化方案,无需额外Python代码:

1. 拆分任务配置文件 + Include 指令

将每个任务的指标过滤规则单独存放在独立的配置文件中,通过主配置的include指令引入,避免主配置臃肿:

主配置示例(prometheus.yml)

scrape_configs:
  - job_name: 'task1'
    static_configs:
      - targets: ['localhost:9090']
    # 引入该任务的专属过滤配置
    include: 'configs/task1_relabels.yml'

任务专属配置示例(configs/task1_relabels.yml)

metric_relabel_configs:
  - source_labels: [__name__]
    # 正则可通过shell工具批量生成:将指标名逐行写入文本文件后,用awk拼接成正则
    # 示例shell命令:awk 'BEGIN{printf "(?i)("} {printf "%s|", $0} END{printf "\b)"}{}' task1_whitelist.txt
    regex: (?i)(metric1|metric2|...|metric1000)
    action: keep

2. 使用全局模板(Prometheus 2.26+ 支持)

通过模板功能将所有任务的指标白名单正则统一管理,主配置中直接引用模板变量,提升可维护性:

步骤1:创建模板文件(whitelists.tmpl)

{{ define "task1_whitelist" }}(?i)(metric1|metric2|...|metric1000){{ end }}
{{ define "task2_whitelist" }}(?i)(foo_metric|bar_metric|...){{ end }}

步骤2:主配置中引用模板

启动Prometheus时需启用template-include特性:prometheus --config.file=prometheus.yml --enable-feature=template-include

主配置示例:

# 引入模板文件
{{ include "whitelists.tmpl" . }}

scrape_configs:
  - job_name: 'task1'
    static_configs:
      - targets: ['localhost:9090']
    metric_relabel_configs:
      - source_labels: [__name__]
        regex: {{ template "task1_whitelist" }}
        action: keep

3. 拆分多个Keep规则(备选方案)

如果不想拼接超长正则,可以将指标按逻辑分组,拆分多个keep规则,每个规则匹配一组指标:

metric_relabel_configs:
  - source_labels: [__name__]
    regex: (?i)(metric1|metric2|metric3|metric4|metric5)
    action: keep
  - source_labels: [__name__]
    regex: (?i)(metric6|metric7|metric8|metric9|metric10)
    action: keep
  # 按逻辑分组添加更多规则

内容的提问来源于stack exchange,提问作者Unmil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 22:32:49