Logging latency of a query in JPA

43 views Asked by At

I have a CRUD repository in springboot java app. I am trying to measure the latency of the query form APP perspective and log it in the logger. What is a good elegant way to achieve this please ? I am also going to use these logs for monitoring purposes later.

Currently the way I am doing it is -

long start = System.currentTimeMillis();
result = respoistoryDao.findId();
long executionTime = System.currentTimeMillis()-start;

How can I make this better ?

1

There are 1 answers

1
Jacob On

The most elegant and reusable design would be an Aspect. (Spring AOP docs)

First, create an annotation

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Timed {}

Then create the Aspect

@Slf4j
@Aspect
@Component
public class TimedAspect {

    @Around("@annotation(Timed)")
    public Object executionTimeLogger(ProceedingJoinPoint joinPoint) {
        long start = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long duration = (System.currentTimeMillis() - start);
          
        log.info("Method: {} | Duration:  {}ms", joinPoint.getSignature(), duration);
        return result;
    }
}

Once you have these two pieces, just add @Timed to any method signature, and it will log out the duration for you.