Spring AOP自定义注解实现日志管理

转载:https://blog.csdn.net/l1028386804/article/details/80295737

1、定义日志类SystemLog

[java]  view plain  copy
  1. package io.mykit.annotation.spring.log.entity;  
  2.   
  3. import java.util.Date;  
  4.   
  5. /** 
  6.  * 定义日志实体信息 
  7.  * @author liuyazhuang 
  8.  * 
  9.  */  
  10. public class SystemLog {  
  11.   
  12.     private String id;  
  13.   
  14.     private String description;  
  15.   
  16.     private String method;  
  17.   
  18.     private Long logType;  
  19.   
  20.     private String requestIp;  
  21.   
  22.     private String exceptioncode;  
  23.   
  24.     private String exceptionDetail;  
  25.   
  26.     private String params;  
  27.   
  28.     private String createBy;  
  29.   
  30.     private Date createDate;  
  31.   
  32.     public String getId() {  
  33.         return id;  
  34.     }  
  35.   
  36.     public void setId(String id) {  
  37.         this.id = id == null ? null : id.trim();  
  38.     }  
  39.   
  40.     public String getDescription() {  
  41.         return description;  
  42.     }  
  43.   
  44.     public void setDescription(String description) {  
  45.         this.description = description == null ? null : description.trim();  
  46.     }  
  47.   
  48.     public String getMethod() {  
  49.         return method;  
  50.     }  
  51.   
  52.     public void setMethod(String method) {  
  53.         this.method = method == null ? null : method.trim();  
  54.     }  
  55.   
  56.     public Long getLogType() {  
  57.         return logType;  
  58.     }  
  59.   
  60.     public void setLogType(Long logType) {  
  61.         this.logType = logType;  
  62.     }  
  63.   
  64.     public String getRequestIp() {  
  65.         return requestIp;  
  66.     }  
  67.   
  68.     public void setRequestIp(String requestIp) {  
  69.         this.requestIp = requestIp == null ? null : requestIp.trim();  
  70.     }  
  71.   
  72.     public String getExceptioncode() {  
  73.         return exceptioncode;  
  74.     }  
  75.   
  76.     public void setExceptioncode(String exceptioncode) {  
  77.         this.exceptioncode = exceptioncode == null ? null : exceptioncode.trim();  
  78.     }  
  79.   
  80.     public String getExceptionDetail() {  
  81.         return exceptionDetail;  
  82.     }  
  83.   
  84.     public void setExceptionDetail(String exceptionDetail) {  
  85.         this.exceptionDetail = exceptionDetail == null ? null : exceptionDetail.trim();  
  86.     }  
  87.   
  88.     public String getParams() {  
  89.         return params;  
  90.     }  
  91.   
  92.     public void setParams(String params) {  
  93.         this.params = params == null ? null : params.trim();  
  94.     }  
  95.   
  96.     public String getCreateBy() {  
  97.         return createBy;  
  98.     }  
  99.   
  100.     public void setCreateBy(String createBy) {  
  101.         this.createBy = createBy == null ? null : createBy.trim();  
  102.     }  
  103.   
  104.     public Date getCreateDate() {  
  105.         return createDate;  
  106.     }  
  107.   
  108.     public void setCreateDate(Date createDate) {  
  109.         this.createDate = createDate;  
  110.     }  
  111.   
  112.     @Override  
  113.     public String toString() {  
  114.         return "SystemLog [id=" + id + ", description=" + description + ", method=" + method + ", logType=" + logType  
  115.                 + ", requestIp=" + requestIp + ", exceptioncode=" + exceptioncode + ", exceptionDetail="  
  116.                 + exceptionDetail + ", params=" + params + ", createBy=" + createBy + ", createDate=" + createDate  
  117.                 + "]";  
  118.     }  
  119.       
  120. }  

2、定义SystemLogService接口

