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

如何用Python3更新Prometheus指标值且保留其余指标

如何在Prometheus Push Gateway中更新指定指标并保留其余指标?

我懂你的困扰——每次运行update.py推送更新后,Push Gateway里对应job='test'的其他指标全被清空了,只剩你修改的那一个。这是因为默认的push_to_gateway行为是完全替换整个job的指标集合,而非增量更新。

核心解决方案:用pushadd_to_gateway替代push_to_gateway

Prometheus客户端库提供了pushadd_to_gateway方法,它专门用于增量推送指标:只会更新你指定的标签对应的指标值,同时保留该job下已有的所有其他指标。

只需要修改update.py的两个地方:

  1. 导入pushadd_to_gateway而非push_to_gateway
  2. 调用pushadd_to_gateway替换原有的push_to_gateway

修改后的update.py代码如下:

from prometheus_client import CollectorRegistry, Gauge, pushadd_to_gateway
from prometheus_client.exposition import basic_auth_handler

r = 10
def my_auth_handler(url, method, timeout, headers, data):
    username = 'admin'
    password = 'secret'
    return basic_auth_handler(url, method, timeout, headers, data, username, password)

registry = CollectorRegistry()
g = Gauge('test_test', 'Random gauge', ['user_status', 'status', 'country', 'state', 'city'], registry=registry)
# 先设置初始值r=10,再减1,最终值为9
g.labels('1', 'Rejected', 'Canada', 'AB', 'Albany').set(r)
g.labels('1', 'Rejected', 'Canada', 'AB', 'Albany').dec()

# 使用pushadd_to_gateway实现增量更新
pushadd_to_gateway('localhost:9091', job='test', registry=registry, handler=my_auth_handler)

原理说明

  • push_to_gateway会把Push Gateway中对应job='test'的所有指标,替换成当前registry里的内容——所以你只推送了一个指标时,其他指标自然会被清空
  • pushadd_to_gateway则是将当前registry里的指标添加/更新到对应job中:如果标签组合已存在,就更新它的值;如果不存在,就新增该指标;原有其他标签的指标会完整保留

额外注意点

  • 对于Gauge类型指标,set()操作会直接覆盖对应标签组合的现有值,完全符合你想要的更新效果
  • 如果是Counter类型指标,pushadd_to_gateway会累加数值(这也是Counter的预期行为)
  • 确保你的Push Gateway是较新版本,旧版本可能不支持pushadd功能

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 05:32:46