0

How to calculate Spring Controller Execution time for All spring Controller? Let's say I have 200 Spring REST Controller in my Application, how can I calculate execution time for each controller and save that time in Database?

Ali Ben Messaoud
  • 11,690
  • 8
  • 54
  • 87
jagdish khetre
  • 1,381
  • 2
  • 8
  • 15

2 Answers2

1

Write a Servlet HttpFilter or a Spring MVC HandlerInterceptor.

For HandlerInterceptor, see Spring Documentation.

See also Difference between Interceptor and Filter in Spring MVC.

Andreas
  • 154,647
  • 11
  • 152
  • 247
0

You can use Aspect to add this behaviour to your application.

@Aspect 
@Component
@Slf4j
public class RequestLogAspect {

  @Autowired DurationRepository repo;
  ... 
  
  @Around("@annotation(org.springframework.web.bind.annotation.RequestMapping) 
           && execution(public * *(..))"
  )
  public Object log(final ProceedingJoinPoint proceedingJoinPoint) throws Throwable {

    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
            .currentRequestAttributes())
            .getRequest();
  
    long start = System.currentTimeMillis();

    Object value;

    try {
        value = proceedingJoinPoint.proceed();
    } catch (Throwable throwable) {
        throw throwable;
    } finally {
        long duration = System.currentTimeMillis() - start;

        log.info("{} {} from {} took {} ms",
                request.getMethod(), request.getRequestURI(),
                request.getRemoteAddr(), duration);
        // use repo and the information above to persist data
    }

    return value;
  }
}

Source from this tutorial.

Ali Ben Messaoud
  • 11,690
  • 8
  • 54
  • 87