Java - Aspect based measuring the method execution time of function with annotation

less than 1 minute read

Annotation definition.

1
2
3
4
5
@Target({ElementType.METHOD,
         ElementType.CONSTRUCTOR})
@Retention(RetentionPolicy.RUNTIME)
public @interface MeasureMethodTime {
}

Aspect advice implementation.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Aspect
public class MeasureMethodLogger {
    private static Logger LOGGER = LoggerFactory.getLogger(MeasureMethodLogger.class);
    @Around("execution(@com.acrocontext.api.utils.MeasureMethodTime * *(..)) && @annotation(measureMethodTimeAnnotation)")
    public Object logDuration(ProceedingJoinPoint joinPoint,
                              MeasureMethodTime measureMethodTimeAnnotation)
            throws Throwable {
        long start = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        LOGGER.info(
                String.format("[MEASURE]: %s in %d(msec)",
                joinPoint.getSignature().getName(),
                System.currentTimeMillis() - start));
        return result;
    }
}

Example

1
2
3
  @MeasureMethodTime
  public int test(int value) {
  }