⭐⭐⭐ Spring Boot 项目实战 ⭐⭐⭐ Spring Cloud 项目实战
《Dubbo 实现原理与源码解析 —— 精品合集》 《Netty 实现原理与源码解析 —— 精品合集》
《Spring 实现原理与源码解析 —— 精品合集》 《MyBatis 实现原理与源码解析 —— 精品合集》
《Spring MVC 实现原理与源码解析 —— 精品合集》 《数据库实体设计合集》
《Spring Boot 实现原理与源码解析 —— 精品合集》 《Java 面试题 + Java 学习指南》

摘要: 原创出处 cnblogs.com/wm-dv/p/11735828.html 「咫尺的梦想_w」欢迎转载,保留摘要,谢谢!


🙂🙂🙂关注**微信公众号:【芋道源码】**有福利:

  1. RocketMQ / MyCAT / Sharding-JDBC 所有源码分析文章列表
  2. RocketMQ / MyCAT / Sharding-JDBC 中文注释源码 GitHub 地址
  3. 您对于源码的疑问每条留言将得到认真回复。甚至不知道如何读源码也可以请教噢
  4. 新的源码解析文章实时收到通知。每周更新一篇左右
  5. 认真的源码交流微信群。

平时我们在做项目时经常需要对一些重要功能操作记录日志,方便以后跟踪是谁在操作此功能;我们在操作某些功能时也有可能会发生异常,但是每次发生异常要定位原因我们都要到服务器去查询日志才能找到,而且也不能对发生的异常进行统计,从而改进我们的项目,要是能做个功能专门来记录操作日志和异常日志那就好了, 当然我们肯定有方法来做这件事情,而且也不会很难,我们可以在需要的方法中增加记录日志的代码,和在每个方法中增加记录异常的代码,最终把记录的日志存到数据库中。听起来好像很容易,但是我们做起来会发现,做这项工作很繁琐,而且都是在做一些重复性工作,还增加大量冗余代码,这种方式记录日志肯定是不可行的。

​ 我们以前学过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 com.hyd.zcar.cms.common.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 com.hyd.zcar.cms.common.utils.aop;
2
3 import java.lang.reflect.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.aspectj.lang.reflect.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.springframework.web.context.request.RequestAttributes;
20 import org.springframework.web.context.request.RequestContextHolder;
21
22 import com.gexin.fastjson.JSON;
23 import com.hyd.zcar.cms.common.utils.IPUtil;
24 import com.hyd.zcar.cms.common.utils.annotation.OperLog;
25 import com.hyd.zcar.cms.common.utils.base.UuidUtil;
26 import com.hyd.zcar.cms.common.utils.security.UserShiroUtil;
27 import com.hyd.zcar.cms.entity.system.log.ExceptionLog;
28 import com.hyd.zcar.cms.entity.system.log.OperationLog;
29 import com.hyd.zcar.cms.service.system.log.ExceptionLogService;
30 import com.hyd.zcar.cms.service.system.log.OperationLogService;
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(com.hyd.zcar.cms.common.utils.annotation.OperLog)")
61 public void operLogPoinCut() {
62 }
63
64 /**
65 * 设置操作异常切入点记录异常日志 扫描所有controller包下操作
66 */
67 @Pointcut("execution(* com.hyd.zcar.cms.controller..*.*(..))")
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 = RequestContextHolder.getRequestAttributes();
81 // 从获取RequestAttributes中获取HttpServletRequest的信息
82 HttpServletRequest request = (HttpServletRequest) requestAttributes
83 .resolveReference(RequestAttributes.REFERENCE_REQUEST);
84
85 OperationLog operlog = new OperationLog();
86 try {
87 operlog.setOperId(UuidUtil.get32UUID()); // 主键ID
88
89 // 从切面织入点处通过反射机制获取织入点处的方法
90 MethodSignature signature = (MethodSignature) joinPoint.getSignature();
91 // 获取切入点所在的方法
92 Method method = signature.getMethod();
93 // 获取操作
94 OperLog opLog = method.getAnnotation(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 = joinPoint.getTarget().getClass().getName();
105 // 获取请求的方法名
106 String methodName = method.getName();
107 methodName = className + "." + methodName;
108
109 operlog.setOperMethod(methodName); // 请求方法
110
111 // 请求的参数
112 Map<String, String> rtnMap = converMap(request.getParameterMap());
113 // 将参数所在的数组转换成json
114 String params = JSON.toJSONString(rtnMap);
115
116 operlog.setOperRequParam(params); // 请求参数
117 operlog.setOperRespParam(JSON.toJSONString(keys)); // 返回结果
118 operlog.setOperUserId(UserShiroUtil.getCurrentUserLoginName()); // 请求用户ID
119 operlog.setOperUserName(UserShiroUtil.getCurrentUserName()); // 请求用户名称
120 operlog.setOperIp(IPUtil.getRemortIP(request)); // 请求IP
121 operlog.setOperUri(request.getRequestURI()); // 请求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 = RequestContextHolder.getRequestAttributes();
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) joinPoint.getSignature();
148 // 获取切入点所在的方法
149 Method method = signature.getMethod();
150 excepLog.setExcId(UuidUtil.get32UUID());
151 // 获取请求的类名
152 String className = joinPoint.getTarget().getClass().getName();
153 // 获取请求的方法名
154 String methodName = method.getName();
155 methodName = className + "." + methodName;
156 // 请求的参数
157 Map<String, String> rtnMap = converMap(request.getParameterMap());
158 // 将参数所在的数组转换成json
159 String params = JSON.toJSONString(rtnMap);
160 excepLog.setExcRequParam(params); // 请求参数
161 excepLog.setOperMethod(methodName); // 请求方法名
162 excepLog.setExcName(e.getClass().getName()); // 异常名称
163 excepLog.setExcMessage(stackTraceToString(e.getClass().getName(), e.getMessage(), e.getStackTrace())); // 异常信息
164 excepLog.setOperUserId(UserShiroUtil.getCurrentUserLoginName()); // 操作员ID
165 excepLog.setOperUserName(UserShiroUtil.getCurrentUserName()); // 操作员名称
166 excepLog.setOperUri(request.getRequestURI()); // 操作URI
167 excepLog.setOperIp(IPUtil.getRemortIP(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, paramMap.get(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" + strbuff.toString();
205 return message;
206 }
207 }

五、在Controller层方法添加@OperLog注解

六、操作日志、异常日志查询功能

文章目录
  1. 1. 一、创建日志记录表、异常日志表,表结构如下:
  2. 2. 二、添加Maven依赖
  3. 3. 三、创建操作日志注解类OperLog.java
  4. 4. 四、创建切面类记录操作日志
  5. 5. 五、在Controller层方法添加@OperLog注解
  6. 6. 六、操作日志、异常日志查询功能