Skip to content

Instantly share code, notes, and snippets.

@neo7BF
Last active August 11, 2020 09:34
Show Gist options
  • Save neo7BF/e2569434a6d40b790c5f837a2ee67723 to your computer and use it in GitHub Desktop.
Save neo7BF/e2569434a6d40b790c5f837a2ee67723 to your computer and use it in GitHub Desktop.
Another structured way to trace execution time of queries with spring aop and spring jdbc in spring boot
import org.apache.commons.lang3.time.DurationFormatUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;
//Replate <> with your package
@Component
@Aspect
@Slf4j
public class LoggingExecutionTimeQueryAspect {
@Around("@annotation(<PACKAGE>.TrackExecutionTime)")
public Object trackTime (ProceedingJoinPoint pjp) throws Throwable {
long startTime = System.currentTimeMillis();
Object obj = pjp.proceed();
long endTime = System.currentTimeMillis();
log.info("Execution time: " + DurationFormatUtils.formatDurationHMS(endTime-startTime) + " Method: " + pjp.getSignature());
return obj;
}
}
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TrackExecutionTime {
}
@Repository
public interface UserRepository extends CrudRepository<User, Long> {
@TrackExecutionTime
@Query("SELECT * FROM USER WHERE EMAIL=:email")
Optional<User> findUserByEmail(@Param("email") String email);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment