Spring-boot micrometer timer() how does it work?

anonymous-explorer picture anonymous-explorer · Aug 21, 2018 · Viewed 13.9k times · Source

I am new to using spring-boot metrics and started with micrometer. I couldn't find good examples(the fact that its new) for performing timer Metrics in my spring-boot app. I am using spring-boot-starter-web:2.0.2.RELEASE dependency . But running spring-boot server and starting jconsole, I didn't see it showing Metrics (MBeans),so I also explicitly included below dependency:

spring-boot-starter-actuator:2.0.2.RELEASE

Also micrometer dependency : 'io.micrometer:micrometer-registry-jmx:latest' After adding actuator ,it does show Metrics folder but I do not see my timer(app.timer)attribute in the list. Am I doing something wrong? Any suggestions appreciated!

Below code snippet:

MeterRegistry registry = new CompositeMeterRegistry();
long start = System.currentTimeMillis();
Timer timer = registry.timer("app.timer", "type", "ping");
timer.record(System.currentTimeMillis() - start, TimeUnit.MILLISECONDS);

This works:

Metrics.timer("app.timer").record(()-> {

 didSomeLogic;
 long t = timeOccurred - timeScheduled;
 LOG.info("recorded timer = {}", t);
});

Answer

Dovmo picture Dovmo · Aug 21, 2018

See this part of the docs. I tweaked it to be more similar to what you want. You just have to register your Timer with the AutoConfigured MetricRegistry:

@Component
public class SampleBean {

    private final Timer timer;

    public SampleBean(MeterRegistry registry) {
        long start = System.currentTimeMillis();
        this.timer = registry.timer("app.timer", "type", "ping");
    }

    public void handleMessage(String message) {
        timer.record(System.currentTimeMillis() - start, TimeUnit.MILLISECONDS);
    }

}