在Spring的项目中配置Log4j

 原创文章,转载请务必注明出处,作者:李佳

 

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());
  }
 }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值