CommanderData
CommanderData

Reputation: 583

Custom prometheus metric without Spring

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?

Upvotes: 2

Views: 1697

Answers (1)

CommanderData
CommanderData

Reputation: 583

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.

Upvotes: 3

Related Questions