Using metric tags with MicroProfile Metrics 2.0
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:
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 | @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:
1 2 3 4 5 6 | 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:
01 02 03 04 05 06 07 08 09 10 11 12 13 | 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:
1 2 3 4 5 6 | 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. 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:
Success! Now check your email to confirm your subscription.
All opinions are my own and do not reflect those of my employer or colleagues.
Published on Java Code Geeks with permission by Sebastian Daschner, partner at our JCG program. See the original article here: Using metric tags with MicroProfile Metrics 2.0 Opinions expressed by Java Code Geeks contributors are their own. |