sebastiandaschner blog


Using metric tags with MicroProfile Metrics 2.0

#microprofile saturday, july 20, 2019

Business-related metrics that are emitted from our application might contain parameters (i.e. tags or labels) for which a specific metric is being measured. Since MicroProfile Metrics 2.0 it’s possible to assign tags to specific metrics using the API.

 

Declarative approach

Assuming we have the following resource:

@Path("greetings")
public class GreetingsResource {

    @GET
    @Path("hello")
    @Counted(name = "greetings", tags = "greeting=formal")
    public String hello() {
        return "Здравствуйте";
    }

    @GET
    @Path("hi")
    @Counted(name = "greetings", tags = "greeting=casual")
    public String hi() {
        return "Привет";
    }
}

Depending on which resource will be accessed, we’ll increment the counter that is identified by the name greetings and one of the tags greeting=formal or greeting=casual:

When we access the MicroProfile Metrics endpoint, we’ll see our metrics' values:

curl http://localhost:9080/metrics/
[...]
# TYPE application_com_example_GreetingsResource_greetings_total counter
application_com_example_GreetingsResource_greetings_total{greeting="formal"} 2
# TYPE application_com_example_GreetingsResource_greetings_total counter
application_com_example_GreetingsResource_greetings_total{greeting="casual"} 5

 

Programmatic approach

It’s also possible to dynamically create and retrieve metrics depending on the values of their tags.

For business logic that creates cars, we can dynamically create or retrieve a counter as follows:

public class CarManufacturer {

    @Inject
    MetricRegistry metricRegistry;

    public void createCar(CarColor color) {
        Counter counter = metricRegistry.counter("cars_produced",
                new Tag("color", color.name()));
        counter.inc();

        // ...
    }
}

Resulting in similar, tagged metrics:

curl http://localhost:9080/metrics/
[...]
# TYPE application_cars_produced_total counter
application_cars_produced_total{color="blue"} 1
# TYPE application_cars_produced_total counter
application_cars_produced_total{color="red"} 3

You can already try out this and other MicroProfile 3.0 features on Open Liberty version 19.0.0.7.

 

This change in the Metrics API makes using other, third-party libraries obsolete. In my book Architecting Modern Java EE Applications, I’m describing how to use the Prometheus Java API using tags or labels. This usage can now be replaced with MicroProfile Metrics 2.0.

 

Found the post useful? Subscribe to my newsletter for more free content, tips and tricks on IT & Java: