项目结构调整 x 16 : 将 monitor、sms、dict 等组件拆分出去

This commit is contained in:
YunaiV
2021-05-02 15:41:38 +08:00
parent 20066bc864
commit cf4eeab395
305 changed files with 792 additions and 552 deletions

View File

@ -0,0 +1,44 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>cn.iocoder.boot</groupId>
<artifactId>yudao-framework</artifactId>
<version>${revision}</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>yudao-spring-boot-starter-biz-operatelog</artifactId>
<packaging>jar</packaging>
<name>${artifactId}</name>
<description>操作日志</description>
<url>https://github.com/YunaiV/ruoyi-vue-pro</url>
<dependencies>
<dependency>
<groupId>cn.iocoder.boot</groupId>
<artifactId>yudao-common</artifactId>
</dependency>
<!-- Spring 核心 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!-- Web 相关 -->
<dependency>
<groupId>cn.iocoder.boot</groupId>
<artifactId>yudao-spring-boot-starter-web</artifactId>
<scope>provided</scope>
</dependency>
<!-- 工具类相关 -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,15 @@
package cn.iocoder.yudao.framework.operatelog.config;
import cn.iocoder.yudao.framework.operatelog.core.aop.OperateLogAspect;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class YudaoOperateLogAutoConfiguration {
@Bean
public OperateLogAspect operateLogAspect() {
return new OperateLogAspect();
}
}

View File

@ -0,0 +1,57 @@
package cn.iocoder.yudao.framework.operatelog.core.annotations;
import cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 操作日志注解
*
* @author 芋道源码
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface OperateLog {
// ========== 模块字段 ==========
/**
* 操作模块
*
* 为空时,会尝试读取 {@link Api#value()} 属性
*/
String module() default "";
/**
* 操作名
*
* 为空时,会尝试读取 {@link ApiOperation#value()} 属性
*/
String name() default "";
/**
* 操作分类
*
* 实际并不是数组,因为枚举不能设置 null 作为默认值
*/
OperateTypeEnum[] type() default {};
// ========== 开关字段 ==========
/**
* 是否记录操作日志
*/
boolean enable() default true;
/**
* 是否记录方法参数
*/
boolean logArgs() default true;
/**
* 是否记录方法结果的数据
*/
boolean logResultData() default true;
}

View File

