Monday, June 1, 2009

How to do an "around" logging Spring AOP Advice on all methods of a class?

Define a LoggingInterceptor in this way :

package ro.vodafone.search.admin.common;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

import org.apache.log4j.Logger;

public class LogInterceptor implements MethodInterceptor{

public Object invoke(MethodInvocation methodInvocation) throws Throwable {
Object result = null;
Logger logger = Logger.getLogger(methodInvocation.getMethod().getDeclaringClass());
try {

logger.info(methodInvocation.getMethod().getDeclaringClass()+ "."+ methodInvocation.getMethod().getName()+ " entered with parameters: " + methodInvocation.getArguments());
result = methodInvocation.proceed();
if (methodInvocation.getMethod().getReturnType() != null && result != null)
logger.info(methodInvocation.getMethod().getDeclaringClass() + "." + methodInvocation.getMethod().getName()+ " exitting with parameters: " + result);
else
logger.info(methodInvocation.getMethod().getDeclaringClass() + "." + methodInvocation.getMethod().getName()+" exitting");
} catch (Throwable ex) {
logger.error("Error while executing the method:"+methodInvocation.getMethod().getName(), ex);
throw ex;
}

return result;
}
}


Then in the spring app context file define the interceptors over the target in this way:

<bean id="logInterceptor" class="ro.vodafone.search.admin.common.LogInterceptor"/>
<bean id="searchAdminService" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target">
<ref local="service"/>
</property>
<property name="interceptorNames">
<list>
<value>logInterceptor</value>
</list>
</property>
</bean>

No comments: