Announcement Announcement Module
No announcement yet.
AOP for Logging without changing code Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • AOP for Logging without changing code

    Hi Springians

    we have a big project in Spring and in next phase we are going to adding logging functionality, Old existing code is working fine after a rigirous testing so without chaning any code can it be log it in between of some existing. Please suggest some mature and quality suggestion. with sample code if possible.

  • #2

    You can use Spring's AOP to write a generic around advice and log method signatures, parameters and return values.

    I tried following as examples:

    LoggingAspect is simple POJO aspect.
    public class LoggingAspect {
    	Logger logger = Logger.getLogger(LoggingAspect.class);
    	public Object log(ProceedingJoinPoint pjp) throws Throwable {
    		//Log method name, input
    		Signature sig = pjp.getSignature();
    		String sigName = sig.getDeclaringTypeName() + "." + sig.getName();
    		String arguments = "(";
    		Object[] args = pjp.getArgs();
    		if (args != null) {
    			for (int i = 0; i< args.length ; i++) {
    				arguments += args[i] + ",";
    		arguments += ")";
    		System.out.println(sigName + arguments);
    		Object ret = pjp.proceed();
    		System.out.println("Returned:[" + (ret) + "]");
    		return ret;
    		<aop:pointcut id="loggerMethods"
    			expression="execution(* com.examples..*.*(..))"/>
    		<aop:aspect id="logger" ref="loggerAspect">
    			<aop:around pointcut-ref="loggerMethods" method="log"/>
    	<bean id="loggerAspect" class="com.examples.aop.logging.LoggingAspect" />
    Above aspect is logging method signature with parameters and return values for all methods in "com.examples" package classes and sub packages.



    • #3
      From Spring Documentation [ ]:

      "Spring AOP currently supports only method execution join points (advising the execution of methods on Spring beans)."

      So, if what you are trying to intercept with Spring AOP is a Spring bean then yes, it will work. But if it is not, then you'll need a full blown AOP solution such as AspectJ.

      The reason for this is that Spring AOP is a proxy-based AOP framework.

      For more information on Spring AOP check the documentation (link above).

      I hope it helps.