Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Log the return value of a method using spring aop

Tags:

spring-aop

I have a method which returns an object. I would like to print that object's value in my log using spring AOP. How can I achieve that?

Please help!

like image 910
prabu Avatar asked Aug 27 '13 15:08

prabu


People also ask

Which advice allows access the return value of a JoinPoint?

After (finally) advice: Advice to be executed regardless of the means by which a join point exits (normal or exceptional return). Around advice: Advice that surrounds a join point such as a method invocation. This is the most powerful kind of advice.

What is JoinPoint in AOP?

Join Point: A join point is a specific point in the application such as method execution, exception handling, changing object variable values, etc. In Spring AOP a join point is always the execution of a method. Advice: Advices are actions taken for a particular join point.

What is Pointcut in Spring AOP?

In Spring AOP, a join point always represents a method execution. A pointcut is a predicate that matches the join points, and the pointcut expression language is a way of describing pointcuts programmatically.


2 Answers

Using @AfterReturning with a returnValue param.

You could then interogate the object returned This is an example where I do it on everything but get methods in a repository

@AfterReturning(value = "@target(org.springframework.stereotype.Repository) && !execution(* get*(..))", returning = "returnValue")
public void loggingRepositoryMethods(JoinPoint joinPoint, Object returnValue) {
    String classMethod = this.getClassMethod(joinPoint);



     if(returnValue !=null)
     {
       //test type of object get properties (could use reflection)
       log it out
     }
     else
     {
         //do logging here probably passing in (joinPoint, classMethod);
     }
}
like image 66
Shaun Hare Avatar answered Dec 03 '22 10:12

Shaun Hare


In our case, majority of the time we return entity classes of spring modal, so we overridden the toString method of all entity classes with required minimal information and printed as below

@AfterReturning(pointcut = "within(@org.springframework.stereotype.Service *)", returning = "result")
public void logAfterReturning(JoinPoint joinPoint, Object result) {
    logger.info(" ###### Returning for class : {} ; Method : {} ", joinPoint.getTarget().getClass().getName(), joinPoint.getSignature().getName());
    if (result != null) {
        logger.info(" ###### with value : {}", result.toString());
    } else{
        logger.info(" ###### with null as return value.");
    }
}
like image 29
Jajikanth pydimarla Avatar answered Dec 03 '22 09:12

Jajikanth pydimarla