๐ŸŒ
client_python
prometheus.github.io โ€บ client_python โ€บ instrumenting โ€บ counter
Counter | client_python
April 9, 2026 - A Counter tracks a value that only ever goes up. Use it for things you count โ€” requests served, errors raised, bytes sent. When the process restarts, the counter resets to zero. If your value can go down, use a Gauge instead. from prometheus_client import Counter c = Counter('my_failures', ...
๐ŸŒ
ProgramCreek
programcreek.com โ€บ python โ€บ example โ€บ 105486 โ€บ prometheus_client.Counter
Python Examples of prometheus_client.Counter
def test_prometheus_counter(): @solid(required_resource_keys={'prometheus'}) def prometheus_solid(context): c = Counter( 'some_counter_seconds', 'Description of this counter', registry=context.resources.prometheus.registry, ) c.inc() c.inc(1.6) recorded = context.resources.prometheus.registry.get_sample_value( 'some_counter_seconds_total' ) assert abs(2.6 - recorded) < EPS assert execute_solid(prometheus_solid, run_config=ENV, mode_def=MODE).success
Discussions

python - Prometheus counter inside async call - Stack Overflow
I'm working with Prometheus Histograms and Counters and openAPI. What I'm looking somehow make the counter work : Creates a record with exact status and count them. When I'm getting 200, everything... More on stackoverflow.com
๐ŸŒ stackoverflow.com
May 27, 2021
prometheus - Python prometheus_client, how to get counter from the registry? - Stack Overflow
How can I obtain a Counter object from the registry? In the example below, I am currently using the private argument to achieve this. Perhaps someone knows a more elegant way to accomplish this using More on stackoverflow.com
๐ŸŒ stackoverflow.com
Prometheus: Count metric value over a period of time - Stack Overflow
I don't speak English very well, but I need some advice. I have Prometheus. How can I calculate the number of downtime for a service over a period of time? It's my function irate(ALERTS{job="blac... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - realize the meaning of prometheus metrics increase and rate of counter? - Stack Overflow
I want to get count of requests coming to my web application using prometheus, but I don't realize the numbers of the graph? In my case I used both increase(search_all_view_counter_total{instance=' More on stackoverflow.com
๐ŸŒ stackoverflow.com
January 11, 2022
๐ŸŒ
OpenObserve
openobserve.ai โ€บ home โ€บ blog โ€บ prometheus metrics count basics
Prometheus Metrics Count Basics
September 26, 2025 - Learn how Prometheus metrics counts unique label values using basic queries and methods like `count(count by (label) (metric))`.
๐ŸŒ
Chronosphere
chronosphere.io โ€บ home โ€บ an introduction to the 4 primary prometheus metrics types
An introduction to the 4 primary Prometheus metrics types
April 2, 2025 - To learn more about how to implement ... and Python. Prometheus also provides more in depth documentation. Letโ€™s look at the four Prometheus metrics types and when to use them: When tracking continually increasing counts of events youโ€™d use a Counter metric. They are most often queried using the rate() function to view how ...
๐ŸŒ
Prometheus
prometheus.io โ€บ docs โ€บ concepts โ€บ metric_types
Metric types | Prometheus
Remember, however, that these buckets are cumulative , i.e. every bucket counts all observations less than or equal to the upper boundary provided as a label. With native histograms, you can look at observations within given boundaries with the histogram_fraction() function (to calculate fractions of observations) and the trim operators (to filter for the desired band of observations).
๐ŸŒ
Tom Gregory
tomgregory.com โ€บ the-four-types-of-prometheus-metrics
The 4 Types Of Prometheus Metrics | Tom Gregory
December 2, 2019 - What if you wanted to record the ... well as count? Or maybe you want to record a value that goes up as well as down, such as queue size? Fortunately, Prometheus provides 4 different types of metrics which work in most situations, all wrapped up in a convenient client library. Currently, libraries exist for Go, Java, Python, and ...
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 67720049 โ€บ prometheus-counter-inside-async-call
python - Prometheus counter inside async call - Stack Overflow
May 27, 2021 - from prometheus_client import Histogram, Counter with HIST.labels(model_id, version_id).time(): async with client_session.post( settings.url, json=data, allow_redirects=False, ) as response: print(response.status) STATUS_COUNTER.labels(response.status).inc(1) if not response.status == 200: response.raise_for_status() return await response.json()
๐ŸŒ
Linux Hint
linuxhint.com โ€บ monitor-python-applications-prometheus
Monitoring Python Applications using Prometheus โ€“ Linux Hint
To experiment with the Counter metric, create a new Python script counter.py in your project directory and type in the following lines of codes. import http.server from prometheus_client import start_http_server from prometheus_client import Counter REQUESTS = Counter('server_requests_total', 'Total number of requests to this webserver') class ServerHandler(http.server.BaseHTTPRequestHandler): def do_GET(self): REQUESTS.inc() self.send_response(200) self.end_headers() self.wfile.write(b"Hello World!") if __name__ == "__main__": start_http_server(8000) server = http.server.HTTPServer(('', 8001), ServerHandler) print("Prometheus metrics available on port 8000 /metrics") print("HTTP server available on port 8001") server.serve_forever()
Find elsewhere
๐ŸŒ
Medium
medium.com โ€บ @e.ahmadi โ€บ monitoring-your-system-with-prometheus-and-grafana-efb328cedd4b
Monitoring your system with Prometheus and Grafana. | by Ehsan Ahmadi | Medium
August 22, 2021 - this type usually exposes the โ€œ_createdโ€ suffix to show how long it takes to run the function itโ€™s counting. for example, you can use this metric type in your python code like the blow: from prometheus_client import Counter c = Counter('my_failures', 'Description of counter') c.inc() # Increment by 1 c.inc(1.6) # Increment by given value
๐ŸŒ
Robust Perception
robustperception.io โ€บ instrumenting-python-with-prometheus
Instrumenting Python with Prometheus โ€“ Robust Perception | Prometheus Monitoring Experts
HANDLERS = {'/foo': some_function, '/bar': other_function} def route_request(request): HANDLERS[request.path](request) This is part of an online serving system, so we would like to know request rate, errors and latency: from prometheus_client import Summary, Counter HANDLERS = {'/foo': some_function, '/bar': other_function} REQUEST_DURATION = Summary('my_router_request_latency_seconds', 'Latency of request router handlers', ['path']) REQUEST_EXCEPTIONS = Counter('my_router_request_exceptions_total', 'Exceptions thrown in request router handlers', ['path']) def route_request(request): with REQUEST_DURATION.labels(request.path).time(): with REQUEST_EXCEPTIONS.labels(request.path).count_exceptions() HANDLERS[request.path](request) This creates a Summary to track the latency, and a Counter to track exceptions.
Top answer
1 of 1
1

The same problem I had

In my personal project, I have the same problem and I adopted this solution.

In CollectorRegistry, the class where you store your metrics, there's no method to get Collector object (Collector is the parent class of any metric like Counter, Gauge, Histogram, etc.).

The restricted_registry method creates a subset (a restricted registry) where you have the Metrics that have that name and labels. But "it's experimental", so be careful. It doesn't solve my (our) problem. Because if a metric has a label, you also have to specify its value, and sometimes you can't know it (for example, if you're counting how many https requests you've made):

def restricted_registry(self, names: Iterable[str]) -> "RestrictedRegistry":
    """Returns object that only collects some metrics.

    Returns an object which upon collect() will return
    only samples with the given names.

    Intended usage is:
        generate_latest(REGISTRY.restricted_registry(['a_timeseries']))

    Experimental."""
    names = set(names)
    return RestrictedRegistry(names, self)

So if you're coding a project, and not its tests, don't use it.


My solutions adopted

First solution (fast implementation)

The first is to store all your metrics inside a custom class (eg PrometheusMetrics) where you have a dictionary with all Metrics object, for example (return objects are custom for my case, if you want to use a parent class, writes Collector):

def register_new_metrics(self, metrics: list[Counter | Gauge | Histogram | Summary | Enum]):
    for metric in metrics:
        for metric_obj in metric.describe():
            # Register the new metric inside the registry
            self.get_registry().register(metric)
            # Add it to the dict
            self._metric[metric_obj.name] = metric

And you can invoke it in this way:

self.register_new_metrics([
            Counter(f'name', "documentation", ['label1','label2']),
            Histogram(f'name2', "documentation", ['label1', 'label2', 'label3'])
])

This way you can have a simple get('metric_name') method that returns a requested metric object. This solution doesn't cause any problems if you only create metrics once at the same time as you create a CollectorRegistry (e.g.).

But if you want to create metrics at runtime, don't use this solution. Because Prometheus uses a threading.Lock (doc) inside the CollectorRegistry class and uses it for a lot of operations.

Second solution (more logical than the first)

The second, in my opinion, is another more logical solution. You can create a subclass of CollectorRegistry and create your own method where you get metrics using the protected field self._names_to_collectors and lock the thread with self._lock. After that you can register your own subclass using "Custom Collectors" way (doc):

from prometheus_client import REGISTRY

REGISTRY.register(CustomRegistry())

class CustomRegistry(CollectorRegistry):
    # ...
    def get_metric(metric: str) -> Collector:
        with self._lock:
            self._names_to_collectors.get(metric)
    # ...

If anyone has a better solution, please write! I am also interested in this topic.

๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 70663115 โ€บ realize-the-meaning-of-prometheus-metrics-increase-and-rate-of-counter
python - realize the meaning of prometheus metrics increase and rate of counter? - Stack Overflow
January 11, 2022 - I want to get count of requests coming to my web application using prometheus, but I don't realize the numbers of the graph? In my case I used both increase(search_all_view_counter_total{instance='
๐ŸŒ
GitHub
github.com โ€บ prometheus โ€บ client_python โ€บ discussions โ€บ 799
Summary count and sum value ยท prometheus/client_python ยท Discussion #799
As an example, if you are creating a summary from 3 observations, say 1.0, 1.5, 1.8, then count would be 3 and sum would be 4.3.
Author: prometheus
๐ŸŒ
Medium
leapcell.medium.com โ€บ understanding-prometheus-and-monitoring-python-applications-37abf0712e2f
Understanding Prometheus and Monitoring Python Applications | by Leapcell | Medium
May 28, 2025 - It is typically used to count events such as the number of requests served, tasks completed, or errors occurred. ... from prometheus_client import Counter # Create a counter metric request_counter = Counter('http_requests_total', 'Total number ...
Top answer
1 of 2
3

I came up with two solutions to this, choose whichever suits you best. For the purpose of simplifying things, let's assume your Prometheus scrape at 15 seconds interval and the error state lasted for 1 minute. Then, the gathered data would look like this:

state_metric 0 @t
state_metric 1 @t+15s
state_metric 1 @t+30s
state_metric 1 @t+45s
state_metric 1 @t+60s
state_metric 0 @t+75s

With changes()

This shows how many state changes were there. It would return 1 for the exemplary data above and it only gives adequate results if the gauge in question can hold exactly two possible values (for example 1 and 0).

changes(state_metric[1d])/2

changes() shows how many times the metric value has changed during the interval, while division by 2 is to compensate the state change back to normal. This is the downside of this method, which makes it only usable for detecting quick changes of state. But you probably have an alert when the error state hangs for some time, so I think this shouldn't be really a problem.

With a subquery

This is more precisely what you asked:

the number of times when metrics were 1

But there is a catch: with the exemplary data above, the query below will return you 4:

sum_over_time(count(state_metric == 1)[1d:])

[1d:] means repeat that instant query (count(state_metric == 1)) for each data point during last 1d. This is precisely the number of times when state_metric was 1 and it can be useful, for example, to calculate the downtime (just multiply by the scrape interval). Unlike the first method, this can work with any number of possible states, since you can define what you need in the condition.

2 of 2
1

I need to calculate the number of times when metrics were 1 by range variable provided in Grafana.

The following query should return the number of times the time series matching aqa_device_health_checker{env="dev", device="FOO"} series selector had value 1 on the selected time range in Grafana (aka $__range):

last_over_time(
  sum_over_time(
    aqa_device_health_checker{env="dev", device="FOO"}[$__range] offset -$__range
  )[$__range:$__range]
)

The query returns individual results per each matching time series. If you need summary result over all the matching time series, then just wrap the query above into sum():

sum(
  last_over_time(
    sum_over_time(
      aqa_device_health_checker{env="dev", device="FOO"}[$__range] offset -$__range
    )[$__range:$__range]
  )
)

Note that both queries above allow calculating the number of times the metric had 1 value if the metric could have either 0 or 1 values. If the metric can have other values, then these queries won't work as expected. Unfortunately, Prometheus doesn't provide easy to use functionality for counting the number of raw samples with some pre-defined value N. If you know beforehand the interval between samples (aka scrape_interval), then the following hack based on Prometheus subquery can be used:

count_over_time(
  (
    last_over_time(m[scrape_interval]) == N
  )[$__range:scrape_interval]
)

This query counts the number of raw samples with values equal to N on the time range $__range selected in Grafana.

If the interval between samples isn't known beforehand, then it is impossible to calculate the number of samples with a particular value in Prometheus. If you still need this functionality, then take a look at count_eq_over_time() function provided by VictoriaMetrics - this is Prometheus-like monitoring solution I work on. For example, the following query returns the exact number of samples with the value 10 over the last hour for time series m:

count_eq_over_time(m[1h], 10)
๐ŸŒ
HexDocs
hexdocs.pm โ€บ prometheus_ex โ€บ Prometheus.Metric.Counter.html
Prometheus.Metric.Counter โ€” Prometheus.ex v5.1.0
Increments the counter identified by spec by value. Raises Prometheus.InvalidValueError exception if value isn't a positive number.<br> Raises Prometheus.UnknownMetricError exception if a counter for spec can't be found.<br> Raises Prometheus.InvalidMetricArityError exception if labels count mismatch.
๐ŸŒ
Better Stack
betterstack.com โ€บ community โ€บ questions โ€บ prometheus-to-count-unique-label-values
Prometheus Query to Count Unique Label Values | Better Stack Community
December 2, 2024 - To count unique label values in Prometheus, you can use the count function along with the by clause to aggregate metrics based on a specific label.
๐ŸŒ
CloudBees
cloudbees.com โ€บ blog โ€บ monitoring-your-synchronous-python-web-applications-using-prometheus
Monitoring Your Synchronous Python Web Applications Using Prometheus
June 5, 2026 - The generate_latest() function generates the latest metrics and sets the content type to indicate the Prometheus server that we are sending the metrics in text format using the 0.0.4 version. However, the real work of setting the metrics happens in our middleware module. We have introduced two major changes, the first of which is initializing objects of two metric types: Counter and Histogram.