[java]  view plain  copy
  1. package io.mykit.annotation.spring.log.service;  
  2.   
  3. import io.mykit.annotation.spring.log.entity.SystemLog;  
  4.   
  5. /** 
  6.  * 日志的Service接口 
  7.  * @author liuyazhuang 
  8.  * 
  9.  */  
  10. public interface SystemLogService {  
  11.   
  12.     int deleteSystemLog(String id);  
  13.   
  14.     int insert(SystemLog record);  
  15.       
  16.     int insertTest(SystemLog record);  
  17.   
  18.     SystemLog selectSystemLog(String id);  
  19.       
  20.     int updateSystemLog(SystemLog record);  
  21. }  

3、接口实现类SystemLogServiceImpl

[java]  view plain  copy
  1. package io.mykit.annotation.spring.log.service.impl;  
  2.   
  3. import java.util.Date;  
  4. import java.util.UUID;  
  5.   
  6. import org.slf4j.Logger;  
  7. import org.slf4j.LoggerFactory;  
  8. import org.springframework.stereotype.Service;  
  9.   
  10. import io.mykit.annotation.spring.log.entity.SystemLog;  
  11. import io.mykit.annotation.spring.log.service.SystemLogService;  
  12.   
  13. @Service("systemLogService")  
  14. public class SystemLogServiceImpl implements SystemLogService {  
  15.       
  16.     private final Logger logger = LoggerFactory.getLogger(SystemLogServiceImpl.class);  
  17.       
  18.     @Override  
  19.     public int deleteSystemLog(String id) {  
  20.         logger.info("deleteSystemLog===>>>" + id);  
  21.         return 1;  
  22.     }  
  23.   
  24.     @Override  
  25.     public int insert(SystemLog record) {  
  26.         logger.info("insert===>>>" + record.toString());  
  27.         return 1;  
  28.     }  
  29.   
  30.     @Override  
  31.     public int insertTest(SystemLog record) {  
  32.         logger.info("insertTest===>>>" + record.toString());  
  33.         return 1;  
  34.     }  
  35.   
  36.     @Override  
  37.     public SystemLog selectSystemLog(String id) {  
  38.         logger.info("selectSystemLog===>>>" + id);  
  39.         SystemLog log = new SystemLog();    
  40.         log.setId(UUID.randomUUID().toString());  
  41.         log.setDescription("查询日志");    
  42.         log.setMethod("selectSystemLog");    
  43.         log.setLogType((long)0);    
  44.         log.setRequestIp("127.0.0.1");    
  45.         log.setExceptioncode( null);    
  46.         log.setExceptionDetail( null);    
  47.         log.setParams( null);    
  48.         log.setCreateBy("刘亚壮");    
  49.         log.setCreateDate(new Date());   
  50.         return log;  
  51.     }  
  52.   
  53.     @Override  
  54.     public int updateSystemLog(SystemLog record) {  
  55.         logger.info("updateSystemLog===>>>" + record.toString());  
  56.         return 1;  
  57.     }  
  58. }  

4、自定义注解Log

[java]  view plain  copy
  1. package io.mykit.annotation.spring.log.provider;  
  2.   
  3. import java.lang.annotation.Documented;  
  4. import java.lang.annotation.ElementType;  
  5. import java.lang.annotation.Retention;  
  6. import java.lang.annotation.RetentionPolicy;  
  7. import java.lang.annotation.Target;  
  8.   
  9. /** 
  10.  * 自定义日志注解 
  11.  * @author liuyazhuang 
  12.  * 
  13.  */  
  14. @Target({ElementType.PARAMETER, ElementType.METHOD})    
  15. @Retention(RetentionPolicy.RUNTIME)    
  16. @Documented    
  17. public @interface Log {  
  18.   
  19.     /** 要执行的操作类型比如:add操作 **/    
  20.     public String operationType() default "";    
  21.        
  22.     /** 要执行的具体操作比如:添加用户 **/    
  23.     public String operationName() default "";  
  24. }  

5、实现注解解析器SystemLogAspect

