Video in progress
What does a Micrometer Timer measure, and how do you add it to a method?
A Timer collects the number of calls, the total time and the maximum time in one metric, and if the histogram is enabled it also produces percentiles. You add it by hand with Timer.record() or with the @Timed annotation.
📖 Answer
By hand:
private final Timer timer;
public ReportService(MeterRegistry registry) {
this.timer = Timer.builder("report.generate")
.tag("type", "monthly")
.publishPercentileHistogram()
.register(registry);
}
public Report generate() {
return timer.record(() -> buildReport());
}
In Prometheus a single Timer gives several series:
report_generate_seconds_count: how many times it was called;report_generate_seconds_sum: the total time (the average = sum / count);report_generate_seconds_max: the longest call in the last interval;_bucket: if the histogram is enabled.
With the annotation:
@Timed(value = "report.generate", histogram = true)
public Report generate() { ... }
There is a trap here: in Spring Boot 3, @Timed works only if a TimedAspect bean exists (and spring-boot-starter-aop is needed). From Boot 3.2, management.observations.annotations.enabled=true adds it automatically, and before that you declare the bean by hand. Without the aspect, the annotation silently does nothing. Since it's an AOP proxy, calling this.generate() from within the class isn't measured either.
For HTTP endpoints you don't need to write a Timer: http.server.requests is there automatically.
Sign up to mark studied questions and save your progress.