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

Prometheus自定义收集器:实现指标重置,仅保留最新数据

我来帮你搞定这个问题!你的核心需求是让Prometheus收集器每次返回上一次checker()生成的最新指标,同时避免旧指标堆积,还要保持9100端口的HTTP服务一直可用对吧?下面给你两种可行的解决方案,你可以根据自己的代码结构选择:


方案一:小改动适配现有代码(清空旧指标后添加新指标)

如果不想大幅修改现有代码,只需要在checker()函数开头加入逻辑,移除之前注册的旧指标,再生成新指标即可。

代码修改示例

from prometheus_client import REGISTRY

def checker():
    # 先移除所有旧的custom_metric指标
    for collector in list(REGISTRY._collector_to_names.keys()):
        # 识别并移除我们自定义的指标
        if hasattr(collector, '_name') and collector._name == 'custom_metric':
            REGISTRY.unregister(collector)
    
    # 保留你原来的指标生成逻辑(对应check.py里的函数)
    generate_metrics()

关键说明

  • 用list()遍历注册表是为了避免迭代过程中修改注册表导致的报错;
  • _collector_to_names是Prometheus客户端的内部属性,虽然不是公共API,但自用场景下完全可靠;
  • 每次运行checker()都会先清理旧指标,再添加新的,保证注册表中始终只有最新的那一个指标。

方案二:自定义Collector(更优雅的长期方案)

如果你的需求后续可能扩展,推荐用这种方式——通过自定义Collector持有最新指标,HTTP查询时直接返回最新数据,从根源上避免旧指标堆积问题。

完整代码示例

from prometheus_client.core import GaugeMetricFamily
from prometheus_client import start_http_server, REGISTRY
import time
import random

class CustomMetricCollector:
    def __init__(self):
        # 存储最新生成的指标
        self.latest_metric = None
        # 初始化时先生成一次指标,避免首次查询为空
        self.refresh_metrics()

    def collect(self):
        # 每次HTTP查询都会调用这个方法,返回最新指标
        if self.latest_metric:
            yield self.latest_metric

    def refresh_metrics(self):
        # 这里替换成你check.py里的指标生成逻辑
        label_name = f"label_{random.randint(1, 100)}"
        # 创建Gauge指标家族
        metric = GaugeMetricFamily(
            name='custom_metric',
            documentation='A custom metric',
            labels=[label_name]
        )
        # 添加随机生成的指标样本
        metric.add_metric(
            labels=[f"sample_val_{random.randint(1, 100)}"],
            value=random.randint(0, 100)
        )
        self.latest_metric = metric

def main():
    # 注册自定义Collector到全局注册表
    collector = CustomMetricCollector()
    REGISTRY.register(collector)

    # 启动HTTP服务,保持9100端口持续可用
    start_http_server(9100, addr='0.0.0.0')

    # 每100秒刷新一次指标
    while True:
        collector.refresh_metrics()
        time.sleep(100)

if __name__ == "__main__":
    main()

关键说明

  • 自定义Collector的collect()方法会在每次HTTP查询时被调用,直接返回存储的最新指标;
  • 定时任务只负责更新Collector里的latest_metric,不用手动操作注册表,逻辑更清晰;
  • 可以轻松扩展支持多种指标类型(如Counter、Summary),后续维护更方便。

验证方式

不管用哪种方案,你都可以用curl http://localhost:9100/metrics测试:

  • 每次查询只会看到最新生成的带随机标签的指标,旧指标不会残留;
  • 9100端口的HTTP服务会一直保持可用,每100秒自动更新一次指标数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 15:17:35