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 "";
 
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章