How to Log Method Execution Time in Spring Boot Using AOP
Overview
Monitoring method execution time is one of the easiest yet most effective ways to understand your application’s performance. In this guide, we’ll explore how to use Spring Boot with Aspect-Oriented Programming (AOP) to log method execution times cleanly—without cluttering your business logic. By leveraging the @Aspect annotation, we can intercept method calls, measure how long they take, and log this information for performance analysis. This approach is flexible, reusable, and perfect for tracking performance bottlenecks in large-scale applications. Let’s dive in and build a lightweight execution time logger using Spring AOP.
Aspect Annotation
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TrackExecutionTime {
 //
}
Aspect Interceptor
@Aspect
@Component
@Slf4j
public class ExecutionTimeAspect {
  @Around("@annotation(com.dcx.nba.actions.annotations.TrackExecutionTime)")
  public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
    long startTime = System.currentTimeMillis();
    Object result = joinPoint.proceed();
    long endTime = System.currentTimeMillis();
    long executionTime = endTime - startTime;
    log.info("{} executed in {}ms", joinPoint.getSignature().toShortString(), executionTime);
    return result;
  }
}
Annotation Usage
@Override
@TrackExecutionTime
@SchedulerLock(name = JOB_NAME)
@Scheduled(cron = "${app.schedulers.update-action-status.cron}")
public void scheduleUpdateStatus() {
}




Post a Comment