[置顶] springmvc Aspect 实现自定义注解的日志记录

1,设置直接拦截所有的controller所以需要spring-mvc.xml中添加 交由cglib代理。
<aop:aspectj-autoproxy proxy-target-class="true" />  

2,使用时候只要在controller的method上加上
@SystemControllerLog(description="添加用户")


3,代码片段

SystemLogAspect.java
 
 
package com.cm.contract.controller.annotation;

import java.lang.reflect.Method;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.cm.contract.common.CMConstant;
import com.cm.contract.model.companyinfo.CMcompany;
import com.cm.contract.model.customerinfo.CMcustomer;
import com.cm.contract.model.jurinfo.CMjurisdiction;
import com.cm.contract.model.loginfo.CMlog;
import com.cm.contract.model.userinfo.CMuser;
import com.cm.contract.service.loginfo.LogService;
import com.cm.contract.utill.CommonUtill;
import com.cm.contract.utill.DateUtils;

/**
 * 自定义切点类
 * 
 * @author FENGWEI
 * @date 2016-6-17
 */
@Aspect
@Component
public class SystemLogAspect {
	// 注入service 用于把热值保存数据库
	@Resource
	private LogService logService;
	// 本地异常日志记录对象
	private static final Log logger = LogFactory.getLog(SystemLogAspect.class);

	// Service层切点
	@Pointcut("@annotation(com.cm.contract.controller.annotation.SystemServiceLog)")
	public void serviceAspect() {
		logger.info("service 日志记录方式启动!");
	}

	// Contorller层切点
	@Pointcut("@annotation(com.cm.contract.controller.annotation.SystemControllerLog)")
	public void controllerAspect() {
		logger.info("controller 日志记录方式启动!");
	}

	// 前置通知 用于拦截contorller层记录 日志的操作
	@Before("controllerAspect()")
	public void doBefore(JoinPoint joinPoint) {

		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes()).getRequest();
		// 读取session中的用户
		CMuser user = (CMuser) request.getSession().getAttribute(
				CMConstant.LOGINUSER);
		// 请求的IP
		String ip = CommonUtill.getIp();
	
