原创文章,转载请务必注明出处,作者:李佳
1.在web.xml中加入如下代码
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/classes/log4j.properties</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<servlet>
<servlet-name>log4j</servlet-name>
<servlet-class>org.springframework.web.util.Log4jConfigServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
2.在applicationContext.xml中加入如下代码
<bean class="com.aop.LoggerAdvice" id="loggerAdvice"/>
<bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
<property name="interceptorNames">
<list>
<value>loggerAdvice</value>
</list>
</property>
<property name="beanNames">
<list>
<idref local="userService"/>
</list>
</property>
</bean>
3.编写aop切面日志
package com.aop;
import java.lang.reflect.Method;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Logger;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;
public class LoggerAdvice implements MethodBeforeAdvice, AfterReturningAdvice {
public void before(Method method, Object[] args, Object target) throws Throwable {
//web.xml(spring + log4j)
Logger logger = Logger.getLogger(target.getClass());
logger.debug("+Class : "+ target.getClass().getName());
logger.debug("+-------Method : "+ method.getName());
for(int i=0; i<args.length; i++){
logger.debug(" +-arg"+ i + " : " + args[i].toString());
}
}
public void afterReturning(Object retuVal, Method method, Object[] args, Object target) throws Throwable {
//common-logging + log4j
Log log = LogFactory.getLog(target.getClass());
if(retuVal != null){
log.debug("+-------Return : " + retuVal.toString());
}
}
}