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

This method runs via scheduler and computes the total elapsed time during the execution
@Override
@TrackExecutionTime
@SchedulerLock(name = JOB_NAME)
@Scheduled(cron = "${app.schedulers.update-action-status.cron}")
public void scheduleUpdateStatus() {
}

0 Comments

Post a Comment

Post a Comment (0)

Previous Post Next Post
NERV Open Source

Building production Spring Boot systems?

Explore NERV — open-source Java libraries for audit trails, persistence, exception handling, and reliable event-driven architecture.

Explore NERV on GitHub →