使⽤SpringBootAOP记录操作⽇志、异常⽇志⼀、创建⽇志记录表、异常⽇志表,表结构如下:
⼆、添加Maven依赖
三、创建操作⽇志注解类OperLog.java
四、创建切⾯类记录操作⽇志
五、在Controller层⽅法添加@OperLog注解
六、操作⽇志、异常⽇志查询功能
平时我们在做项⽬时经常需要对⼀些重要功能操作记录⽇志,⽅便以后跟踪是谁在操作此功能;我们在操作某些功能时也有可能会发⽣异常,但是每次发⽣异常要定位原因我们都要到服务器去查询⽇志才能到,⽽且也不能对发⽣的异常进⾏统计,从⽽改进我们的项⽬,要是能做个功能专门来记录操作⽇志和异常⽇志那就好了, 当然我们肯定有⽅法来做这件事情,⽽且也不会很难,我们可以在需要的⽅法中增加记录⽇志的代码,和在每个⽅法中增加记录异常的代码,最终把记录的⽇志存到数据库中。听起来好像很容易,但是我们做起来会发现,做这项⼯作很繁琐,⽽且都是在做⼀些重复性⼯作,还增加⼤量冗余代码,这种⽅式记录⽇志肯定是不可⾏的。
我们以前学过Spring 三⼤特性,IOC(控制反转),DI(依赖注⼊),AOP(⾯向切⾯),那其中AOP的主要功能就是将⽇志记录,性能统计,安全控制,事务处理,异常处理等代码从业务逻辑代码中划分出来。今天我们就来⽤springBoot Aop 来做⽇志记录,好了,废话说了⼀⼤堆还是上货吧。
⼀、创建⽇志记录表、异常⽇志表,表结构如下:
异常⽇志表
⼆、添加Maven依赖
1 <dependency>
2    <groupId>org.springframework.boot</groupId>
3    <artifactId>spring-boot-starter-aop</artifactId>
4 </dependency>
三、创建操作⽇志注解类OperLog.java
1 package ar.cmsmon.utils.annotation;
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 wu
12  */
13 @Target(ElementType.METHOD) //注解放置的⽬标位置,METHOD是可注解在⽅法级别上
14 @Retention(RetentionPolicy.RUNTIME) //注解在哪个阶段执⾏
15 @Documented
16 public @interface OperLog {
17    String operModul() default ""; // 操作模块
18    String operType() default "";  // 操作类型
19    String operDesc() default "";  // 操作说明
20 }
四、创建切⾯类记录操作⽇志
1 package ar.cmsmon.utils.aop;
2
3 import flect.Method;
4 import java.util.Date;
5 import java.util.HashMap;
6 import java.util.Map;
7
8 import javax.servlet.http.HttpServletRequest;
9
10 import org.aspectj.lang.JoinPoint;
11 import org.aspectj.lang.annotation.AfterReturning;
12 import org.aspectj.lang.annotation.AfterThrowing;
13 import org.aspectj.lang.annotation.Aspect;
14 import org.aspectj.lang.annotation.Pointcut;
15 import org.flect.MethodSignature;
16 import org.springframework.beans.factory.annotation.Autowired;
17 import org.springframework.beans.factory.annotation.Value;
18 import org.springframework.stereotype.Component;
19 import org.t.request.RequestAttributes;
20 import org.t.request.RequestContextHolder;
21
22 in.fastjson.JSON;
23 import ar.cmsmon.utils.IPUtil;
24 import ar.cmsmon.utils.annotation.OperLog;
25 import ar.cmsmon.utils.base.UuidUtil;
26 import ar.cmsmon.utils.security.UserShiroUtil;
27 import ity.system.log.ExceptionLog;
28 import ity.system.log.OperationLog;
29 import ar.cms.service.system.log.ExceptionLogService;
30 import ar.cms.service.system.log.OperationLogService;
31
31
32 /**
33  * 切⾯处理类,操作⽇志异常⽇志记录处理
34  *
35  * @author wu
36  * @date 2019/03/21
37  */
38 @Aspect
39 @Component
40 public class OperLogAspect {
41
42    /**
43      * 操作版本号
44      * <p>
45      * 项⽬启动时从命令⾏传⼊,例如:java -jar xxx.war --version=201902
46      * </p>
47      */
48    @Value("${version}")
49    private String operVer;
50
51    @Autowired
52    private OperationLogService operationLogService;
53
54    @Autowired
55    private ExceptionLogService exceptionLogService;
56
57    /**
58      * 设置操作⽇志切⼊点记录操作⽇志在注解的位置切⼊代码
59      */
60    @Pointcut("@annotation(ar.cmsmon.utils.annotation.OperLog)")
61    public void operLogPoinCut() {
62    }
63
64    /**
65      * 设置操作异常切⼊点记录异常⽇志扫描所有controller包下操作
66      */
67    @Pointcut("execution(* ller..*.*(..))")
68    public void operExceptionLogPoinCut() {
69    }
70
71    /**
72      * 正常返回通知,拦截⽤户操作⽇志,连接点正常执⾏完成后执⾏,如果连接点抛出异常,则不会执⾏
73      *
74      * @param joinPoint 切⼊点
75      * @param keys      返回结果
76      */
77    @AfterReturning(value = "operLogPoinCut()", returning = "keys")
78    public void saveOperLog(JoinPoint joinPoint, Object keys) {
79        // 获取RequestAttributes
80        RequestAttributes requestAttributes = RequestAttributes();
81        // 从获取RequestAttributes中获取HttpServletRequest的信息
82        HttpServletRequest request = (HttpServletRequest) requestAttributes
spring ioc注解
83                .resolveReference(RequestAttributes.REFERENCE_REQUEST);
84
85        OperationLog operlog = new OperationLog();
86        try {
87            operlog.32UUID()); // 主键ID
88
89            // 从切⾯织⼊点处通过反射机制获取织⼊点处的⽅法
90            MethodSignature signature = (MethodSignature) Signature();
91            // 获取切⼊点所在的⽅法
92            Method method = Method();
93            // 获取操作
94            OperLog opLog = Annotation(OperLog.class);
95            if (opLog != null) {
96                String operModul = opLog.operModul();
97                String operType = opLog.operType();
98                String operDesc = opLog.operDesc();
99                operlog.setOperModul(operModul); // 操作模块
100                operlog.setOperType(operType); // 操作类型
101                operlog.setOperDesc(operDesc); // 操作描述
102            }
103            // 获取请求的类名
104            String className = Target().getClass().getName();
105            // 获取请求的⽅法名
106            String methodName = Name();
107            methodName = className + "." + methodName;
108
109            operlog.setOperMethod(methodName); // 请求⽅法
110
111            // 请求的参数
112            Map<String, String> rtnMap = ParameterMap());
113            // 将参数所在的数组转换成json
114            String params = JSONString(rtnMap);
115
116            operlog.setOperRequParam(params); // 请求参数
117            operlog.JSONString(keys)); // 返回结果
118            operlog.CurrentUserLoginName()); // 请求⽤户ID 119            operlog.CurrentUserName()); // 请求⽤户名称120            operlog.RemortIP(request)); // 请求IP
121            operlog.RequestURI()); // 请求URI
122            operlog.setOperCreateTime(new Date()); // 创建时间
123            operlog.setOperVer(operVer); // 操作版本
124            operationLogService.insert(operlog);
125        } catch (Exception e) {
126            e.printStackTrace();
127        }
128    }
129
130    /**
131      * 异常返回通知,⽤于拦截异常⽇志信息连接点抛出异常后执⾏
132      *
133      * @param joinPoint 切⼊点
134      * @param e        异常信息
135      */
136    @AfterThrowing(pointcut = "operExceptionLogPoinCut()", throwing = "e")
137    public void saveExceptionLog(JoinPoint joinPoint, Throwable e) {
138        // 获取RequestAttributes
139        RequestAttributes requestAttributes = RequestAttributes(); 140        // 从获取RequestAttributes中获取HttpServletRequest的信息
141        HttpServletRequest request = (HttpServletRequest) requestAttributes
142                .resolveReference(RequestAttributes.REFERENCE_REQUEST);
143
144        ExceptionLog excepLog = new ExceptionLog();
145        try {
146            // 从切⾯织⼊点处通过反射机制获取织⼊点处的⽅法
147            MethodSignature signature = (MethodSignature) Signature();
148            // 获取切⼊点所在的⽅法
149            Method method = Method();
150            excepLog.32UUID());
151            // 获取请求的类名
152            String className = Target().getClass().getName();
153            // 获取请求的⽅法名
154            String methodName = Name();
155            methodName = className + "." + methodName;
156            // 请求的参数
157            Map<String, String> rtnMap = ParameterMap());
158            // 将参数所在的数组转换成json
159            String params = JSONString(rtnMap);
160            excepLog.setExcRequParam(params); // 请求参数
161            excepLog.setOperMethod(methodName); // 请求⽅法名
162            excepLog.Class().getName()); // 异常名称
163            excepLog.setExcMessage(Class().getName(), e.getMessage(), e.getStackTrace())); // 异常信息164            excepLog.CurrentUserLoginName()); // 操作员ID
165            excepLog.CurrentUserName()); // 操作员名称
166            excepLog.RequestURI()); // 操作URI
167            excepLog.RemortIP(request)); // 操作员IP
168            excepLog.setOperVer(operVer); // 操作版本号
169            excepLog.setOperCreateTime(new Date()); // 发⽣异常时间
170
171            exceptionLogService.insert(excepLog);
172
173        } catch (Exception e2) {
174            e2.printStackTrace();
175        }
176
177    }
178
179    /**
180      * 转换request 请求参数
181      *
182      * @param paramMap request获取的参数数组
183      */
184    public Map<String, String> converMap(Map<String, String[]> paramMap) {
185        Map<String, String> rtnMap = new HashMap<String, String>();
186        for (String key : paramMap.keySet()) {
187            rtnMap.put(key, (key)[0]);
188        }
189        return rtnMap;
190    }
191
192    /**
193      * 转换异常信息为字符串
194      *
195      * @param exceptionName    异常名称
196      * @param exceptionMessage 异常信息
197      * @param elements        堆栈信息
198      */
199    public String stackTraceToString(String exceptionName, String exceptionMessage, StackTraceElement[] elements) {
200        StringBuffer strbuff = new StringBuffer();
201        for (StackTraceElement stet : elements) {
202            strbuff.append(stet + "\n");
203        }
204        String message = exceptionName + ":" + exceptionMessage + "\n\t" + String();
205        return message;
206    }
207 }
五、在Controller层⽅法添加@OperLog注解

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。