2
votes

I need to provide custom metrics for a web application. The thing is that I cannot use Spring but I have to use a jax-rs endpoint instead. The requirements are very simple. Imagine you have a map with key value pairs where the key is the metric name and the value is a simple integer which is a counter. The code would be something like this:

public static Map<String, Integer> metrics = Map.of(
    "logged_in_users_today", 123
);

@GET
@Path("/metrics/{metricId}")
public Integer getMetric(@PathParam("metricId") String metricId) {
    int count = metrics.get(metricId);
    return count;
}

But now I need to use some API to publish those metrics. I looked up some tutorials but I could only find Spring based demos that are using micrometer annotations to export metrics. How can I do that in a programmatic way?

1
Not much experience with Java, but it should be simple enough to use a Java client and register metrics using it and post it to prometheus server running. sysdig.com/blog/prometheus-metrics refer this link, it has a java exampleGaurav Kumar
There is still a general question I have. Do I need to create an endpoint for each metric I am publishing or do I have just one endpoint for /metrics?Matthew Darton
You just need one endpoint /metrics, all the counters, gauges etc are posted to this endpoint and then the server does the necessary aggregations to show you the resulting values of metrics over periods of timeGaurav Kumar

1 Answers

3
votes

It is indeed rather easy. This is the code:

public static double metricValue = 123;

@GET
@Path("/metrics")
public String getMetrics() {
    Writer writer = new StringWriter();
    CollectorRegistry registry = new CollectorRegistry();
    Gauge gauge = Gauge.build().name("logged_in_users").help("Logged in users").register(registry);
    gauge.set(metricValue);
    TextFormat.write004(writer, registry.metricFamilySamples());
    return writer.toString();
}

I was always struggling with the name of the method metricFamilySamples because I thought it would just output sample data ;). But that actually does the trick.