springmvc Aspect 实现自定义注解的日志记录


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

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


3,代码片段

SystemLogAspect.java
[java] view plain copy
  1. package com.cm.contract.controller.annotation;  
  2.   
  3. import java.lang.reflect.Method;  
  4.   
  5. import javax.annotation.Resource;  
  6. import javax.servlet.http.HttpServletRequest;  
  7. import javax.servlet.http.HttpSession;  
  8.   
  9. import org.apache.commons.logging.Log;  
  10. import org.apache.commons.logging.LogFactory;  
  11. import org.aspectj.lang.JoinPoint;  
  12. import org.aspectj.lang.annotation.AfterThrowing;  
  13. import org.aspectj.lang.annotation.Aspect;  
  14. import org.aspectj.lang.annotation.Before;  
  15. import org.aspectj.lang.annotation.Pointcut;  
  16. import org.springframework.stereotype.Component;  
  17. import org.springframework.web.context.request.RequestContextHolder;  
  18. import org.springframework.web.context.request.ServletRequestAttributes;  
  19.   
  20. import com.cm.contract.common.CMConstant;  
  21. import com.cm.contract.model.companyinfo.CMcompany;  
  22. import com.cm.contract.model.customerinfo.CMcustomer;  
  23. import com.cm.contract.model.jurinfo.CMjurisdiction;  
  24. import com.cm.contract.model.loginfo.CMlog;  
  25. import com.cm.contract.model.userinfo.CMuser;  
  26. import com.cm.contract.service.loginfo.LogService;  
  27. import com.cm.contract.utill.CommonUtill;  
  28. import com.cm.contract.utill.DateUtils;  
  29.   
  30. /** 
  31.  * 自定义切点类 
  32.  *  
  33.  * @author FENGWEI 
  34.  * @date 2016-6-17 
  35.  */  
  36. @Aspect  
  37. @Component  
  38. public class SystemLogAspect {  
  39.     // 注入service 用于把热值保存数据库  
  40.     @Resource  
  41.     private LogService logService;  
  42.     // 本地异常日志记录对象  
  43.     private static final Log logger = LogFactory.getLog(SystemLogAspect.class);  
  44.   
  45.     // Service层切点  
  46.     @Pointcut("@annotation(com.cm.contract.controller.annotation.SystemServiceLog)")  
  47.     public void serviceAspect() {  
  48.         logger.info("service 日志记录方式启动!");  
  49.     }  
  50.   
  51.     // Contorller层切点  
  52.     @Pointcut("@annotation(com.cm.contract.controller.annotation.SystemControllerLog)")  
  53.     public void controllerAspect() {  
  54.         logger.info("controller 日志记录方式启动!");  
  55.     }  
  56.   
  57.     // 前置通知 用于拦截contorller层记录 日志的操作  
  58.     @Before("controllerAspect()")  
  59.     public void doBefore(JoinPoint joinPoint) {  
  60.   
  61.         HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder  
  62.                 .getRequestAttributes()).getRequest();  
  63.         // 读取session中的用户  
  64.         CMuser user = (CMuser) request.getSession().getAttribute(  
  65.                 CMConstant.LOGINUSER);  
  66.         // 请求的IP  
  67.         String ip = CommonUtill.getIp();  
  68.       
  69.         try {  
  70.             // *========控制台输出=========*//  
  71.             logger.info("=====前置通知开始=====");  
  72.             logger.info("请求方法:"  
  73.                     + (joinPoint.getTarget().getClass().getName() + "."  
  74.                             + joinPoint.getSignature().getName() + "()"));  
  75.             logger.info(joinPoint.getTarget().getClass().getName());  
  76.             //获取用户请求方法的参数  
  77.             String params = "";  
  78.             //参数组  
  79.             Object[] methodParams = joinPoint.getArgs();  
  80.             //获取description值 判断请求的方法  
  81.             String methodRemark = getControllerMethodDescription(joinPoint);  
  82.             //如果参数为对象 则CMjurisdiction jur=(CMjurisdiction) methodParams[0];--方式  如果参数为ModelMap 则直接获取参数  
  83.             if (methodParams != null && methodParams.length > 0) {  
  84.                 for (int i = 0; i < methodParams.length; i++) {  
  85.                     if (methodRemark.equals("添加权限")) {  
  86.                         CMjurisdiction jur=(CMjurisdiction) methodParams[0];  
  87.                         params=" 名称:"+jur.getJurname();  
  88.                     }  
  89.                     if (methodRemark.equals("修改权限")) {  
  90.                         CMjurisdiction jur=(CMjurisdiction) methodParams[0];  
  91.                         params=" ID:"+jur.getJurid();  
  92.                     }  
  93.                     if (methodRemark.equals("添加部门")) {  
  94.                         String orgname = request.getParameter("addName");  
  95.                         params=" 名称:"+orgname;  
  96.                     }  
  97.                     if (methodRemark.equals("删除部门")) {  
  98.                         String currId = request.getParameter("treeId");  
  99.                         params=" ID:"+currId;  
  100.                     }  
  101.                     if (methodRemark.equals("修改部门")) {  
  102.                         String orgid = request.getParameter("editId");  
  103.                         params=" ID:"+orgid;  
  104.                     }  
  105.                       
  106.                 }  
  107.             }  
  108.               
  109.             String type="4";//日志类型(0:客户,1:公司,2:合同,3:成本,4:其它,5:数据库操作)方便查询页面显示  
  110.             //公司添加的日志  
  111.             if (joinPoint.getThis().getClass().toString().contains("CompanyController")) {  
  112.                 type="1";  
  113.             }  
  114.             if (joinPoint.getThis().getClass().toString().contains("CustomerController")) {  
  115.                 type="0";  
  116.             }  
  117.             if (joinPoint.getThis().getClass().toString().contains("BakRecoverController")) {  
  118.                 type="5";  
  119.             }  
  120.             logger.info(joinPoint.getSignature());  
  121.             logger.info("方法描述:"  
  122.                     + getControllerMethodDescription(joinPoint));  
  123.             logger.info("请求人:" + user.getUsername());  
  124.             logger.info("请求IP:" + ip);  
  125.             logger.info("请求參數:" + params);  
  126.             // *========数据库日志=========*//  
  127.             CMlog log = new CMlog();  
  128.             log.setContent("用户: "+user.getUsername() +" "+getControllerMethodDescription(joinPoint)+": "+params +"成功!");  
  129.             log.setTitle(getControllerMethodDescription(joinPoint));  
  130.             log.setLogtype("0"); // 日志类型 业务日志  
  131.             log.setUserip(ip);  
  132.             log.setUsername(user.getLoginname());  
  133.             log.setLogtime(DateUtils.dateTimeStr());  
  134.             log.setType(type);  
  135.             log.setUserid(user.getUserid());  
  136.             // 保存数据库  
  137.             logService.insert(log);  
  138.             logger.info("=====前置通知结束=====");  
  139.         } catch (Exception e) {  
  140.             // 记录本地异常日志  
  141.             logger.error("==前置通知异常==异常信息:{}");  
  142.             logger.error(e.getMessage());  
  143.         }  
  144.     }  
  145.   
  146.     /** 
  147.      * 异常通知 用于拦截service层记录异常日志 
  148.      *  
  149.      * @param joinPoint 
  150.      * @param e 
  151.      */  
  152.     @AfterThrowing(pointcut = "serviceAspect()", throwing = "e")  
  153.     public void doAfterThrowing(JoinPoint joinPoint, Throwable e) {  
  154.         HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder  
  155.                 .getRequestAttributes()).getRequest();  
  156.         HttpSession session = request.getSession();  
  157.         // 读取session中的用户  
  158.         CMuser user = (CMuser) request.getSession().getAttribute(  
  159.                 CMConstant.LOGINUSER);  
  160.         // 获取请求ip  
  161.         String ip = CommonUtill.getIp();  
  162.         //获取用户请求方法的参数  
  163.         String params = "";  
  164.         try {  
  165.           
  166.             //参数组  
  167.             Object[] methodParams = joinPoint.getArgs();  
  168.             //获取description值 判断请求的方法  
  169.             String methodRemark = getControllerMethodDescription(joinPoint);  
  170.             //如果参数为对象 则CMjurisdiction jur=(CMjurisdiction) methodParams[0];--方式  如果参数为ModelMap 则直接获取参数  
  171.             if (methodParams != null && methodParams.length > 0) {  
  172.                 for (int i = 0; i < methodParams.length; i++) {  
  173.                     if (methodRemark.equals("添加权限")) {  
  174.                         CMjurisdiction jur=(CMjurisdiction) methodParams[0];  
  175.                         params=" 名称:"+jur.getJurname();  
  176.                     }  
  177.                     if (methodRemark.equals("修改权限")) {  
  178.                         CMjurisdiction jur=(CMjurisdiction) methodParams[0];  
  179.                         params=" ID:"+jur.getJurid();  
  180.                     }  
  181.                     if (methodRemark.equals("添加部门")) {  
  182.                         String orgname = request.getParameter("addName");  
  183.                         params=" 名称:"+orgname;  
  184.                     }  
  185.                     if (methodRemark.equals("删除部门")) {  
  186.                         String currId = request.getParameter("treeId");  
  187.                         params=" ID:"+currId;  
  188.                     }  
  189.                     if (methodRemark.equals("修改部门")) {  
  190.                         String orgid = request.getParameter("editId");  
  191.                         params=" ID:"+orgid;  
  192.                     }  
  193.                     if (methodRemark.equals("添加客户")) {  
  194.                         CMcustomer cus=(CMcustomer) methodParams[0];  
  195.                         params=" 名称:"+cus.getCustomername();  
  196.                     }  
  197.                     if (methodRemark.equals("修改客户")) {  
  198.                         String customerid = request.getParameter("customerid");  
  199.                         params=" ID:"+customerid;  
  200.                     }  
  201.                     if (methodRemark.equals("删除客户")) {  
  202.                         String customerid = request.getParameter("id");  
  203.                         params=" ID:"+customerid;  
  204.                     }  
  205.                     if (methodRemark.equals("添加公司")) {  
  206.                         CMcompany com=(CMcompany) methodParams[0];  
  207.                           
  208.                         params=" 名称:"+com.getCompanyname();  
  209.                     }  
  210.                     if (methodRemark.equals("编辑公司")) {  
  211.                         String companyid = request.getParameter("companyid");  
  212.                         params=" ID:"+companyid;  
  213.                     }  
  214.                     if (methodRemark.equals("上传公司文件")) {  
  215.                         String companyid = request.getParameter("companyid");  
  216.                         params=" 公司ID:"+companyid;  
  217.                     }  
  218.                     if (methodRemark.equals("删除公司关联文件")) {  
  219.                         String fileid = request.getParameter("fileid");  
  220.                         params=" 文件ID:"+fileid;  
  221.                     }  
  222.                     if (methodRemark.equals("下载公司关联文件")) {  
  223.                         String fileid = request.getParameter("fileid");  
  224.                         params=" 文件ID:"+fileid;  
  225.                     }  
  226.                     if (methodRemark.equals("数据库手动备份")) {  
  227.                         String fileName = "合同管理系统bak";  
  228.                         String date = DateUtils.doFindDate();  
  229.                         fileName += "[" + date + "]";  
  230.                         params="  :"+fileName+".zip";  
  231.                     }  
  232.                     if (methodRemark.equals("启动数据库定时备份")) {  
  233.                         String bakFileName = request.getParameter("bakFileName");  
  234.                         String date = DateUtils.doFindDate();  
  235.                         bakFileName += "[" + date + "]";  
  236.                         params="  :"+bakFileName+".zip";  
  237.                     }  
  238.                     if (methodRemark.equals("执行定时备份")) {  
  239.                          String bakFileName=methodParams[0].toString();  
  240.                         params="  :"+bakFileName+".zip";  
  241.                     }  
  242.                     if (methodRemark.equals("还原数据库")) {  
  243.                         String backid = request.getParameter("backid");  
  244.                         params="  ID:"+backid;  
  245.                     }  
  246.                 }  
  247.             }  
  248.             /* ========控制台输出========= */  
  249.             logger.info("=====异常通知开始=====");  
  250.             logger.info("异常代码:" + e.getClass().getName());  
  251.             logger.info("异常信息:" + e.getMessage());  
  252.             logger.info("异常方法:"  
  253.                     + (joinPoint.getTarget().getClass().getName() + "."  
  254.                             + joinPoint.getSignature().getName() + "()"));  
  255.             logger.info("方法描述:" + getServiceMthodDescription(joinPoint));  
  256.             logger.info("请求人:" + user.getUsername());  
  257.             logger.info("请求IP:" + ip);  
  258.             logger.info("请求参数:" + params);  
  259.             /* ==========数据库日志========= */  
  260.             CMlog log = new CMlog();  
  261.             log.setContent("用户: "+user.getUsername() +" "+getControllerMethodDescription(joinPoint) +"异常!");  
  262.             log.setTitle(getControllerMethodDescription(joinPoint));  
  263.             log.setLogtype("2"); // 日志类型 业务日志  
  264.             log.setUserip(ip);  
  265.             log.setUsername(user.getUsername());  
  266.             // log.setUserip(CommonUtill.getIp());  
  267.             log.setLogtime(DateUtils.dateTimeStr());  
  268.             log.setOther1(params);  
  269.             // 保存数据库  
  270.             logService.insert(log);  
  271.             logger.info("=====异常通知结束=====");  
  272.         } catch (Exception ex) {  
  273.             // 记录本地异常日志  
  274.             logger.error("异常信息:{}");  
  275.             logger.error(ex.getMessage());  
  276.         }  
  277.         /* ==========记录本地异常日志========== */  
  278.   
  279.         logger.error("异常方法:{}异常代码:{}异常信息:{}参数:{}");  
  280.         logger.error(joinPoint.getTarget().getClass().getName()  
  281.                 + joinPoint.getSignature().getName() + e.getClass().getName()  
  282.                 + e.getMessage() + params);  
  283.     }  
  284.   
  285.     /** 
  286.      * 获取注解中对方法的描述信息 用于service层注解 
  287.      *  
  288.      * @param joinPoint 
  289.      *            切点 
  290.      * @return 方法描述 
  291.      * @throws Exception 
  292.      */  
  293.     public static String getServiceMthodDescription(JoinPoint joinPoint)  
  294.             throws Exception {  
  295.         // 获取目标类名  
  296.         String targetName = joinPoint.getTarget().getClass().getName();  
  297.         // 获取方法名  
  298.         String methodName = joinPoint.getSignature().getName();  
  299.         // 获取相关参数  
  300.         Object[] arguments = joinPoint.getArgs();  
  301.         // 生成类对象  
  302.         Class targetClass = Class.forName(targetName);  
  303.         // 获取该类的方法  
  304.         Method[] methods = targetClass.getMethods();  
  305.         String description = "";  
  306.         for (Method method : methods) {  
  307.             if (method.getName().equals(methodName)) {  
  308.                 Class[] clazzs = method.getParameterTypes();  
  309.                 if (clazzs.length == arguments.length) {  
  310.                     description = method.getAnnotation(SystemServiceLog.class)  
  311.                             .description();  
  312.                     break;  
  313.                 }  
  314.             }  
  315.         }  
  316.         return description;  
  317.     }  
  318.   
  319.     /** 
  320.      * 获取注解中对方法的描述信息 用于Controller层注解 
  321.      *  
  322.      * @param joinPoint 
  323.      *            切点 
  324.      * @return 方法描述 
  325.      * @throws Exception 
  326.      */  
  327.     public static String getControllerMethodDescription(JoinPoint joinPoint)  
  328.             throws Exception {  
  329.         // 获取目标类名  
  330.         String targetName = joinPoint.getTarget().getClass().getName();  
  331.         // 获取方法名  
  332.         String methodName = joinPoint.getSignature().getName();  
  333.         // 获取相关参数  
  334.         Object[] arguments = joinPoint.getArgs();  
  335.         // 生成类对象  
  336.         Class targetClass = Class.forName(targetName);  
  337.         // 获取该类的方法  
  338.         Method[] methods = targetClass.getMethods();  
  339.         String description = "";  
  340.         for (Method method : methods) {  
  341.             if (method.getName().equals(methodName)) {  
  342.                 Class[] clazzs = method.getParameterTypes();  
  343.                 if (clazzs.length == arguments.length) {  
  344.                     description = method.getAnnotation(  
  345.                             SystemControllerLog.class).description();  
  346.                     break;  
  347.                 }  
  348.             }  
  349.         }  
  350.         return description;  
  351.     }  
  352. }  


 4,Controller注解类  

[java] view plain copy
  1. import java.lang.annotation.Documented;  
  2. import java.lang.annotation.Retention;  
  3. import java.lang.annotation.Target;  
  4. import java.lang.annotation.ElementType;  
  5. import java.lang.annotation.RetentionPolicy;  
  6.    
  7. @Target({ElementType.PARAMETER, ElementType.METHOD})      
  8. @Retention(RetentionPolicy.RUNTIME)      
  9. @Documented     
  10. public @interface SystemControllerLog {  
  11.     /** 标题 */  
  12.     String descripy()  default "";  
  13.    
  14. }  
5.Service注解类
[java] view plain copy
  1. @Target({ElementType.PARAMETER, ElementType.METHOD})      
  2. @Retention(RetentionPolicy.RUNTIME)      
  3. @Documented     
  4. public @interface SystemServiceLog {  
  5.     /** 标题 */  
  6.     String descripy()  default "";  
  7.    

猜你喜欢

转载自blog.csdn.net/u014756578/article/details/79657399