0

I have a basic spring rest controller and have a company requirement which needs to log request and response in one combined log message. I planned on doing this with some simple aspect.

However the controller calls a service which in turn calls out to another third party api and there is requirement to include the time taken for this third party call in the log output from the controller mentioned above.

I am wondering if this can be achieved with aspects? I guess it would need an @Around aspect for main controller and then another @Around for the downstream api call and some way to inject the result of the inner aspect to the advice or outer one. Not sure if this can be done?? Or perhaps a request scoped bean passed through aspects??

Thanks

  • You might want to add an [MCVE](https://stackoverflow.com/help/mcve) to your question in order to improve the chances to get good answers. It would help other developers to reproduce your situation, analyse it and provide a working solution. :-) – kriegaex Nov 05 '19 at 14:21

1 Answers1

0

How about a class Log

public class Log {

private long start;

private long end;

public long getStart() {
    return start;
}

public void setStart(long start) {
    this.start = start;
}

public long getEnd() {
    return end;
}

public void setEnd(long end) {
    this.end = end;
}

@Override
public String toString() {
    return "Log [start=" + start + ", end=" + end + "]";
}

And pass the instance of this object through the api calls.

Say BeanOne.methodOne(Log,..) -> BeanTwo.methodTwo(Log,..) . BeanTwo.methodTwo() calls the external api and the time is recorded in Log instance.

and an advice as follows

@Around("execution(* methodOne(..)) && args(log)")
    public void testAdviceBeanOne(ProceedingJoinPoint pjp,Log log) {
        System.out.println("Before methodOne()");
        try {
            System.out.println(log);
            pjp.proceed();
            System.out.println(log);
        } catch (Throwable e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("After methodOne()");
    }

Gives the output

Before methodOne()
Log [start=0, end=0]
Log [start=1572408716134, end=1572408716136]
After methodOne()

There could be a more elegant solution , still my two cents

R.G
  • 6,436
  • 3
  • 19
  • 28