How to measure service methods using spring boot 2 and micrometer

Christian Frommeyer picture Christian Frommeyer · Feb 9, 2018 · Viewed 32.2k times · Source

I started my first project on Spring Boot 2 (RC1). Thanks to the already good documentation this has not been to hard coming from Spring Boot 1.x.

However now that I want to integrate metrics I'm stumbeling. As far as I was able to find currently there is only documentation for the metrics shipped by default. But I'd like to also measure service level execution time as well as the time used in dynamodb.

EDIT I'm looking for a solution using Micrometer, the library used in the new actuator library shipped with spring-boot 2.

Is there any guide on how this should be done? From this I read that there is no easy annotation based solution for arbitrary spring beans yet. Could s.o. give me an example / link to documentation on how a method like below could be metered?

@Service
@Timed
public class MyService {
    public void doSomething() {
        ...;
    }
}

Answer

Michal Stepan picture Michal Stepan · Mar 9, 2018

@io.micrometer.core.annotation.Timed annotation seems to be out of order for custom calls due to reduction of scope, at it is mentioned in link in your question.

You need to manually setup an Aspect:

@Configuration
@EnableAspectJAutoProxy
public class AutoTimingConfiguration {
    @Bean
    public TimedAspect timedAspect(MeterRegistry registry) {
        return new TimedAspect(registry);
        }
}

This way method like this:

@Timed("GET_CARS")
public List<Car> getCars(){
        return Lists.newArrayList();
}

will result in GET_CARS metric in /actuator/metrics (default) endpoint.