@ -0,0 +1,354 @@
package cn.iocoder.yudao.framework.operatelog.core.aop;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import cn.iocoder.yudao.framework.operatelog.core.dto.OperateLogCreateReqDTO;
import cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum;
import cn.iocoder.yudao.framework.operatelog.core.service.OperateLogFrameworkService;
import cn.iocoder.yudao.framework.common.util.monitor.TracerUtils;
import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import cn.iocoder.yudao.framework.common.util.servlet.ServletUtils;
import cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;
import java.lang.reflect.Array;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.IntStream;
import static cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR;
import static cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants.SUCCESS;
/**
* 拦截使用 @OperateLog 注解,如果满足条件,则生成操作日志。
* 满足如下任一条件,则会进行记录:
* 1. 使用 @ApiOperation + 非 @GetMapping
* 2. 使用 @OperateLog 注解
*
* 但是,如果声明 @OperateLog 注解时,将 enable 属性设置为 false 时,强制不记录。
*
* @author 芋道源码
*/
@Aspect
@Slf4j
public class OperateLogAspect {
/**
* 用于记录操作内容的上下文
*
* @see OperateLogCreateReqDTO#getContent()
*/
private static final ThreadLocal<String> CONTENT = new ThreadLocal<>();
/**
* 用于记录拓展字段的上下文
*
* @see OperateLogCreateReqDTO#getExts()
*/
private static final ThreadLocal<Map<String, Object>> EXTS = new ThreadLocal<>();
@Resource
private OperateLogFrameworkService operateLogFrameworkService;
@Around("@annotation(apiOperation)")
public Object around(ProceedingJoinPoint joinPoint, ApiOperation apiOperation) throws Throwable {
// 可能也添加了 @ApiOperation 注解
OperateLog operateLog = getMethodAnnotation(joinPoint, OperateLog.class);
return around0(joinPoint, operateLog, apiOperation);
}
@Around("!@annotation(io.swagger.annotations.ApiOperation) && @annotation(operateLog)") // 兼容处理,只添加 @OperateLog 注解的情况
public Object around(ProceedingJoinPoint joinPoint, OperateLog operateLog) throws Throwable {
return around0(joinPoint, operateLog, null);
}
private Object around0(ProceedingJoinPoint joinPoint, OperateLog operateLog, ApiOperation apiOperation) throws Throwable {
// 记录开始时间
Date startTime = new Date();
try {
// 执行原有方法
Object result = joinPoint.proceed();
// 记录正常执行时的操作日志
this.log(joinPoint, operateLog, apiOperation, startTime, result, null);
return result;
} catch (Throwable exception) {
this.log(joinPoint, operateLog, apiOperation, startTime, null, exception);
throw exception;
} finally {
clearThreadLocal();
}
}
public static void setContent(String content) {
CONTENT.set(content);
}
public static void addExt(String key, Object value) {
if (EXTS.get() == null) {
EXTS.set(new HashMap<>());
}
EXTS.get().put(key, value);
}
private static void clearThreadLocal() {
CONTENT.remove();
EXTS.remove();
}
private void log(ProceedingJoinPoint joinPoint, OperateLog operateLog, ApiOperation apiOperation,
Date startTime, Object result, Throwable exception) {
try {
// 判断不记录的情况
if (!isLogEnable(joinPoint, operateLog)) {
return;
}
// 真正记录操作日志
this.log0(joinPoint, operateLog, apiOperation, startTime, result, exception);
} catch (Throwable ex) {
log.error("[log][记录操作日志时,发生异常,其中参数是 joinPoint({}) operateLog({}) apiOperation({}) result({}) exception({}) ]",
joinPoint, operateLog, apiOperation, result, exception, ex);
}
}
private void log0(ProceedingJoinPoint joinPoint, OperateLog operateLog, ApiOperation apiOperation,
Date startTime, Object result, Throwable exception) {
OperateLogCreateReqDTO operateLogDTO = new OperateLogCreateReqDTO();
// 补全通用字段
operateLogDTO.setTraceId(TracerUtils.getTraceId());
operateLogDTO.setStartTime(startTime);
// 补充用户信息
fillUserFields(operateLogDTO);
// 补全模块信息
fillModuleFields(operateLogDTO, joinPoint, operateLog, apiOperation);
// 补全请求信息
fillRequestFields(operateLogDTO);
// 补全方法信息
fillMethodFields(operateLogDTO, joinPoint, operateLog, startTime, result, exception);
// 异步记录日志
operateLogFrameworkService.createOperateLogAsync(operateLogDTO);
}
private static void fillUserFields(OperateLogCreateReqDTO operateLogDTO) {
operateLogDTO.setUserId(WebFrameworkUtils.getLoginUserId());
}
private static void fillModuleFields(OperateLogCreateReqDTO operateLogDTO,
ProceedingJoinPoint joinPoint, OperateLog operateLog, ApiOperation apiOperation) {
// module 属性
if (operateLog != null) {
operateLogDTO.setModule(operateLog.module());
}
if (StrUtil.isEmpty(operateLogDTO.getModule())) {
Api api = getClassAnnotation(joinPoint, Api.class);
if (api != null) {
// 优先读取 @API 的 name 属性
if (StrUtil.isNotEmpty(api.value())) {
operateLogDTO.setModule(api.value());
}
// 没有的话,读取 @API 的 tags 属性
if (StrUtil.isEmpty(operateLogDTO.getModule()) && ArrayUtil.isNotEmpty(api.tags())) {
operateLogDTO.setModule(api.tags()[0]);
}
}
}
// name 属性
if (operateLog != null) {
operateLogDTO.setName(operateLog.name());
}
if (StrUtil.isEmpty(operateLogDTO.getName()) && apiOperation != null) {
operateLogDTO.setName(apiOperation.value());
}
// type 属性
if (operateLog != null && ArrayUtil.isNotEmpty(operateLog.type())) {
operateLogDTO.setType(operateLog.type()[0].getType());
}
if (operateLogDTO.getType() == null) {
RequestMethod requestMethod = obtainFirstMatchRequestMethod(obtainRequestMethod(joinPoint));
OperateTypeEnum operateLogType = convertOperateLogType(requestMethod);
operateLogDTO.setType(operateLogType != null ? operateLogType.getType() : null);
}
// content 和 exts 属性
operateLogDTO.setContent(CONTENT.get());
operateLogDTO.setExts(EXTS.get());
}
private static void fillRequestFields(OperateLogCreateReqDTO operateLogDTO) {
// 获得 Request 对象
HttpServletRequest request = ServletUtils.getRequest();
if (request == null) {
return;
}
// 补全请求信息
operateLogDTO.setRequestMethod(request.getMethod());
operateLogDTO.setRequestUrl(request.getRequestURI());
operateLogDTO.setUserIp(ServletUtil.getClientIP(request));
operateLogDTO.setUserAgent(ServletUtils.getUserAgent(request));
}
private static void fillMethodFields(OperateLogCreateReqDTO operateLogDTO,
ProceedingJoinPoint joinPoint, OperateLog operateLog,
Date startTime, Object result, Throwable exception) {
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
operateLogDTO.setJavaMethod(methodSignature.toString());
if (operateLog == null || operateLog.logArgs()) {
operateLogDTO.setJavaMethodArgs(obtainMethodArgs(joinPoint));
}
if (operateLog == null || operateLog.logResultData()) {
operateLogDTO.setResultData(obtainResultData(result));
}
operateLogDTO.setDuration((int) (System.currentTimeMillis() - startTime.getTime()));
// (正常)处理 resultCode 和 resultMsg 字段
if (result != null) {
if (result instanceof CommonResult) {
CommonResult<?> commonResult = (CommonResult<?>) result;
operateLogDTO.setResultCode(commonResult.getCode());
operateLogDTO.setResultMsg(commonResult.getMsg());
} else {
operateLogDTO.setResultCode(SUCCESS.getCode());
}
}
// (异常)处理 resultCode 和 resultMsg 字段
if (exception != null) {
operateLogDTO.setResultCode(INTERNAL_SERVER_ERROR.getCode());
operateLogDTO.setResultMsg(ExceptionUtil.getRootCauseMessage(exception));
}
}
private static boolean isLogEnable(ProceedingJoinPoint joinPoint, OperateLog operateLog) {
// 有 @OperateLog 注解的情况下
if (operateLog != null) {
return operateLog.enable();
}
// 没有 @ApiOperation 注解的情况下,只记录 POST、PUT、DELETE 的情况
return obtainFirstLogRequestMethod(obtainRequestMethod(joinPoint)) != null;
}
private static RequestMethod obtainFirstLogRequestMethod(RequestMethod[] requestMethods) {
if (ArrayUtil.isEmpty(requestMethods)) {
return null;
}
return Arrays.stream(requestMethods).filter(requestMethod ->
requestMethod == RequestMethod.POST
|| requestMethod == RequestMethod.PUT
|| requestMethod == RequestMethod.DELETE)
.findFirst().orElse(null);
}
private static RequestMethod obtainFirstMatchRequestMethod(RequestMethod[] requestMethods) {
if (ArrayUtil.isEmpty(requestMethods)) {
return null;
}
// 优先,匹配最优的 POST、PUT、DELETE
RequestMethod result = obtainFirstLogRequestMethod(requestMethods);
if (result != null) {
return result;
}
// 然后,匹配次优的 GET
result = Arrays.stream(requestMethods).filter(requestMethod -> requestMethod == RequestMethod.GET)
.findFirst().orElse(null);
if (result != null) {
return result;
}
// 兜底,获得第一个
return requestMethods[0];
}
private static OperateTypeEnum convertOperateLogType(RequestMethod requestMethod) {
if (requestMethod == null) {
return null;
}
switch (requestMethod) {
case GET:
return OperateTypeEnum.GET;
case POST:
return OperateTypeEnum.CREATE;
case PUT:
return OperateTypeEnum.UPDATE;
case DELETE:
return OperateTypeEnum.DELETE;
default:
return OperateTypeEnum.OTHER;
}
}
private static RequestMethod[] obtainRequestMethod(ProceedingJoinPoint joinPoint) {
RequestMapping requestMapping = AnnotationUtils.getAnnotation( // 使用 Spring 的工具类,可以处理 @RequestMapping 别名注解
((MethodSignature) joinPoint.getSignature()).getMethod(), RequestMapping.class);
return requestMapping != null ? requestMapping.method() : new RequestMethod[]{};
}
@SuppressWarnings("SameParameterValue")
private static <T extends Annotation> T getMethodAnnotation(ProceedingJoinPoint joinPoint, Class<T> annotationClass) {
return ((MethodSignature) joinPoint.getSignature()).getMethod().getAnnotation(annotationClass);
}
@SuppressWarnings("SameParameterValue")
private static <T extends Annotation> T getClassAnnotation(ProceedingJoinPoint joinPoint, Class<T> annotationClass) {
return ((MethodSignature) joinPoint.getSignature()).getMethod().getDeclaringClass().getAnnotation(annotationClass);
}
private static String obtainMethodArgs(ProceedingJoinPoint joinPoint) {
// TODO 提升:参数脱敏和忽略
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
String[] argNames = methodSignature.getParameterNames();
Object[] argValues = joinPoint.getArgs();
// 拼接参数
Map<String, Object> args = Maps.newHashMapWithExpectedSize(argValues.length);
for (int i = 0; i < argNames.length; i++) {
String argName = argNames[i];
Object argValue = argValues[i];
// 被忽略时,标记为 ignore 字符串,避免和 null 混在一起
args.put(argName, !isIgnoreArgs(argValue) ? argValue : "[ignore]");
}
return JsonUtils.toJsonString(args);
}
private static String obtainResultData(Object result) {
// TODO 提升:结果脱敏和忽略
if (result instanceof CommonResult) {
result = ((CommonResult<?>) result).getData();
}
return JsonUtils.toJsonString(result);
}
private static boolean isIgnoreArgs(Object object) {
Class<?> clazz = object.getClass();
// 处理数组的情况
if (clazz.isArray()) {
return IntStream.range(0, Array.getLength(object))
.anyMatch(index -> isIgnoreArgs(Array.get(object, index)));
}
// 递归处理数组、Collection、Map 的情况
if (Collection.class.isAssignableFrom(clazz)) {
return ((Collection<?>) object).stream()
.anyMatch((Predicate<Object>) o -> isIgnoreArgs(object));
}
if (Map.class.isAssignableFrom(clazz)) {
return isIgnoreArgs(((Map<?, ?>) object).values());
}
// obj
return object instanceof MultipartFile
|| object instanceof HttpServletRequest
|| object instanceof HttpServletResponse;
}
}

