5
votes

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);
});
3

3 Answers

7
votes

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);
    }

}
3
votes

This could be. If you are using Spring Boot 2, just call Timer wherever you want, no need to use a constructor.

public void methodName(){
    //start
    Stopwatch stopwatch = Stopwatch.createStarted();// Google Guava
    
    // your job here
         
    // check time
    Metrics.timer("metric-name",
            "tag1", this.getClass().getSimpleName(), //class
            "tag2", new Exception().getStackTrace()[0].getMethodName()) // method 
            .record(stopwatch.stop().elapsed());
}
1
votes

Another way to output the timer information with Spring Boot Micrometer, is to add the annotation io.micrometer.core.annotation.Timed to the method whose execution to track, and add in the ApplicationContext class, or in any class that has the @Configuration annotation, the following method:

@Bean
public TimedAspect timedAspect(MeterRegistry registry) {
    return new TimedAspect(registry);
}

After that, a working example would be:

@PostMapping(value = "/save", produces = "application/json")
@Timed(description = "Time spent saving results")
public ResponseEntity<Integer> saveResults(@CookieValue(name = "JSESSIONID") String sessionId) {
    return new ResponseEntity<>(importer.saveResults(sessionId), HttpStatus.OK);
}

See also this answer: https://stackoverflow.com/a/49193908/5538923 .