1. Overview
In this article, we’ll explore Micrometer metrics with a focus on tagging. We’ll use Micrometer in a Spring Boot application and apply various patterns to create simple metrics, such as counters and timers.
We’ll start by using Micrometer’s Builder API to create meters with variable tag values. Additionally, we’ll look at MeterProviders as an alternative that allows us to avoid potential performance issues. We’ll also use Spring AOP and Micrometer-specific annotations to record method invocations in a declarative manner.
Finally, we’ll cover best practices for naming conventions and selecting tag values, as well as common pitfalls to avoid.
2. Using the Builder API
We’ll use a simple Spring Boot service with a public function called foo() that takes the client device type as a String. For the code samples in this article, we’ll attempt to count and time each call to foo(), and tag the metrics with the device type passed as a parameter:
@Service
class DummyService {
// logger, constructor
public String foo(String deviceType) {
log.info("foo({})", deviceType);
String response = invokeSomeLogic();
return response;
}
private void invokeSomeLogic() { /* ... */ }
}
Firstly, let’s add the Spring Boot Actuator dependency to our pom.xml, which will include the Micrometer dependencies:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
A simple approach is to use the Micrometer fluent API to create different types of meters. When foo() is called, we create a Counter.builder with a meter name, then add the tag as a key-value pair.
Micrometer uses a MeterRegistry to manage and store all the meters we create. So we need to inject it into our service and use it in the final step of the builder chain – by calling register(). This actually builds and registers the meter.
Finally, we simply call the increment() method on the created Counter instance:
@Component
class DummyService {
private final MeterRegistry meterRegistry;
// logger, constructor
public String foo(String deviceType) {
log.info("foo({})", deviceType);
Counter.builder("foo.count")
.tag("device.type", deviceType)
.register(meterRegistry)
.increment();
String response = Timer.builder("foo.time")
.tag("device.type", deviceType)
.register(meterRegistry)
.record(this::invokeSomeLogic);
return response;
}
private void invokeSomeLogic() { /* ... */ }
}
As we can see, registering a Timer is very similar to registering a Counter. The main difference is that instead of using increment() like a Counter, a Timer uses methods like record(). In our case, we use record() to pass in a function to execute. The Timer will wrap the function call, measure how long it takes, record the timing, and return the function’s result.
It’s important to know that a meter is uniquely identified by its name and its set of tags. For example, even if we use the builder pattern to create multiple Counters named “foo.count” with the same tag “device.type” set to “mobile“, they will actually refer to the same underlying metric. So, incrementing either one will update the same counter.
On the other hand, this approach has the downside of creating builder objects every time foo() is called. Depending on how often the method is invoked, this can increase garbage collection overhead and impact performance over time.
3. Exposing the Metrics
Now that we are monitoring the invocations of the foo() method, we can expose these metrics through Spring Boot Actuator. To do this, we update the management.endpoints.web.exposure.include property in the configuration and set it to metrics, or use ‘*’ to expose all endpoints:
management:
endpoints.web.exposure.include: '*'
As a result, we can now view the metrics for foo() at /actuator/metrics/foo.count and /actuator/metrics/foo.time. For example, this is what is exposed for foo.time:
{
"name": "foo.time",
"baseUnit": "seconds",
"measurements": [
{
"statistic": "COUNT",
"value": 100
},
{
"statistic": "TOTAL_TIME",
"value": 5.5068953
},
{
"statistic": "MAX",
"value": 0
}
],
"availableTags": [
{
"tag": "device.type",
"values": [ "mobile", "tablet", "smart_tv", "wearable", "desktop" ]
}
]
}
As we can see, each metric also shows the list of available tags. We can use any of these tags to narrow the metric’s scope. For example, to inspect invocations for the desktop device type, we can use the endpoint /actuator/metrics/foo.time?tag=device.type:desktop.
4. Using Meter Providers
As discussed, using Micrometer’s Builder API has the drawback of creating builder objects on every function call. We can avoid this by leveraging the MeterProvider API. A MeterProvider follows a variation of the template design pattern, allowing us to reuse meters and reduce garbage collection overhead.
In the constructor, we’ll still use Counter.builder(), but instead of calling register(), we use the withRegistry(meterRegistry) variation. This returns a MeterProvider<Counter>, which we can store as a field in our service and reuse whenever needed.
The same approach works for other meter types like Timers, with the API returning a MeterProvider<Timer>:
@Service
class DummyService {
private final MeterRegistry meterRegistry;
private final Meter.MeterProvider<Counter> counterProvider;
private final Meter.MeterProvider<Timer> timerProvider;
// logger
public DummyService(MeterRegistry meterRegistry) {
this.meterRegistry = meterRegistry;
this.counterProvider = Counter.builder("bar.count")
.withRegistry(meterRegistry);
this.timerProvider = Timer.builder("bar.time")
.withRegistry(meterRegistry);
}
// ...
}
Now, we can use the counterProvider and meterProvider fields to record metrics while intercepting calls to a new method, which we’ll call bar():
public String bar(String device) {
log.info("bar({})", device);
counterProvider.withTag("device.type", device)
.increment();
String response = timerProvider.withTag("device.type", device)
.record(this::invokeSomeLogic);
return response;
}
As we can see, we can use a MeterProvider to add tags dynamically and then call the meter-specific methods, such as increment() for a Counter or record() for a Timer.
5. Using AOP
In addition to the Builder and MeterProvider APIs, we can also define meters declaratively using Aspect-Oriented Programming (AOP).
Our component is a Spring-managed bean annotated with @Service; therefore, we can use Spring’s AOP support to automatically record metrics for method invocations and avoid managing the meters manually. To do this, we only annotate the method we want to observe with the appropriate Micrometer annotations.
For example, we can create a new method, buzz(), and annotate it with Micrometer’s @Counted and @Timed:
@Timed("buzz.time")
@Counted("buzz.time")
public String buzz(String device) {
log.info("buzz({})", device);
return invokeSomeLogic();
}
By doing this, we’ll automatically record the method’s invocations and expose the metrics through Actuator. However, since this relies on AOP, it’s important that calls to buzz() go through the Spring proxy; direct internal calls within the same class won’t be intercepted.
The dynamic tagging is supported for the @Timed and @Counted annotations, but it needs additional configuration. First, we need to enable the annotations observation from our config:
management:
observations.annotations.enabled: true
# ...
Additionally, we need to define a MeterTagAnnotationHandler bean to help the meter evaluate annotated parameters. While it can be configured to parse SpEL expressions, we’ll keep it simple and have it always return the annotated object’s toString() method:
@Bean
MeterTagAnnotationHandler meterTagAnnotationHandler() {
return new MeterTagAnnotationHandler(
aClass -> Object::toString,
aClass -> (exp, param) -> pram.toString()
);
}
Lastly, we’ll annotate the parameter of the buzz() method with @MeterTag.Â
@Timed(value = "buzz.time")
@Counted(value = "buzz.count")
public String buzz(@MeterTag("device.type") String device) {
log.info("buzz({})", device);
return invokeSomeLogic();
}
As a result, the Timer that intercepts calls to buzz() will dynamically attach the “device.type” tag.
On the other hand, if we want to configure @Counted to work in the same way, we’ll need to register the CountedAspect bean and manually set a CountedMeterTagAnnotationHandler implementation:
@Bean
public CountedAspect countedAspect() {
CountedAspect aspect = new CountedAspect();
CountedMeterTagAnnotationHandler tagAnnotationHandler = new CountedMeterTagAnnotationHandler(
aClass -> Object::toString,
aClass -> (exp, param) -> "");
aspect.setMeterTagAnnotationHandler(tagAnnotationHandler);
return aspect;
}
6. Best Practices and Conventions
Micrometer encourages descriptive, lowercase names separated by dots for metrics and tags – such as “foo.time” and “device.type”. The metric name should provide meaningful context on its own, while tags add additional dimensions for filtering or grouping.Â
We should avoid overly generic tags like “service” that aggregate unrelated metrics. Generic names can make it difficult to understand what the metric represents and reduce the usefulness of the collected data.
We should be cautious with dynamic tag values. Highly variable values can create many unique metric combinations, increasing cardinality and putting pressure on the monitoring system. In our demo, using “device.type” is safe because it has a limited set of values, keeping cardinality low.
7. Conclusion
In this tutorial, we explored different ways to create Micrometer metrics with variable tag values. We started by learning that a metric is uniquely identified by its name and tags, and manually created Counter and Timer meters using the Builder API.
Next, we saw that this approach can lead to creating builder instances on each method call, which can put pressure on the garbage collector. To address this, we explored using a MeterProvider to reuse meters and reduce overhead.
Finally, we leveraged Spring AOP and Micrometer-specific annotations like @Timed and @Counted to record method invocations declaratively. We also discussed best practices for using dynamic tags and following consistent naming conventions.
The code backing this article is available on GitHub. Once you're
logged in as a Baeldung Pro Member, start learning and coding on the project.