[java]  view plain  copy
  1. package io.mykit.annotation.spring.log.aspect;  
  2.   
  3. import java.lang.reflect.Method;  
  4. import java.util.Date;  
  5. import java.util.UUID;  
  6.   
  7. import javax.annotation.Resource;  
  8.   
  9. import org.aspectj.lang.JoinPoint;  
  10. import org.aspectj.lang.ProceedingJoinPoint;  
  11. import org.aspectj.lang.annotation.After;  
  12. import org.aspectj.lang.annotation.AfterReturning;  
  13. import org.aspectj.lang.annotation.AfterThrowing;  
  14. import org.aspectj.lang.annotation.Around;  
  15. import org.aspectj.lang.annotation.Aspect;  
  16. import org.aspectj.lang.annotation.Before;  
  17. import org.aspectj.lang.annotation.Pointcut;  
  18. import org.slf4j.Logger;  
  19. import org.slf4j.LoggerFactory;  
  20. import org.springframework.stereotype.Component;  
  21.   
  22. import com.alibaba.fastjson.JSONObject;  
  23.   
  24. import io.mykit.annotation.spring.log.entity.SystemLog;  
  25. import io.mykit.annotation.spring.log.entity.User;  
  26. import io.mykit.annotation.spring.log.provider.Log;  
  27. import io.mykit.annotation.spring.log.service.SystemLogService;  
  28.   
  29.   
  30. /** 
  31.  * 具体切片类的实现 
  32.  * @author liuyazhuang 
  33.  * 
  34.  */  
  35. @Aspect  
  36. @Component  
  37. public class SystemLogAspect {  
  38.   
  39.     //注入Service用于把日志保存数据库    
  40.     @Resource  //这里我用resource注解,一般用的是@Autowired,他们的区别如有时间我会在后面的博客中来写  
  41.     private SystemLogService systemLogService;    
  42.       
  43.     private static final Logger logger = LoggerFactory.getLogger(SystemLogAspect. class);    
  44.       
  45.     //Controller层切点    
  46.     @Pointcut("execution (* io.mykit.annotation.spring.log.user.service..*.*(..))")    
  47.     public  void controllerAspect() {    
  48.     }    
  49.       
  50.     /**  
  51.      * 前置通知 用于拦截Controller层记录用户的操作  
  52.      *  
  53.      * @param joinPoint 切点  
  54.      */   
  55.     @Before("controllerAspect()")  
  56.     public void doBefore(JoinPoint joinPoint) {  
  57.         System.out.println("==========执行controller前置通知===============");  
  58.         if(logger.isInfoEnabled()){  
  59.             logger.info("before " + joinPoint);  
  60.         }  
  61.     }      
  62.       
  63.     //配置controller环绕通知,使用在方法aspect()上注册的切入点  
  64.       @Around("controllerAspect()")  
  65.       public void around(JoinPoint joinPoint){  
  66.           System.out.println("==========开始执行controller环绕通知===============");  
  67.           long start = System.currentTimeMillis();  
  68.           try {  
  69.               ((ProceedingJoinPoint) joinPoint).proceed();  
  70.               long end = System.currentTimeMillis();  
  71.               if(logger.isInfoEnabled()){  
  72.                   logger.info("around " + joinPoint + "\tUse time : " + (end - start) + " ms!");  
  73.               }  
  74.               System.out.println("==========结束执行controller环绕通知===============");  
  75.           } catch (Throwable e) {  
  76.               long end = System.currentTimeMillis();  
  77.               if(logger.isInfoEnabled()){  
  78.                   logger.info("around " + joinPoint + "\tUse time : " + (end - start) + " ms with exception : " + e.getMessage());  
  79.               }  
  80.           }  
  81.       }  
  82.       
  83.     /**  
  84.      * 后置通知 用于拦截Controller层记录用户的操作  
  85.      *  
  86.      * @param joinPoint 切点  
  87.      */    
  88.     @SuppressWarnings("rawtypes")  
  89.     @After("controllerAspect()")    
  90.     public  void after(JoinPoint joinPoint) {    
  91.     
  92.        /* HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();   
  93.         HttpSession session = request.getSession();  */  
  94.         //读取session中的用户    
  95.        // User user = (User) session.getAttribute("user");    
  96.         //请求的IP    
  97.         //String ip = request.getRemoteAddr();  
  98.         User user = new User();  
  99.         user.setId(1);  
  100.         user.setName("刘亚壮");  
  101.         String ip = "127.0.0.1";  
  102.          try {    
  103.             String targetName = joinPoint.getTarget().getClass().getName();    
  104.             String methodName = joinPoint.getSignature().getName();    
  105.             Object[] arguments = joinPoint.getArgs();    
  106.             Class targetClass = Class.forName(targetName);    
  107.             Method[] methods = targetClass.getMethods();  
  108.             String operationType = "";  
  109.             String operationName = "";  
  110.              for (Method method : methods) {    
  111.                  if (method.getName().equals(methodName)) {    
  112.                     Class[] clazzs = method.getParameterTypes();    
  113.                      if (clazzs.length == arguments.length) {    
  114.                          if(method.isAnnotationPresent(Log.class)){  
  115.                              operationType = method.getAnnotation(Log.class).operationType();  
  116.                              operationName = method.getAnnotation(Log.class).operationName();  
  117.                              break;    
  118.                          }  
  119.                     }    
  120.                 }    
  121.             }  
  122.             //*========控制台输出=========*//    
  123.             System.out.println("=====controller后置通知开始=====");    
  124.             System.out.println("请求方法:" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()")+"."+operationType);    
  125.             System.out.println("方法描述:" + operationName);    
  126.             System.out.println("请求人:" + user.getName());    
  127.             System.out.println("请求IP:" + ip);    
  128.             //*========数据库日志=========*//    
  129.             SystemLog log = new SystemLog();    
  130.             log.setId(UUID.randomUUID().toString());  
  131.             log.setDescription(operationName);    
  132.             log.setMethod((joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()")+"."+operationType);    
  133.             log.setLogType((long)0);    
  134.             log.setRequestIp(ip);    
  135.             log.setExceptioncode( null);    
  136.             log.setExceptionDetail( null);    
  137.             log.setParams( null);    
  138.             log.setCreateBy(user.getName());    
  139.             log.setCreateDate(new Date());    
  140.             //保存数据库    
  141.             systemLogService.insert(log);    
  142.             System.out.println("=====controller后置通知结束=====");    
  143.         }  catch (Exception e) {    
  144.             //记录本地异常日志    
  145.             logger.error("==后置通知异常==");    
  146.             logger.error("异常信息:{}", e.getMessage());    
  147.         }    
  148.     }   
  149.       
  150.     //配置后置返回通知,使用在方法aspect()上注册的切入点  
  151.       @AfterReturning("controllerAspect()")  
  152.       public void afterReturn(JoinPoint joinPoint){  
  153.           System.out.println("=====执行controller后置返回通知=====");    
  154.               if(logger.isInfoEnabled()){  
  155.                   logger.info("afterReturn " + joinPoint);  
  156.               }  
  157.       }  
  158.       
  159.     /**  
  160.      * 异常通知 用于拦截记录异常日志  
  161.      *  
  162.      * @param joinPoint  
  163.      * @param e  
  164.      */    
  165.      @AfterThrowing(pointcut = "controllerAspect()", throwing="e")    
  166.      public  void doAfterThrowing(JoinPoint joinPoint, Throwable e) {    
  167.         /*HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();   
  168.         HttpSession session = request.getSession();   
  169.         //读取session中的用户   
  170.         User user = (User) session.getAttribute(WebConstants.CURRENT_USER);   
  171.         //获取请求ip   
  172.         String ip = request.getRemoteAddr(); */   
  173.         //获取用户请求方法的参数并序列化为JSON格式字符串    
  174.           
  175.         User user = new User();  
  176.         user.setId(1);  
  177.         user.setName("刘亚壮");  
  178.         String ip = "127.0.0.1";  
  179.         String params = "";    
  180.          if (joinPoint.getArgs() !=  null && joinPoint.getArgs().length > 0) {    
  181.              for ( int i = 0; i < joinPoint.getArgs().length; i++) {    
  182. //                params += JsonUtil.getJsonStr(joinPoint.getArgs()[i]) + ";";    
  183.                 params += JSONObject.toJSONString(joinPoint.getArgs()[i]) + ";";   
  184.             }    
  185.         }    
  186.          try {    
  187.              String targetName = joinPoint.getTarget().getClass().getName();    
  188.              String methodName = joinPoint.getSignature().getName();    
  189.              Object[] arguments = joinPoint.getArgs();    
  190.              Class targetClass = Class.forName(targetName);    
  191.              Method[] methods = targetClass.getMethods();  
  192.              String operationType = "";  
  193.              String operationName = "";  
  194.               for (Method method : methods) {    
  195.                   if (method.getName().equals(methodName)) {    
  196.                      Class[] clazzs = method.getParameterTypes();    
  197.                       if (clazzs.length == arguments.length) {    
  198.                           if(method.isAnnotationPresent(Log.class)){  
  199.                               operationType = method.getAnnotation(Log.class).operationType();  
  200.                               operationName = method.getAnnotation(Log.class).operationName();  
  201.                               break;    
  202.                           }  
  203.                      }    
  204.                  }    
  205.              }  
  206.             /*========控制台输出=========*/    
  207.             System.out.println("=====异常通知开始=====");    
  208.             System.out.println("异常代码:" + e.getClass().getName());    
  209.             System.out.println("异常信息:" + e.getMessage());    
  210.             System.out.println("异常方法:" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()")+"."+operationType);    
  211.             System.out.println("方法描述:" + operationName);    
  212.             System.out.println("请求人:" + user.getName());    
  213.             System.out.println("请求IP:" + ip);    
  214.             System.out.println("请求参数:" + params);    
  215.                /*==========数据库日志=========*/    
  216.             SystemLog log = new SystemLog();  
  217.             log.setId(UUID.randomUUID().toString());  
  218.             log.setDescription(operationName);    
  219.             log.setExceptioncode(e.getClass().getName());    
  220.             log.setLogType((long)1);    
  221.             log.setExceptionDetail(e.getMessage());    
  222.             log.setMethod((joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()"));    
  223.             log.setParams(params);    
  224.             log.setCreateBy(user.getName());    
  225.             log.setCreateDate(new Date());    
  226.             log.setRequestIp(ip);    
  227.             //保存数据库    
  228.             systemLogService.insert(log);    
  229.             System.out.println("=====异常通知结束=====");    
  230.         }  catch (Exception ex) {    
  231.             //记录本地异常日志    
  232.             logger.error("==异常通知异常==");    
  233.             logger.error("异常信息:{}", ex.getMessage());    
  234.         }    
  235.          /*==========记录本地异常日志==========*/    
  236.         logger.error("异常方法:{}异常代码:{}异常信息:{}参数:{}", joinPoint.getTarget().getClass().getName() + joinPoint.getSignature().getName(), e.getClass().getName(), e.getMessage(), params);    
  237.     
  238.     }    
  239.       
  240. }  

6、实现User实体类

[java]  view plain  copy
  1. package io.mykit.annotation.spring.log.entity;  
  2.   
  3. /** 
  4.  * 测试AOP切面的类 
  5.  * @author liuyazhuang 
  6.  * 
  7.  */  
  8. public class User {  
  9.       
  10.     private Integer id;  
  11.     private String name;  
  12.       
  13.     public Integer getId() {  
  14.         return id;  
  15.     }  
  16.     public void setId(Integer id) {  
  17.         this.id = id;  
  18.     }  
  19.     public String getName() {  
  20.         return name;  
  21.     }  
  22.     public void setName(String name) {  
  23.         this.name = name;  
  24.     }  
  25.     @Override  
  26.     public String toString() {  
  27.         return "User [id=" + id + ", name=" + name + "]";  
  28.     }  
  29. }  

7、定义UserService接口

[java]  view plain  copy
  1. package io.mykit.annotation.spring.log.user.service;  
  2.   
  3. /** 
  4.  * 日志切面的UserService 
  5.  * @author liuyazhuang 
  6.  * 
  7.  */  
  8. public interface UserService {  
  9.       
  10.     void addUser();  
  11. }  

8、接口实现类UserServiceImpl

我们在这个类上加上了注解@Log(operationType="add操作", operationName = "添加用户")

[java]  view plain  copy
  1. package io.mykit.annotation.spring.log.user.service.impl;  
  2.   
  3. import org.slf4j.Logger;  
  4. import org.slf4j.LoggerFactory;  
  5. import org.springframework.stereotype.Service;  
  6.   
  7. import io.mykit.annotation.spring.log.provider.Log;  
  8. import io.mykit.annotation.spring.log.user.service.UserService;  
  9.   
  10. @Service("logUserService")  
  11. public class UserServiceImpl implements UserService {  
  12.     private final Logger logger  = LoggerFactory.getLogger(UserServiceImpl.class);  
  13.     @Override  
  14.     @Log(operationType="add操作", operationName = "添加用户")  
  15.     public void addUser() {  
  16.         logger.info("执行了添加用户的操作");  
  17.     }  
  18. }  

9、spring-log-annotation.xml

[html]  view plain  copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.        xmlns:p="http://www.springframework.org/schema/p"  
  5.        xmlns:context="http://www.springframework.org/schema/context"  
  6.        xmlns:aop="http://www.springframework.org/schema/aop"   
  7.        xmlns:tx="http://www.springframework.org/schema/tx"  
  8.        xmlns:mvc="http://www.springframework.org/schema/mvc"  
  9.        xmlns:cache="http://www.springframework.org/schema/cache"  
  10.        xmlns:task="http://www.springframework.org/schema/task"  
  11.        xsi:schemaLocation="http://www.springframework.org/schema/beans  
  12.                         http://www.springframework.org/schema/beans/spring-beans-4.0.xsd  
  13.                         http://www.springframework.org/schema/context   
  14.                         http://www.springframework.org/schema/context/spring-context-4.0.xsd  
  15.                         http://www.springframework.org/schema/tx   
  16.                         http://www.springframework.org/schema/tx/spring-tx-4.0.xsd  
  17.                         http://www.springframework.org/schema/aop   
  18.                         http://www.springframework.org/schema/aop/spring-aop-4.0.xsd  
  19.                         http://www.springframework.org/schema/mvc   
  20.                         http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd  
  21.                         http://www.springframework.org/schema/cache   
  22.                         http://www.springframework.org/schema/cache/spring-cache-4.0.xsd  
  23.                         http://www.springframework.org/schema/task  http://www.springframework.org/schema/task/spring-task-4.0.xsd"  
  24.                         default-autowire="byName">  
  25.      <mvc:annotation-driven />  
  26.      <!-- 激活组件扫描功能,在包io.mykit.annotation.spring.log及其子包下面自动扫描通过注解配置的组件 -->  
  27.      <context:component-scan base-package="io.mykit.annotation.spring.log" />   
  28.       
  29.      <!-- 启动对@AspectJ注解的支持 -->  
  30.      <!-- proxy-target-class等于true是强制使用cglib代理,proxy-target-class默认是false,如果你的类实现了接口 就走JDK代理,如果没有走cglib代理  -->  
  31.      <!-- 注:对于单利模式建议使用cglib代理,虽然JDK动态代理比cglib代理速度快,但性能不如cglib -->  
  32.      <aop:aspectj-autoproxy proxy-target-class="true"/>  
  33.      <context:annotation-config />  
  34.      <bean id="systemLogAspect" class="io.mykit.annotation.spring.log.aspect.SystemLogAspect"/>   
  35. </beans>  

10、测试类LogAnnotationTest

[java]  view plain  copy
  1. package io.mykit.annotation.spring.log.provider;  
  2.   
  3. import org.junit.Test;  
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  5.   
  6. import io.mykit.annotation.spring.log.user.service.UserService;  
  7.   
  8. /** 
  9.  * 测试日志注解信息 
  10.  * @author liuyazhuang 
  11.  * 
  12.  */  
  13. public class LogAnnotationTest {  
  14.       
  15.     @SuppressWarnings("resource")  
  16.     @Test  
  17.     public void testLogAnnotation(){  
  18.         ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"spring/spring-log-annotation.xml"});  
  19.         UserService userService = (UserService) context.getBean("logUserService");  
  20.         userService.addUser();  
  21.     }  
  22. }  

11、pom.xml的Jar包依赖

[html]  view plain  copy
  1. <properties>  
  2.     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  
  3.     <skip_maven_deploy>false</skip_maven_deploy>  
  4.     <jdk.version>1.8</jdk.version>  
  5.     <spring.version>4.1.0.RELEASE</spring.version>  
  6. </properties>  
  7.   
  8. <dependencies>  
  9.      
  10.   <dependency>  
  11.         <groupId>org.springframework</groupId>  
  12.         <artifactId>spring-expression</artifactId>  
  13.         <version>${spring.version}</version>  
  14.     </dependency>   
  15.       
  16.         <dependency>  
  17.         <groupId>org.springframework</groupId>  
  18.         <artifactId>spring-messaging</artifactId>  
  19.         <version>${spring.version}</version>  
  20.     </dependency>  
  21.       
  22.     <dependency>  
  23.         <groupId>org.springframework</groupId>  
  24.         <artifactId>spring-jms</artifactId>  
  25.         <version>${spring.version}</version>  
  26.     </dependency>  
  27.       
  28.     <dependency>  
  29.         <groupId>org.springframework</groupId>  
  30.         <artifactId>spring-aop</artifactId>  
  31.         <version>${spring.version}</version>  
  32.     </dependency>  
  33.       
  34.     <dependency>  
  35.         <groupId>org.springframework</groupId>  
  36.         <artifactId>spring-jdbc</artifactId>  
  37.          <version>${spring.version}</version>  
  38.     </dependency>  
  39.       
  40.      <dependency>  
  41.         <groupId>org.springframework</groupId>  
  42.         <artifactId>spring-context</artifactId>  
  43.         <version>${spring.version}</version>  
  44.     </dependency>  
  45.   
  46.     <dependency>  
  47.         <groupId>org.springframework</groupId>  
  48.         <artifactId>spring-context-support</artifactId>  
  49.         <version>${spring.version}</version>  
  50.     </dependency>  
  51.       
  52.     <dependency>  
  53.         <groupId>org.springframework</groupId>  
  54.         <artifactId>spring-web</artifactId>  
  55.         <version>${spring.version}</version>  
  56.     </dependency>  
  57.       
  58.     <dependency>  
  59.         <groupId>org.springframework</groupId>  
  60.         <artifactId>spring-webmvc</artifactId>  
  61.         <version>${spring.version}</version>  
  62.     </dependency>  
  63.       
  64.     <dependency>  
  65.         <groupId>org.aspectj</groupId>  
  66.         <artifactId>aspectjtools</artifactId>  
  67.         <version>1.9.1</version>  
  68.     </dependency>  
  69.       
  70.     <dependency>  
  71.         <groupId>javax.servlet</groupId>  
  72.         <artifactId>javax.servlet-api</artifactId>  
  73.         <version>3.0.1</version>  
  74.     </dependency>  
  75.   
  76.     <dependency>    
  77.         <groupId>org.slf4j</groupId>    
  78.         <artifactId>slf4j-log4j12</artifactId>    
  79.         <version>1.7.2</version>    
  80.     </dependency>   
  81.       
  82.       <dependency>  
  83.         <groupId>commons-logging</groupId>  
  84.         <artifactId>commons-logging</artifactId>  
  85.         <version>1.1.1</version>  
  86.     </dependency>  
  87.      <dependency>  
  88.             <groupId>cglib</groupId>  
  89.             <artifactId>cglib-nodep</artifactId>  
  90.             <version>2.1_3</version>  
  91.         </dependency>  
  92.       
  93. </dependencies>  

12、log4j.properties

[plain]  view plain  copy
  1. log4j.rootCategory=INFO,stdout,file,ERROR  
  2. #log4j.rootCategory=ERROR,stdout,file  
  3. log4j.appender.stdout=org.apache.log4j.ConsoleAppender  
  4. #log4j.appender.stdout=org.apache.log4j.FileAppender  
  5. log4j.appender.stdout.layout=org.apache.log4j.PatternLayout  
  6. log4j.appender.stdout.layout.ConversionPattern=[mykit-annotation-spring-provider]%d %p [%t] %C{1}.%M(%L) | %m%n  
  7.   
  8. #log4j.appender.file=org.apache.log4j.DailyRollingFileAppender   
  9. #log4j.appender.file.MaxFileSize=100KB  
  10. #log4j.appender.file.DatePattern = '.'yyyy-MM-dd'.log'  
  11.   
  12. log4j.appender.file=org.apache.log4j.DailyRollingFileAppender   
  13. log4j.appender.file.File=/home/mykit/logs/mykit-annotation-spring-provider/mykit-annotation-spring-provider  
  14. log4j.appender.file.DatePattern='.'yyyy-MM-dd'.log'  
  15. log4j.appender.file.layout=org.apache.log4j.PatternLayout  
  16. log4j.appender.file.layout.ConversionPattern=%-d{yyyy-MM-dd HH\:mm\:ss} [%c-%L]-[%t]-[%p] %m%n  

13、测试结果

[plain]  view plain  copy
  1. ==========开始执行controller环绕通知===============  
  2. ==========执行controller前置通知===============  
  3. [mykit-annotation-spring-provider]2018-05-12 22:58:19,617 INFO [main] SystemLogAspect.doBefore(59) | before execution(void io.mykit.annotation.spring.log.user.service.impl.UserServiceImpl.addUser())  
  4. [mykit-annotation-spring-provider]2018-05-12 22:58:19,629 INFO [main] UserServiceImpl.addUser(16) | 执行了添加用户的操作  
  5. [mykit-annotation-spring-provider]2018-05-12 22:58:19,629 INFO [main] SystemLogAspect.around(72) | around execution(void io.mykit.annotation.spring.log.user.service.impl.UserServiceImpl.addUser())    Use time : 14 ms!  
  6. ==========结束执行controller环绕通知===============  
  7. =====controller后置通知开始=====  
  8. 请求方法:io.mykit.annotation.spring.log.user.service.impl.UserServiceImpl.addUser().add操作  
  9. 方法描述:添加用户  
  10. 请求人:刘亚壮  
  11. 请求IP:127.0.0.1  
  12. [mykit-annotation-spring-provider]2018-05-12 22:58:19,912 INFO [main] SystemLogServiceImpl.insert(26) | insert===>>>SystemLog [id=dfc4415f-0151-4e3e-8268-9397ab264288, description=添加用户, method=io.mykit.annotation.spring.log.user.service.impl.UserServiceImpl.addUser().add操作, logType=0, requestIp=127.0.0.1, exceptioncode=null, exceptionDetail=null, params=null, createBy=刘亚壮, createDate=Sat May 12 22:58:19 CST 2018]  
  13. =====controller后置通知结束=====  
  14. =====执行controller后置返回通知=====  
  15. [mykit-annotation-spring-provider]2018-05-12 22:58:19,912 INFO [main] SystemLogAspect.afterReturn(155) | afterReturn execution(void io.mykit.annotation.spring.log.user.service.impl.UserServiceImpl.addUser())  

备注:

本实例中我们在具体切面实现类SystemLogAspect中打印出了相关操作日志,具体项目业务中,大家可以根据具体业务需求将日志存储到相关的数据库或者分布式文件系统中。

猜你喜欢

转载自blog.csdn.net/u011109589/article/details/80306323