		try {
			// *========控制台输出=========*//
			logger.info("=====前置通知开始=====");
			logger.info("请求方法:"
					+ (joinPoint.getTarget().getClass().getName() + "."
							+ joinPoint.getSignature().getName() + "()"));
			logger.info(joinPoint.getTarget().getClass().getName());
			//获取用户请求方法的参数
			String params = "";
			//参数组
			Object[] methodParams = joinPoint.getArgs();
			//获取description值 判断请求的方法
			String methodRemark = getControllerMethodDescription(joinPoint);
			//如果参数为对象 则CMjurisdiction jur=(CMjurisdiction) methodParams[0];--方式  如果参数为ModelMap 则直接获取参数
			if (methodParams != null && methodParams.length > 0) {
				for (int i = 0; i < methodParams.length; i++) {
					if (methodRemark.equals("添加权限")) {
						CMjurisdiction jur=(CMjurisdiction) methodParams[0];
						params=" 名称:"+jur.getJurname();
					}
					if (methodRemark.equals("修改权限")) {
						CMjurisdiction jur=(CMjurisdiction) methodParams[0];
						params=" ID:"+jur.getJurid();
					}
					if (methodRemark.equals("添加部门")) {
						String orgname = request.getParameter("addName");
						params=" 名称:"+orgname;
					}
					if (methodRemark.equals("删除部门")) {
						String currId = request.getParameter("treeId");
						params=" ID:"+currId;
					}
					if (methodRemark.equals("修改部门")) {
						String orgid = request.getParameter("editId");
						params=" ID:"+orgid;
					}
					
				}
			}
			
			String type="4";//日志类型(0:客户,1:公司,2:合同,3:成本,4:其它,5:数据库操作)方便查询页面显示
			//公司添加的日志
			if (joinPoint.getThis().getClass().toString().contains("CompanyController")) {
				type="1";
			}
			if (joinPoint.getThis().getClass().toString().contains("CustomerController")) {
				type="0";
			}
			if (joinPoint.getThis().getClass().toString().contains("BakRecoverController")) {
				type="5";
			}
			logger.info(joinPoint.getSignature());
			logger.info("方法描述:"
					+ getControllerMethodDescription(joinPoint));
			logger.info("请求人:" + user.getUsername());
			logger.info("请求IP:" + ip);
			logger.info("请求參數:" + params);
			// *========数据库日志=========*//
			CMlog log = new CMlog();
			log.setContent("用户: "+user.getUsername() +" "+getControllerMethodDescription(joinPoint)+": "+params +"成功!");
			log.setTitle(getControllerMethodDescription(joinPoint));
			log.setLogtype("0"); // 日志类型 业务日志
			log.setUserip(ip);
			log.setUsername(user.getLoginname());
			log.setLogtime(DateUtils.dateTimeStr());
			log.setType(type);
			log.setUserid(user.getUserid());
			// 保存数据库
			logService.insert(log);
			logger.info("=====前置通知结束=====");
		} catch (Exception e) {
			// 记录本地异常日志
			logger.error("==前置通知异常==异常信息:{}");
			logger.error(e.getMessage());
		}
	}

	/**
	 * 异常通知 用于拦截service层记录异常日志
	 * 
	 * @param joinPoint
	 * @param e
	 */
	@AfterThrowing(pointcut = "serviceAspect()", throwing = "e")
	public void doAfterThrowing(JoinPoint joinPoint, Throwable e) {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes()).getRequest();
		HttpSession session = request.getSession();
		// 读取session中的用户
		CMuser user = (CMuser) request.getSession().getAttribute(
				CMConstant.LOGINUSER);
		// 获取请求ip
		String ip = CommonUtill.getIp();
		//获取用户请求方法的参数
		String params = "";
		try {
		
			//参数组
			Object[] methodParams = joinPoint.getArgs();
			//获取description值 判断请求的方法
			String methodRemark = getControllerMethodDescription(joinPoint);
			//如果参数为对象 则CMjurisdiction jur=(CMjurisdiction) methodParams[0];--方式  如果参数为ModelMap 则直接获取参数
			if (methodParams != null && methodParams.length > 0) {
				for (int i = 0; i < methodParams.length; i++) {
					if (methodRemark.equals("添加权限")) {
						CMjurisdiction jur=(CMjurisdiction) methodParams[0];
						params=" 名称:"+jur.getJurname();
					}
					if (methodRemark.equals("修改权限")) {
						CMjurisdiction jur=(CMjurisdiction) methodParams[0];
						params=" ID:"+jur.getJurid();
					}
					if (methodRemark.equals("添加部门")) {
						String orgname = request.getParameter("addName");
						params=" 名称:"+orgname;
					}
					if (methodRemark.equals("删除部门")) {
						String currId = request.getParameter("treeId");
						params=" ID:"+currId;
					}
					if (methodRemark.equals("修改部门")) {
						String orgid = request.getParameter("editId");
						params=" ID:"+orgid;
					}
					if (methodRemark.equals("添加客户")) {
						CMcustomer cus=(CMcustomer) methodParams[0];
						params=" 名称:"+cus.getCustomername();
					}
					if (methodRemark.equals("修改客户")) {
						String customerid = request.getParameter("customerid");
						params=" ID:"+customerid;
					}
					if (methodRemark.equals("删除客户")) {
						String customerid = request.getParameter("id");
						params=" ID:"+customerid;
					}
					if (methodRemark.equals("添加公司")) {
						CMcompany com=(CMcompany) methodParams[0];
						
						params=" 名称:"+com.getCompanyname();
					}
					if (methodRemark.equals("编辑公司")) {
						String companyid = request.getParameter("companyid");
						params=" ID:"+companyid;
					}
					if (methodRemark.equals("上传公司文件")) {
						String companyid = request.getParameter("companyid");
						params=" 公司ID:"+companyid;
					}
					if (methodRemark.equals("删除公司关联文件")) {
						String fileid = request.getParameter("fileid");
						params=" 文件ID:"+fileid;
					}
					if (methodRemark.equals("下载公司关联文件")) {
						String fileid = request.getParameter("fileid");
						params=" 文件ID:"+fileid;
					}
					if (methodRemark.equals("数据库手动备份")) {
						String fileName = "合同管理系统bak";
						String date = DateUtils.doFindDate();
						fileName += "[" + date + "]";
						params="  :"+fileName+".zip";
					}
					if (methodRemark.equals("启动数据库定时备份")) {
						String bakFileName = request.getParameter("bakFileName");
						String date = DateUtils.doFindDate();
						bakFileName += "[" + date + "]";
						params="  :"+bakFileName+".zip";
					}
					if (methodRemark.equals("执行定时备份")) {
						 String bakFileName=methodParams[0].toString();
						params="  :"+bakFileName+".zip";
					}
					if (methodRemark.equals("还原数据库")) {
						String backid = request.getParameter("backid");
						params="  ID:"+backid;
					}
				}
			}
			/* ========控制台输出========= */
			logger.info("=====异常通知开始=====");
			logger.info("异常代码:" + e.getClass().getName());
			logger.info("异常信息:" + e.getMessage());
			logger.info("异常方法:"
					+ (joinPoint.getTarget().getClass().getName() + "."
							+ joinPoint.getSignature().getName() + "()"));
			logger.info("方法描述:" + getServiceMthodDescription(joinPoint));
			logger.info("请求人:" + user.getUsername());
			logger.info("请求IP:" + ip);
			logger.info("请求参数:" + params);
			/* ==========数据库日志========= */
			CMlog log = new CMlog();
			log.setContent("用户: "+user.getUsername() +" "+getControllerMethodDescription(joinPoint) +"异常!");
			log.setTitle(getControllerMethodDescription(joinPoint));
			log.setLogtype("2"); // 日志类型 业务日志
			log.setUserip(ip);
			log.setUsername(user.getUsername());
			// log.setUserip(CommonUtill.getIp());
			log.setLogtime(DateUtils.dateTimeStr());
			log.setOther1(params);
			// 保存数据库
			logService.insert(log);
			logger.info("=====异常通知结束=====");
		} catch (Exception ex) {
			// 记录本地异常日志
			logger.error("异常信息:{}");
			logger.error(ex.getMessage());
		}
		/* ==========记录本地异常日志========== */

		logger.error("异常方法:{}异常代码:{}异常信息:{}参数:{}");
		logger.error(joinPoint.getTarget().getClass().getName()
				+ joinPoint.getSignature().getName() + e.getClass().getName()
				+ e.getMessage() + params);
	}

	/**
	 * 获取注解中对方法的描述信息 用于service层注解
	 * 
	 * @param joinPoint
	 *            切点
	 * @return 方法描述
	 * @throws Exception
	 */
	public static String getServiceMthodDescription(JoinPoint joinPoint)
			throws Exception {
		// 获取目标类名
		String targetName = joinPoint.getTarget().getClass().getName();
		// 获取方法名
		String methodName = joinPoint.getSignature().getName();
		// 获取相关参数
		Object[] arguments = joinPoint.getArgs();
		// 生成类对象
		Class targetClass = Class.forName(targetName);
		// 获取该类的方法
		Method[] methods = targetClass.getMethods();
		String description = "";
		for (Method method : methods) {
			if (method.getName().equals(methodName)) {
				Class[] clazzs = method.getParameterTypes();
				if (clazzs.length == arguments.length) {
					description = method.getAnnotation(SystemServiceLog.class)
							.description();
					break;
				}
			}
		}
		return description;
	}

	/**
	 * 获取注解中对方法的描述信息 用于Controller层注解
	 * 
	 * @param joinPoint
	 *            切点
	 * @return 方法描述
	 * @throws Exception
	 */
	public static String getControllerMethodDescription(JoinPoint joinPoint)
			throws Exception {
		// 获取目标类名
		String targetName = joinPoint.getTarget().getClass().getName();
		// 获取方法名
		String methodName = joinPoint.getSignature().getName();
		// 获取相关参数
		Object[] arguments = joinPoint.getArgs();
		// 生成类对象
		Class targetClass = Class.forName(targetName);
		// 获取该类的方法
		Method[] methods = targetClass.getMethods();
		String description = "";
		for (Method method : methods) {
			if (method.getName().equals(methodName)) {
				Class[] clazzs = method.getParameterTypes();
				if (clazzs.length == arguments.length) {
					description = method.getAnnotation(
							SystemControllerLog.class).description();
					break;
				}
			}
		}
		return description;
	}
}


 
 

 4,Controller注解类  

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;
 
@Target({ElementType.PARAMETER, ElementType.METHOD})    
@Retention(RetentionPolicy.RUNTIME)    
@Documented   
public @interface SystemControllerLog {
    /** 标题 */
    String descripy()  default "";
 
}
5.Service注解类
@Target({ElementType.PARAMETER, ElementType.METHOD})    
@Retention(RetentionPolicy.RUNTIME)    
@Documented   
public @interface SystemServiceLog {
    /** 标题 */
    String descripy()  default "";
 
}


你可能感兴趣的:([置顶] springmvc Aspect 实现自定义注解的日志记录)