Skip to content
Advertisement

How to log Spring Data JPA repository method execution time?

I have simple Spring Data JPA repository.

public interface UserRepository extends JpaRepository<UserEntity, Serializable>{ … }

Is there any way to monitor execution time for methods generated by Spring (for example findOne(…))?

Advertisement

Answer

The easiest way is to use a CustomizableTraceInterceptor as follows:

@Configuration
@EnableAspectJAutoProxy
public class SpringDataExecutionLoggingConfiguration {

  @Bean
  public CustomizableTraceInterceptor customizableTraceInterceptor() {

    CustomizableTraceInterceptor customizableTraceInterceptor = new CustomizableTraceInterceptor();
    customizableTraceInterceptor.setUseDynamicLogger(true);
    customizableTraceInterceptor.setExitMessage("Executed $[methodName] in $[invocationTime]");
    return customizableTraceInterceptor;
  }

  @Bean
  public Advisor advisor() {

    AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
    pointcut.setExpression("execution(public * org.springframework.data.repository.CrudRepository+.*(..))");
    return new DefaultPointcutAdvisor(pointcut, customizableTraceInterceptor());
  }
}
Advertisement