View File

@ -0,0 +1,84 @@
package cn.iocoder.yudao.framework.operatelog.core.dto;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.Map;
/**
* 操作日志创建 Request DTO
*/
@Data
public class OperateLogCreateReqDTO {
@ApiModelProperty(value = "链路追踪编号", required = true, example = "89aca178-a370-411c-ae02-3f0d672be4ab")
@NotEmpty(message = "链路追踪编号不能为空")
private String traceId;
@ApiModelProperty(value = "用户编号", required = true, example = "1024")
@NotNull(message = "用户编号不能为空")
private Long userId;
@ApiModelProperty(value = "操作模块", required = true, example = "订单")
@NotEmpty(message = "操作模块不能为空")
private String module;
@ApiModelProperty(value = "操作名", required = true, example = "创建订单")
@NotEmpty(message = "操作名")
private String name;
@ApiModelProperty(value = "操作分类", required = true, example = "1", notes = "参见 SysOperateLogTypeEnum 枚举类")
@NotNull(message = "操作分类不能为空")
private Integer type;
@ApiModelProperty(value = "操作明细", example = "修改编号为 1 的用户信息,将性别从男改成女,将姓名从芋道改成源码。")
private String content;
@ApiModelProperty(value = "拓展字段", example = "{'orderId': 1}")
private Map<String, Object> exts;
@ApiModelProperty(value = "请求方法名", required = true, example = "GET")
@NotEmpty(message = "请求方法名不能为空")
private String requestMethod;
@ApiModelProperty(value = "请求地址", required = true, example = "/xxx/yyy")
@NotEmpty(message = "请求地址不能为空")
private String requestUrl;
@ApiModelProperty(value = "用户 IP", required = true, example = "127.0.0.1")
@NotEmpty(message = "用户 IP 不能为空")
private String userIp;
@ApiModelProperty(value = "浏览器 UserAgent", required = true, example = "Mozilla/5.0")
@NotEmpty(message = "浏览器 UserAgent 不能为空")
private String userAgent;
@ApiModelProperty(value = "Java 方法名", required = true, example = "cn.iocoder.dashboard.UserController.save(...)")
@NotEmpty(message = "Java 方法名不能为空")
private String javaMethod;
@ApiModelProperty(value = "Java 方法的参数")
private String javaMethodArgs;
@ApiModelProperty(value = "开始时间", required = true)
@NotNull(message = "开始时间不能为空")
private Date startTime;
@ApiModelProperty(value = "执行时长,单位:毫秒", required = true)
@NotNull(message = "执行时长不能为空")
private Integer duration;
@ApiModelProperty(value = "结果码", required = true)
@NotNull(message = "结果码不能为空")
private Integer resultCode;
@ApiModelProperty(value = "结果提示")
private String resultMsg;
@ApiModelProperty(value = "结果数据")
private String resultData;
}

