如何更新计数器:在每次请求后设置新值,而不是将新值增加到以前的值?

How update counter: set new value after avery request, NOT increment new value to previous value?

想通过 python

创建 Prometheus 客户端

Tried to use this module

接受此代码

from prometheus_client import Counter
c = Counter('my_requests_total', 'HTTP Failures', ['method', 'endpoint'])
c.labels(method='get', endpoint='/').inc()
c.labels(method='post', endpoint='/submit').inc()

很好,但我想在每次请求后设置新值,而不是将新值增加到以前的值。

怎样才能做到?

您必须使用量规而不是计数器。

自述文件中的示例:

from prometheus_client import Gauge
g = Gauge('my_inprogress_requests', 'Description of gauge')
g.inc()      # Increment by 1
g.dec(10)    # Decrement by given value
g.set(4.2)   # Set to a given value

另请参阅 Prometheus 指标类型:https://prometheus.io/docs/concepts/metric_types/

Counter

A counter is a cumulative metric that represents a single numerical value that only ever goes up. A counter is typically used to count requests served, tasks completed, errors occurred, etc. Counters should not be used to expose current counts of items whose number can also go down, e.g. the number of currently running goroutines. Use gauges for this use case.

Gauge

A gauge is a metric that represents a single numerical value that can arbitrarily go up and down.

Gauges are typically used for measured values like temperatures or current memory usage, but also "counts" that can go up and down, like the number of running goroutines.

可以通过访问私有 _value 属性 来设置计数器值。 我强烈建议避免使用此解决方案,除非您确定要设置的值只会增加而不会减少。否则使用 Gauge 代替。

from prometheus_client import Counter
c = Counter("foo", "bar")
c._value.set(50)
c._value.get()
50
c._value.set(101)
c._value.get()
101

# the same with labels
cd = Counter("bar", "foo", labelnames=['name'])
cd.labels(name="spam")._value.set(20)

这种方法有什么问题

主要问题是计数器重置。每当 PromQL 功能(例如 rate()increase())检测到计数器减少时,它被视为重置。考虑这个简单的例子:

my_metric            1 2 3 4 3
increase(my_metric)  0 1 1 1 3

因此,如果您减少计数器值,某些函数会将其视为计数器变为 0,然后立即上升到现在的任何值。这将破坏该计数器上的所有计算,特别是如果它很大(例如发送的字节数、处理的请求等)。