Metrics - apinazo/booter GitHub Wiki
Overview
Booter implements an example of how to take customs metrics and register them in the Spring Boot Micrometer system.
Custom metrics
Taking metrics
Adding custom metrics is pretty straightforward. These are the steps:
-
Create a new counter, just with:
Metrics.conter("counter name", "tag key", "tag value"). Usually there is several values for the same tag. They are used for segmentation of data. -
Register the counter in the
MeterRegistrybean, say it's calledregistry:registry.counter("page.visitors");
Adding a counter to MeterRegistry, registers it globally and makes it available through the /actuator/metrics endpoint.
Here is a whole example of a @Service that gets the MeterRegistry bean injected at its constructor, and add some metrics.
@Slf4j
@Service
public class CustomMetricsService {
private Counter counterTag01 = Metrics.counter("page.visitors", "age", "20s");
private Counter counterTag02 = Metrics.counter("page.visitors", "age", "30s");
public CustomMetricsService(MeterRegistry registry) {
registry.counter("page.visitors");
}
@Scheduled(fixedRate = 1000*5)
private void incrementCounterTag01() {
counterTag01.increment();
log.debug("page.visitors in their 20s: {}", counterTag01.count());
}
@Scheduled(fixedRate = 1000*5)
private void incrementCounterTag02() {
counterTag02.increment();
counterTag02.increment();
counterTag02.increment();
log.debug("page.visitors in their 30s: {}", counterTag02.count());
}
}
Showing metrics
In this example, metrics will available at this endpoints.
All metrics for the counter:
http://localhost:8000/actuator/metrics/page.visitors
Metrics for a given tag and value:
http://localhost:8000/actuator/metrics/page.visitors?tag=age:30s
What is this useful for
Custom metrics are very interesting for:
- Audit purposes.
- Count number of executions of a business logic.
- Expose counters based on data persisted in a BBDD or a logs system.