Log execution time of each method of the request using Spring AOP
Clash Royale CLAN TAG#URR8PPP
Log execution time of each method of the request using Spring AOP
Suppose I have a basic Spring boot application with a simple architecture (Controller, Service, Repository). I'm trying to log the execution time of each layer in the application (and different things from each layer), I'm trying to do this using Spring AOP with an @Around Aspect. The thing is that the application is a concurrent application and multiple requests can come at the same time, so if i do something like this:
@Around("controller() || restController() ")
public Object logAround(final ProceedingJoinPoint joinPoint) throws Throwable
log.info("time elapsed" + timeElapsed)
//Log some other Controller useful info
@Around("service() ")
public Object logAround(final ProceedingJoinPoint joinPoint) throws Throwable
log.info("time elapsed" + timeElapsed)
//Log some other Service useful info
@Around("repository() ")
public Object logAround(final ProceedingJoinPoint joinPoint) throws Throwable
log.info("time elapsed" + timeElapsed)
//Log some other Repository useful info
I won't be able to follow the logs of each request because multiple concurrent requests can happen at a time.
I'm using SLF4J with lombok implementation, but I think I can switch to any other implementation of SLF4J such as log4j if it makes any difference for what I want.
I'd love to have a one-line log for each request.
ThreadLocal
1 Answer
1
To track timing for each request.
Add Thread id as part of logging by changing log format as below
Thread id will be unique for each request
%d %-5level [%thread] [%logger36] : %msg%n%rEx
As you are logging time performance of each layer, redirect performance logging to separate file.
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Create
ThreadLocal
on the top-most layer (e.g. controller in your case, or better already in some servlet filter) with a unique request tracking number and log that together with the timing information of every lower level.– Pavel Horal
Aug 5 at 16:23