View File

@ -0,0 +1,55 @@
package cn.iocoder.yudao.framework.operatelog.core.enums;
import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* 操作日志的操作类型
*
* @author ruoyi
*/
@Getter
@AllArgsConstructor
public enum OperateTypeEnum {
/**
* 查询
*
* 绝大多数情况下,不会记录查询动作,因为过于大量显得没有意义。
* 在有需要的时候,通过声明 {@link OperateLog} 注解来记录
*/
GET(1),
/**
* 新增
*/
CREATE(2),
/**
* 修改
*/
UPDATE(3),
/**
* 删除
*/
DELETE(4),
/**
* 导出
*/
EXPORT(5),
/**
* 导入
*/
IMPORT(6),
/**
* 其它
*
* 在无法归类时,可以选择使用其它。因为还有操作名可以进一步标识
*/
OTHER(0);
/**
* 类型
*/
private final Integer type;
}

View File

@ -0,0 +1 @@
package cn.iocoder.yudao.framework.operatelog.core;

View File

@ -0,0 +1,17 @@
package cn.iocoder.yudao.framework.operatelog.core.service;
import cn.iocoder.yudao.framework.operatelog.core.dto.OperateLogCreateReqDTO;
import java.util.concurrent.Future;
public interface OperateLogFrameworkService {
/**
* 异步记录操作日志
*
* @param reqVO 操作日志请求
* @return true: 记录成功,false: 记录失败
*/
Future<Boolean> createOperateLogAsync(OperateLogCreateReqDTO reqVO);
}

View File

@ -0,0 +1,21 @@
package cn.iocoder.yudao.framework.operatelog.core.util;
import cn.iocoder.yudao.framework.operatelog.core.aop.OperateLogAspect;
/**
* 操作日志工具类
* 目前主要的作用,是提供给业务代码,记录操作明细和拓展字段
*
* @author 芋道源码
*/
public class OperateLogUtils {
public static void setContent(String content) {
OperateLogAspect.setContent(content);
}
public static void addExt(String key, Object value) {
OperateLogAspect.addExt(key, value);
}
}

View File

@ -0,0 +1,6 @@
/**
* 用户操作日志:记录用户的操作,用于对用户的操作的审计与追溯,永久保存。
*
* @author 芋道源码
*/
package cn.iocoder.yudao.framework.operatelog;