Class Counter

  • All Implemented Interfaces:
    Collector.Describable

    public class Counter
    extends SimpleCollector<Counter.Child>
    implements Collector.Describable
    Counter metric, to track counts of events or running totals.

    Example of Counters include:

    • Number of requests processed
    • Number of items that were inserted into a queue
    • Total amount of data a system has processed
    Counters can only go up (and be reset), if your use case can go down you should use a Gauge instead. Use the rate() function in Prometheus to calculate the rate of increase of a Counter. By convention, the names of Counters are suffixed by _total.

    An example Counter:

     
       class YourClass {
         static final Counter requests = Counter.build()
             .name("requests_total").help("Total requests.").register();
         static final Counter failedRequests = Counter.build()
             .name("requests_failed_total").help("Total failed requests.").register();
    
         void processRequest() {
            requests.inc();
            try {
              // Your code here.
            } catch (Exception e) {
              failedRequests.inc();
              throw e;
            }
         }
       }
     
     

    You can also use labels to track different types of metric:

     
       class YourClass {
         static final Counter requests = Counter.build()
             .name("requests_total").help("Total requests.")
             .labelNames("method").register();
    
         void processGetRequest() {
            requests.labels("get").inc();
            // Your code here.
         }
         void processPostRequest() {
            requests.labels("post").inc();
            // Your code here.
         }
       }
     
     
    These can be aggregated and processed together much more easily in the Prometheus server than individual metrics for each labelset. If there is a suffix of _total on the metric name, it will be removed. When exposing the time series for counter value, a _total suffix will be added. This is for compatibility between OpenMetrics and the Prometheus text format, as OpenMetrics requires the _total suffix.