使用spring的aop监听所有controller或者action日志

日志还是使用log4,直接配置好文件输出或者控制台打印!

注解或者cml都行,我这里采用xml方式:

spring的配置文件中配置日志类和aop:

<!-- 日志监控类 -->
	<bean id="actionLog" class="com.zhuzher.log.ActionLogAspect"></bean>
	<!-- 监控所有action -->
	<!-- 使用cglib代理 -->
	<aop:config proxy-target-class="true"> 
         <aop:pointcut id="logAction" expression="execution(* com.zhuzher.*.action.*.*(..))"/> 
         <aop:aspect id="b" ref="actionLog">
         <!-- <aop:before pointcut-ref="logAction" method="before"/> -->
         <aop:after pointcut-ref="logAction" method="after"/>
      	<!--  <aop:after-returning method="afterReturn" pointcut-ref="logAction" returning="result"/>
         <aop:after-throwing method="afterThrow" pointcut-ref="logAction" throwing="ex"/> -->
         </aop:aspect> 
    </aop:config>

  ,根据需要即可,

然后编写切面类,注意,最好使用cglib代理,需要添加依赖,默认使用jdk代理的话,所代理的类必须有接口,否则报错:

//action日志监听
public class ActionLogAspect {
	
	private final static Logger log = Logger.getLogger(ActionLogAspect.class);
    /**
     * 后置通知(无论方法是否发生异常都会执行,所以访问不到方法的返回值)
     */
    public void after(JoinPoint joinPoint)throws IOException{
        WriteToLog(joinPoint);
    }
    //把信息写进日志里面
    public void WriteToLog(JoinPoint joinPoint)throws IOException {
    	HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.
                getRequestAttributes()).getRequest();
    	//获取方法名
        String cla=joinPoint.getTarget().getClass().getName();//action
        String method=joinPoint.getSignature().getName();//method
        //获取操作人
        HttpSession session = request.getSession();
        Manager manager = (Manager) session.getAttribute("SESSION_MANAGER");
        Integer userid=null;
        String username="";
        if(manager!=null){
        	userid = manager.getId();
        	username =manager.getUsername();      	
        }
        StringBuffer json=new StringBuffer();//获取请求参数
        Enumeration<String> names = request.getParameterNames();
		while(names.hasMoreElements()){
			//获取每一个文本域的name
			String name = names.nextElement();
			String [] values = request.getParameterValues(name);
			if(values!=null && values.length>0){
				//输出参数名和参数值
				json.append(name+":{");
				for(String val:values){
					json.append(val+",");
				}
				if (','==json.charAt(json.length()-1)) json.deleteCharAt(json.length()-1);
				json.append("},");				
			}
		}
 		if (json!=null && json.length()>0 && ','==json.charAt(json.length()-1)) json.deleteCharAt(json.length()-1);
        log.debug("{method:{"+cla+"."+method+"}, params:{"+json.toString()+"},user:{id:"+userid+",username:"+username+"}}");
    }
}

 获取对应的方法名,类名,以及从session中获取当前用户就可以了

原文地址:https://www.cnblogs.com/houzheng/p/9688049.html