Metrics

When running applications in production we need to send monitoring information to some services like Prometheus.

Quarkus provides JVM and other statistics out-of-box with the Metrics extension, but it’s very valuable for our application to produce its own metrics. Let’s see how we can achieve it in this chapter.

Add the Metrics extension

In a new terminal window at the root of your tutorial-app project, run:

  • Maven

  • Quarkus CLI

./mvnw quarkus:add-extension -D"extensions=quarkus-micrometer"
quarkus extension add quarkus-micrometer

You should also add the quarkus-micrometer-registry-prometheus extension :

  • Maven

  • Quarkus CLI

./mvnw quarkus:add-extension -D"extensions=quarkus-micrometer-registry-prometheus"
quarkus extension add quarkus-micrometer-registry-prometheus

Create TimeResource

Create a new TimeResource Java class in src/main/java in the com.redhat.developers package with the following contents:

package com.redhat.developers;
import java.time.Instant;
import java.util.Calendar;
import java.util.TimeZone;

import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;

import io.micrometer.core.annotation.Counted;
import io.micrometer.core.instrument.MeterRegistry;

@Path("/time")
public class TimeResource {

    private final MeterRegistry registry; (1)

    TimeResource(MeterRegistry registry) {
        this.registry = registry;
        registry.gauge("offsetFromUTC", this,
        TimeResource::offsetFromUTC);(2)
    }

    @Counted(value = "time.now") (3)
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public Instant now() {
        return Instant.now();
    }

    int offsetFromUTC() {
        return TimeZone.getDefault().getOffset(Calendar.ZONE_OFFSET)/(3600*1000);
    }
}
1 Meters in Micrometer are created from and contained in a MeterRegistry.
2 Add a gauge that returns a value computed by our application.
3 The @Counted annotation allows the Metrics extension to count the number of invocations to this method.

Invoke the endpoint multiple times

We need to send some requests to our endpoint to increment our @Counted metrics, so use the following command:

for i in {1..5}; do curl -w '\n' localhost:8080/time; done
2020-05-12T22:38:10.546500Z
2020-05-12T22:38:10.869378Z
2020-05-12T22:38:11.188782Z
2020-05-12T22:38:11.510367Z
2020-05-12T22:38:11.832583Z

Check the metrics

By default the metrics are exposed in Prometheus format. You can check the output by pointing your browser to http://localhost:8080/q/metrics. See if you can find the TimeResource counter result.

Micrometer Timed Resource
In this tutorial we consulted the results in raw format, however these metrics are meant to be consumed by a monitoring system such as Prometheus so you can produce meaningful dashboards or alerts instead of accessing the metrics endpoint directly.