Counter
A Counter
is a metric that only increases in value, it could also reset to 0 for example in case of a service restart.
As the name suggests it's useful to count things, for example cache hits, number of connections or even count exceptions.
Tip
If you need a metric that can go up and down in value, checkout the Gauge.
Usage
To create a Counter
import it and instantiate:
from pytheus.metrics import Counter
cache_hit_total = Counter(name='cache_hit_total', description='number of times the cache got it')
Increment the value
Now it's possible to increment the count by calling the inc()
:
it is also possible to specify by which amount to increase:
Warning
inc()
accepts only positive values as counters cannot decrease.
Count Exceptions
As counters are a good fit for counting exceptions there are some nicities included, you can count exceptions within a with
statement with count_exceptions
:
Note
the following examples assume a Counter
called counter
.
It is also possible to specify which Exceptions
to count:
with counter.count_exceptions((IndexError, ValueError)):
raise KeyError. # does not increase as it's not included in the list
Tip
count_exceptions
accepts an Exception
or a tuple of exceptions.
As a Decorator
When used as a decorator the Counter
will count exceptions, syntactic sugar to count_exceptions
:
you are still able to specify which exceptions you want to count: