'How to use AOP correctly to measure the runtime of requests across services? (Spring Boot)

I would like to invite you to talk with me about AOP and logging in Spring Boot applications. My goal is to log the speeds of each request. This should also work when a service calls another service. Preferably the runtime, the name of the method and an individual ID for each request should be output.

Now the question: Is it possible to realize this with AOP?

I started with the following Youtube tutorial: https://www.youtube.com/watch?v=RVvKPP5HyaA&ab_channel=JavaTechie

And here is a first AOP:

package abc.advise;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.databind.ObjectMapper;

@Aspect
@Component
public class LoggingAdvice {

  Logger log = LoggerFactory.getLogger(LoggingAdvice.class);

  @Pointcut(
      value = "execution(* abc.api.*Controller.*(..))")
  public void pointCut() {

  }

  @Around("pointCut()")
  public Object applicationLogger(ProceedingJoinPoint pjp) throws Throwable {
    ObjectMapper mapper = new ObjectMapper();
    String methodName = pjp.getSignature().getName();
    String className = pjp.getTarget().getClass().toString();
    Object[] array = pjp.getArgs();
    log.info("method invoked " + className + " : " + methodName + "()" + "arguments : "
        + mapper.writeValueAsString(array));

    Object object = pjp.proceed();
    log.info("method invoked " + className + " : " + methodName + "()" + "Response : "
        + mapper.writeValueAsString(array));

    return object;
  }

}

So this AOP looks into the package API and applies the AOP to classes with controller as suffix. (I decided to use AOP because I thought that I would not have to change my single rest methods).

To come back to the question. Can I use AOP to measure request times across services?

The questions that naturally play a role here are:

Where should the ID be stored so that other services working with the same request can continue to use the ID?

How should I use the endpoints with AOP so that I get a log entry that shows the runtime of the complete request?

I am open for suggestions.

Thanks in advance.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source