micrometer-metrics / micrometer

An application observability facade for the most popular observability tools. Think SLF4J, but for observability.
https://micrometer.io
Apache License 2.0
4.39k stars 966 forks source link

Timed annotation should consider Transactional handling #5235

Closed dkroehan closed 2 days ago

dkroehan commented 3 days ago

Please describe the feature request. I use micrometer in a Spring Boot application to measure the execution time of a method. Given the following (Kotlin) method:

class MyClass(...) {

@Timed(value = "my_timer")
@Transactional
fun doSomething() {
// Some code that performs database changes
}

}

I would expect that the @Timed annotation measures the total time that the method execution takes including the @Transactional handling. I compared it to measuring the time outside, as in the following example:

            val start = System.nanoTime()
            myClass.doSomething()
            timer.record(System.nanoTime() - start, TimeUnit.NANOSECONDS)

Since the time measuring is different I did some debugging and found out that the underlying TimedAspect runs after the @Transactional processing, which means the order is as follows:

  1. Transaction start
  2. Time measurement starts
  3. Method body execution
  4. Time measurement stops
  5. Transaction commits

I couldn't find a hint about that in the micrometers docs.

What I would like to achieve instead is the following order:

  1. Time measurement starts
  2. Transaction start
  3. Method body execution
  4. Transaction commits
  5. Time measurement stops

If there is already a way to achieve this, please let me know.

jonatan-ivanov commented 2 days ago

I couldn't find a hint about that in the micrometers docs.

This is because Micrometer does not depend on Spring, I don't think it should document the execution order of every annotation of every version of every library.

What I would like to achieve instead is the following order: ...

I think you should open an issue in spring-framework to change the order.

If there is already a way to achieve this, please let me know.

I'm not sure about this but maybe if you create the aspect beans on your own and add an @Order annotation to them, that might have an effect on the proxying order. This question would also belong to the issue tracker of Spring Framework.