How to add labels to Prometheus Summary metric in Java
Asked Answered
P

3

10

Counters and Gauges allow for labels to be added to them. When I try to add labels to a Summary, I get an "incorrect number of labels" error.

This is what I'm trying:

private static final Summary latencySummary = Summary.build()
            .name("all_latencies")
            .help("all latencies.")
            .register();

latencySummary.labels("xyz_api_latency").observe(timer.elapsedSeconds());

I've looked at the Summary github source code, but can't find the answer. How are labels added to a Summary?

Pilkington answered 16/1, 2018 at 17:54 Comment(0)
G
8

You need to provide the labelname in the metric:

private static final Summary latencySummary = Summary.build()
    .name("latency_seconds")
    .help("All latencies.")
    .labelNames("api")
    .register();
Gumm answered 16/1, 2018 at 19:8 Comment(3)
how can I add more than one label? @GummQueeniequeenly
Try .labelNames("label1","label2")Tommietommy
I did as suggested. When I check the data I get a trailing comma in my metric. Like this: sample_counter{method="POST",status="520",} 1.0 Not sure where I am getting that additional comma from.Sitarski
Z
5

So following is an other example where we can see how to define the labels and the set the actual values:

Gauge mem_usage = Gauge.build().name("mem_usage").help("Memory usage").labelNames("label1", "label2").register();
mem_usage.labels("label1_value1", "label2_value2").set(1000);
Zetta answered 11/9, 2020 at 13:32 Comment(0)
C
1

Histogram and labels working example:-

import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.Histogram;
import org.springframework.stereotype.Service;

@Service
public class HistogramService {

    private final Histogram requestDuration;

    private HistogramService(CollectorRegistry collectorRegistry){
        requestDuration = Histogram.build()
                .name("http_request_latency")
                .help("http request latency.")
                .labelNames("label1", "label2")
                .buckets(.005, .01, .025, .05, .075, .1, .25, .5, .75, 1, 2, 3, 4, 5, 10)
                .register(collectorRegistry);
    }

    public void histogramMetrics() {

        Histogram.Timer requestTimer = requestDuration.labels("label1Value", "label2Value").startTimer();
        try {
           long sleepDuration  = Double.valueOf(Math.floor(Math.random() * 5 * 1000)).longValue();
            Thread.sleep(sleepDuration);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        requestTimer.observeDuration();
    }
}
Catamenia answered 16/2, 2023 at 11:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.