It could be a simple solution but I am unable to get it done.
I need to log the overall execution time for my request in SpringBoot Rest API.
Request always enters to MainController
always and can exit from two places-
Restcontroller
same method orExceptionHandlerController
handler methodI have created one custom annotation and injecting it to both main Controller
and ExceptionController
methods and getting elapsed time for individual methods.
So here is the problem. I need to add these individual times to calculate the total time which I don't want.
Is there any other way to log this information easily.
Aspect class:
@Aspect
@Component
public class PointsAspect {
private final static Logger logger = LoggerFactory.getLogger(PointsAspect.class);
@Around("@annotation(annotation)")
public Object logMethod(final ProceedingJoinPoint proceedingJoinPoint, final LogAround annotation)
throws Throwable {
final long start = System.currentTimeMillis();
Object obj;
try {
logger.debug("Starting...! Method Name - " +proceedingJoinPoint.getSignature().getName());
obj = proceedingJoinPoint.proceed();
} finally {
logger.debug("Exiting...! Method Name - " +proceedingJoinPoint.getSignature().getName() +"Execution Time in Milliseconds:> "+ String.valueOf(System.currentTimeMillis()-start));
}
return obj;
}
}
Marker Interface:
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface LogAround {
}
And this is how I am injecting it:
**ExceptionHandlerController.java**
@LogAround
@ExceptionHandler(HttpMessageNotReadableException.class)
public GenericFailureResponse missingRequestBodyException(HttpServletResponse response,
HttpServletRequest request, Exception ex) throws IOException {
GenericFailureResponse failureResponse = new GenericFailureResponse();
//TODO: exception logic
return failureResponse;
}
**MainController.java**
@LogAround
public String getTotalPoints(@RequestParam(required=true) long memberNo,
HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
//TODO : some logic
return "something";
}
You can use a simple filter.
@Component
public class LogTimeFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
long startTime = System.currentTimeMillis();
chain.doFilter(request, response);
long duration = System.currentTimeMillis() - startTime;
System.out.println("Request take " + duration + " ms");
}
}