It's easy, have a function to fetch Prometheus counter value


import (
    "github.com/prometheus/client_golang/prometheus"
    dto "github.com/prometheus/client_model/go"
    "github.com/prometheus/common/log"
)

func GetCounterValue(metric *prometheus.CounterVec) float64 {
    var m = &dto.Metric{}
    if err := metric.WithLabelValues("label1", "label2").Write(m); err != nil {
        log.Error(err)
        return 0
    }
    return m.Counter.GetValue()
}
Answer from Deep Nirmal on Stack Overflow
🌐
INNOQ
innoq.com › en › blog › 2019 › 05 › prometheus-counters
Prometheus Counters and how to deal with them – INNOQ
May 20, 2019 - To query our Counter, we can just enter its name into the expression input field and execute the query. We get one result with the value 0 (ignore the attributes in the curly brackets for the moment, we will get to this later).
Discussions

Is there a way to get current counter value?
prometheus / client_golang Public · Watch · Couldn't load subscription status. Retry · There was an error while loading. Please reload this page. Fork 1.2k · Star 5.8k · New issueCopy link · New issueCopy link · Closed · Closed · Is there a way to get current counter value?#412 · More on github.com
🌐 github.com
3
May 29, 2018
How to take the previous counter value and add it to the new one in case it resets to zero on Grafana?
Typically, you would use rate, which accounts for counters resets. Is there any reason not to use rate? What's the use case, just out of curiosity? More on reddit.com
🌐 r/PrometheusMonitoring
8
2
July 21, 2023
prometheus - Get Total requests in a period of time - Stack Overflow
If I have a Counter http_requests_total, How can I build a query to get an integer with the total number of requests during a period of time (for example:24hs)? ... Note that Prometheus may return fractional value from increase() function on a time series with integer values. More on stackoverflow.com
🌐 stackoverflow.com
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
🌐
client_python
prometheus.github.io › client_python › instrumenting › counter
Counter | client_python
April 9, 2026 - If your value can go down, use a Gauge instead. 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 If there is a suffix of _total on the metric name, it will be removed.
🌐
HexDocs
hexdocs.pm › prometheus_ex › Prometheus.Metric.Counter.html
Prometheus.Metric.Counter — Prometheus.ex v5.1.0
Returns the value of the counter identified by spec. If there is no counter for given labels combination, returns :undefined. ... Increments the counter identified by spec by 1 when body executed. Read more about bodies: Prometheus.Injector.
🌐
Robust Perception
robustperception.io › setting-a-prometheus-counter
Setting a Prometheus Counter – Robust Perception | Prometheus Monitoring Experts
package main import "github.com/prometheus/client_golang/prometheus" type MyCollector struct { counterDesc *prometheus.Desc } func (c *MyCollector) Describe(ch chan<- *prometheus.Desc) { ch <- c.counterDesc } func (c *MyCollector) Collect(ch chan<- prometheus.Metric) { value := 1.0 // Your code to fetch the counter value goes here.
🌐
Prometheus
prometheus.io › docs › concepts › metric_types
Metric types | Prometheus
The Prometheus server does not yet make use of the type information and flattens all types except native histograms into untyped time series of floating point values. Native histograms, however, are ingested as time series of special composite histogram samples. In the future, Prometheus might handle other metric types as composite types, too. There is also ongoing work to persist the type information of the simple float samples. A counter is a cumulative metric that represents a single monotonically increasing counter whose value can only increase or be reset to zero on restart.
🌐
GitHub
github.com › prometheus › client_golang › issues › 412
Is there a way to get current counter value? · Issue #412 · prometheus/client_golang
May 29, 2018 - prometheus / client_golang Public · Watch · Couldn't load subscription status. Retry · There was an error while loading. Please reload this page. Fork 1.2k · Star 5.8k · New issueCopy link · New issueCopy link · Closed · Closed · Is there a way to get current counter value?#412 ·
Author: prometheus
🌐
GitConnected
levelup.gitconnected.com › prometheus-counter-metrics-d6c393d86076
Working With Prometheus Counter Metrics | Level Up Coding
February 28, 2022 - Prometheus’ increase function calculates the counter increase over a specified time frame². The following PromQL expression calculates the number of job executions over the past 5 minutes. ... Since our job runs at a fixed interval of 30 seconds, our graph should show a value of around 10. ... Prometheus extrapolates increase to cover the full specified time window. Because of this, it is possible to get non-integer results despite the counter only being increased by integer increments¹.
Find elsewhere
🌐
Reddit
reddit.com › r/prometheusmonitoring › how to take the previous counter value and add it to the new one in case it resets to zero on grafana?
r/PrometheusMonitoring on Reddit: How to take the previous counter value and add it to the new one in case it resets to zero on Grafana?
July 21, 2023 -

So I have a counter metric, I aggregate it by sum based on two label values. My question is, after the application restarts the counter is going to reset to zero, but on grafana I want to keep the counter persistent, meaning that when the counter becomes zero, I want to take the previous value and add it to the new counter value.

So if counter metric is 5.0, application restarts and now the counter metric is 0, I basically want to take previous value 5 and add it to the current value 0.

Does this make sense? I don't know how to do it.

🌐
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))`.
🌐
Torsten Mandry
torstenmandry.github.io › Prometheus-Counters
Prometheus Counters and how to deal with them | Torsten Mandry
May 20, 2019 - To query our Counter, we can just enter its name into the expression input field and execute the query. We get one result with the value 0 (ignore the attributes in the curly brackets for the moment, we will get to this later).
🌐
Jupp0r
jupp0r.github.io › prometheus-cpp › classprometheus_1_1Counter.html
Prometheus Client Library for Modern C++: prometheus::Counter Class Reference
This class represents the metric type counter: https://prometheus.io/docs/concepts/metric_types/#counter · The value of the counter can only increase. Example of counters are: ... Do not use a counter to expose a value that can decrease - instead use a Gauge. The class is thread-safe. No concurrent call to any API of this type causes a data race. Get the current value of the counter.
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.

🌐
SigNoz
signoz.io › guides › how to manage prometheus counters - best practices for servers
How to Manage Prometheus Counters - Best Practices for Servers | SigNoz
July 25, 2024 - Implement periodic snapshots of counter values. ... Query the Prometheus server for the most recent counter value before the reset.
🌐
OneUptime
oneuptime.com › home › blog › how to implement prometheus counter best practices
How to Implement Prometheus Counter Best Practices
January 30, 2026 - A counter is a cumulative metric that represents a single monotonically increasing value.
🌐
InfluxData Documentation
docs.influxdata.com › flux › v0 › prometheus › metric-types › counter
Work with Prometheus counters | Flux Documentation
November 6, 2023 - Use difference() with normalized counter data to return the difference between subsequent values. ... from(bucket: "example-bucket") |> range(start: -1m) |> filter(fn: (r) => r._measurement == "prometheus" and r._field == "http_query_request_bytes") |> increase() |> difference()
🌐
Blog
asserts.ai › home › the benefits of prometheus counters
The Benefits of Prometheus Counters - Asserts
April 18, 2026 - If we reset the counter at each pull, we can only have one server scraping its value because if we have more than one, each server will only get a slice of the increments. There goes our high availability. Prometheus evolves the counter approach a little more.
🌐
Prometheus
discuss.prometheus.io › general help/support
Recovering counter value after Prometheus client crash - General Help/Support - Prometheus Monitoring System
January 6, 2022 - Hello, I have a Prometheus client that counts the number of events processed by my application. I want to be able to recover that counter after my application crash and restarts. For example: say that 500 events were counted before the crash. When my application restarts, I want to set my counter to start counting from 500 (not 0). To do so, I want to query Prometheus server for the last known value (500 in my example).