How to use Micrometer @Timed annotation outside of Spring, in a Java Application

Viewed 793

I am trying to use Micrometer to record info in my Java application.

I have Micrometer registry in my application main initialized as follows:

MeterRegistry registry = new SimpleMeterRegistry();

I have a class CountedObject which has an int id and a reference to the registry.

In my class CountedObject I have a method called timedFunction() as follows:

@Timed(value = "myTimer")
public void timedFunction() {
    try {
        int sleepTime = new Random().nextInt(5) + 1;
        Thread.sleep(sleepTime * 1000L);
    } catch (InterruptedException e) {}
    System.out.println("timedFunction");
}

And a method called timedFunction() as follows:

public void timeConsumingFunction() {
    LongTaskTimer longTaskTimer = AppMetrics.getInstance().getLongTaskTimer("longTaskTimer1");
    Sample task = longTaskTimer.start();
    
    try {
        int sleepTime = new Random().nextInt(5) + 1;
        Thread.sleep(sleepTime * 1000L);
    } catch (InterruptedException e) {}
    
    System.out.println("timeConsumingFunction() for object-" + id + " took: " + task.duration(TimeUnit.SECONDS));
    task.stop();
}

In my application I create an object CountedObject and run both methods.

Then I run the following to print all metrics info:

List<Meter> meters = registry.getMeters();
    
for (Meter meter : meters) {
    System.out.println(meter.getId());
    for (Measurement measurement : meter.measure()) {
        System.out.println(measurement.getStatistic() + " : " + measurement.getValue());
    }
    System.out.println("\n");
}

I only find "longTaskTimer1" in the metrics and myTimer used in the annotated method is not there. How can this @Timed annotation be used and how to link it to my app's register

1 Answers

You need to set-up TimedAspect to process @Timed annotations. If you are using Spring, just create a TimedAspect @Bean and it should work. If you don't, you need to set-up AspectJ yourself.

Related