mirror of
https://gitee.com/hhyykk/ipms-sjy.git
synced 2025-07-24 16:05:08 +08:00
Merge branch 'master-jdk21' of https://gitee.com/zhijiantianya/ruoyi-vue-pro into develop
# Conflicts: # yudao-dependencies/pom.xml # yudao-module-crm/yudao-module-crm-biz/src/main/java/cn/iocoder/yudao/module/crm/controller/admin/customer/CrmCustomerController.java # yudao-module-erp/yudao-module-erp-biz/src/main/java/cn/iocoder/yudao/module/erp/controller/admin/purchase/ErpPurchaseOrderController.java
This commit is contained in:
@ -25,7 +25,6 @@
|
||||
<module>yudao-spring-boot-starter-excel</module>
|
||||
<module>yudao-spring-boot-starter-test</module>
|
||||
|
||||
<module>yudao-spring-boot-starter-biz-operatelog</module>
|
||||
<module>yudao-spring-boot-starter-biz-tenant</module>
|
||||
<module>yudao-spring-boot-starter-biz-data-permission</module>
|
||||
<module>yudao-spring-boot-starter-biz-ip</module>
|
||||
|
@ -137,6 +137,11 @@
|
||||
<artifactId>transmittable-thread-local</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.fhs-opensource</groupId> <!-- VO 数据翻译 -->
|
||||
<artifactId>easy-trans-anno</artifactId> <!-- 默认引入的原因,方便 xxx-module-api 包使用 -->
|
||||
</dependency>
|
||||
|
||||
<!-- Test 测试相关 -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
|
@ -1,46 +0,0 @@
|
||||
package cn.iocoder.yudao.framework.common.util.spring;
|
||||
|
||||
import cn.hutool.core.bean.BeanUtil;
|
||||
import org.springframework.aop.framework.AdvisedSupport;
|
||||
import org.springframework.aop.framework.AopProxy;
|
||||
import org.springframework.aop.support.AopUtils;
|
||||
|
||||
/**
|
||||
* Spring AOP 工具类
|
||||
*
|
||||
* 参考波克尔 http://www.bubuko.com/infodetail-3471885.html 实现
|
||||
*/
|
||||
public class SpringAopUtils {
|
||||
|
||||
/**
|
||||
* 获取代理的目标对象
|
||||
*
|
||||
* @param proxy 代理对象
|
||||
* @return 目标对象
|
||||
*/
|
||||
public static Object getTarget(Object proxy) throws Exception {
|
||||
// 不是代理对象
|
||||
if (!AopUtils.isAopProxy(proxy)) {
|
||||
return proxy;
|
||||
}
|
||||
// Jdk 代理
|
||||
if (AopUtils.isJdkDynamicProxy(proxy)) {
|
||||
return getJdkDynamicProxyTargetObject(proxy);
|
||||
}
|
||||
// Cglib 代理
|
||||
return getCglibProxyTargetObject(proxy);
|
||||
}
|
||||
|
||||
private static Object getCglibProxyTargetObject(Object proxy) throws Exception {
|
||||
Object dynamicAdvisedInterceptor = BeanUtil.getFieldValue(proxy, "CGLIB$CALLBACK_0");
|
||||
AdvisedSupport advisedSupport = (AdvisedSupport) BeanUtil.getFieldValue(dynamicAdvisedInterceptor, "advised");
|
||||
return advisedSupport.getTargetSource().getTarget();
|
||||
}
|
||||
|
||||
private static Object getJdkDynamicProxyTargetObject(Object proxy) throws Exception {
|
||||
AopProxy aopProxy = (AopProxy) BeanUtil.getFieldValue(proxy, "h");
|
||||
AdvisedSupport advisedSupport = (AdvisedSupport) BeanUtil.getFieldValue(aopProxy, "advised");
|
||||
return advisedSupport.getTargetSource().getTarget();
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
package cn.iocoder.yudao.framework.common.util.spring;
|
||||
|
||||
import cn.hutool.extra.spring.SpringUtil;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* Spring 工具类
|
||||
*
|
||||
* @author 芋道源码
|
||||
*/
|
||||
public class SpringUtils extends SpringUtil {
|
||||
|
||||
/**
|
||||
* 是否为生产环境
|
||||
*
|
||||
* @return 是否生产环境
|
||||
*/
|
||||
public static boolean isProd() {
|
||||
String activeProfile = getActiveProfile();
|
||||
return Objects.equals("prod", activeProfile);
|
||||
}
|
||||
|
||||
}
|
@ -4,6 +4,8 @@ import cn.iocoder.yudao.framework.datapermission.core.annotation.DataPermission;
|
||||
import cn.iocoder.yudao.framework.datapermission.core.aop.DataPermissionContextHolder;
|
||||
import lombok.SneakyThrows;
|
||||
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
/**
|
||||
* 数据权限 Util
|
||||
*
|
||||
@ -40,4 +42,22 @@ public class DataPermissionUtils {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 忽略数据权限,执行对应的逻辑
|
||||
*
|
||||
* @param callable 逻辑
|
||||
* @return 执行结果
|
||||
*/
|
||||
@SneakyThrows
|
||||
public static <T> T executeIgnore(Callable<T> callable) {
|
||||
DataPermission dataPermission = getDisableDataPermissionDisable();
|
||||
DataPermissionContextHolder.add(dataPermission);
|
||||
try {
|
||||
// 执行 callable
|
||||
return callable.call();
|
||||
} finally {
|
||||
DataPermissionContextHolder.remove();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -522,6 +522,29 @@ id,name,type,parentId
|
||||
441931,凤岗镇,4,441900
|
||||
441932,长安镇,4,441900
|
||||
442000,中山市,3,440000
|
||||
442001,石岐街道,4,442000
|
||||
442002,东区街道,4,442000
|
||||
442003,中山港街道,4,442000
|
||||
442004,西区街道,4,442000
|
||||
442005,南区街道,4,442000
|
||||
442006,五桂山街道,4,442000
|
||||
442007,民众街道,4,442000
|
||||
442008,南朗街道,4,442000
|
||||
442009,黄圃镇,4,442000
|
||||
442010,东凤镇,4,442000
|
||||
442011,古镇镇,4,442000
|
||||
442012,沙溪镇,4,442000
|
||||
442013,坦洲镇,4,442000
|
||||
442014,港口镇,4,442000
|
||||
442015,三角镇,4,442000
|
||||
442016,横栏镇,4,442000
|
||||
442017,南头镇,4,442000
|
||||
442018,阜沙镇,4,442000
|
||||
442019,三乡镇,4,442000
|
||||
442020,板芙镇,4,442000
|
||||
442021,大涌镇,4,442000
|
||||
442022,神湾镇,4,442000
|
||||
442023,小榄镇,4,442000
|
||||
445100,潮州市,3,440000
|
||||
445200,揭阳市,3,440000
|
||||
445300,云浮市,3,440000
|
||||
|
|
@ -1,52 +0,0 @@
|
||||
<?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>${project.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>cn.iocoder.boot</groupId>
|
||||
<artifactId>yudao-module-system-api</artifactId>
|
||||
<version>${revision}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- 工具类相关 -->
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
</project>
|
@ -1,23 +0,0 @@
|
||||
package cn.iocoder.yudao.framework.operatelog.config;
|
||||
|
||||
import cn.iocoder.yudao.framework.operatelog.core.aop.OperateLogAspect;
|
||||
import cn.iocoder.yudao.framework.operatelog.core.service.OperateLogFrameworkService;
|
||||
import cn.iocoder.yudao.framework.operatelog.core.service.OperateLogFrameworkServiceImpl;
|
||||
import cn.iocoder.yudao.module.system.api.logger.OperateLogApi;
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
|
||||
@AutoConfiguration
|
||||
public class YudaoOperateLogAutoConfiguration {
|
||||
|
||||
@Bean
|
||||
public OperateLogAspect operateLogAspect() {
|
||||
return new OperateLogAspect();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public OperateLogFrameworkService operateLogFrameworkService(OperateLogApi operateLogApi) {
|
||||
return new OperateLogFrameworkServiceImpl(operateLogApi);
|
||||
}
|
||||
|
||||
}
|
@ -1,57 +0,0 @@
|
||||
package cn.iocoder.yudao.framework.operatelog.core.annotations;
|
||||
|
||||
import cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
|
||||
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 Tag#name()} 属性
|
||||
*/
|
||||
String module() default "";
|
||||
/**
|
||||
* 操作名
|
||||
*
|
||||
* 为空时,会尝试读取 {@link Operation#summary()} 属性
|
||||
*/
|
||||
String name() default "";
|
||||
/**
|
||||
* 操作分类
|
||||
*
|
||||
* 实际并不是数组,因为枚举不能设置 null 作为默认值
|
||||
*/
|
||||
OperateTypeEnum[] type() default {};
|
||||
|
||||
// ========== 开关字段 ==========
|
||||
|
||||
/**
|
||||
* 是否记录操作日志
|
||||
*/
|
||||
boolean enable() default true;
|
||||
/**
|
||||
* 是否记录方法参数
|
||||
*/
|
||||
boolean logArgs() default true;
|
||||
/**
|
||||
* 是否记录方法结果的数据
|
||||
*/
|
||||
boolean logResultData() default true;
|
||||
|
||||
}
|
@ -1,375 +0,0 @@
|
||||
package cn.iocoder.yudao.framework.operatelog.core.aop;
|
||||
|
||||
import cn.hutool.core.date.LocalDateTimeUtil;
|
||||
import cn.hutool.core.exceptions.ExceptionUtil;
|
||||
import cn.hutool.core.util.ArrayUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
|
||||
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
|
||||
import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
|
||||
import cn.iocoder.yudao.framework.common.util.monitor.TracerUtils;
|
||||
import cn.iocoder.yudao.framework.common.util.servlet.ServletUtils;
|
||||
import cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum;
|
||||
import cn.iocoder.yudao.framework.operatelog.core.service.OperateLog;
|
||||
import cn.iocoder.yudao.framework.operatelog.core.service.OperateLogFrameworkService;
|
||||
import cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils;
|
||||
import com.google.common.collect.Maps;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
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.validation.BindingResult;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import jakarta.annotation.Resource;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.lang.reflect.Array;
|
||||
import java.time.LocalDateTime;
|
||||
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 注解
|
||||
* <p>
|
||||
* 但是,如果声明 @OperateLog 注解时,将 enable 属性设置为 false 时,强制不记录。
|
||||
*
|
||||
* @author 芋道源码
|
||||
*/
|
||||
@Aspect
|
||||
@Slf4j
|
||||
public class OperateLogAspect {
|
||||
|
||||
/**
|
||||
* 用于记录操作内容的上下文
|
||||
*
|
||||
* @see OperateLog#getContent()
|
||||
*/
|
||||
private static final ThreadLocal<String> CONTENT = new ThreadLocal<>();
|
||||
/**
|
||||
* 用于记录拓展字段的上下文
|
||||
*
|
||||
* @see OperateLog#getExts()
|
||||
*/
|
||||
private static final ThreadLocal<Map<String, Object>> EXTS = new ThreadLocal<>();
|
||||
|
||||
@Resource
|
||||
private OperateLogFrameworkService operateLogFrameworkService;
|
||||
|
||||
@Around("@annotation(operation)")
|
||||
public Object around(ProceedingJoinPoint joinPoint, Operation operation) throws Throwable {
|
||||
// 可能也添加了 @ApiOperation 注解
|
||||
cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog operateLog = getMethodAnnotation(joinPoint,
|
||||
cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog.class);
|
||||
return around0(joinPoint, operateLog, operation);
|
||||
}
|
||||
|
||||
@Around("!@annotation(io.swagger.v3.oas.annotations.Operation) && @annotation(operateLog)")
|
||||
// 兼容处理,只添加 @OperateLog 注解的情况
|
||||
public Object around(ProceedingJoinPoint joinPoint,
|
||||
cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog operateLog) throws Throwable {
|
||||
return around0(joinPoint, operateLog, null);
|
||||
}
|
||||
|
||||
private Object around0(ProceedingJoinPoint joinPoint,
|
||||
cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog operateLog,
|
||||
Operation operation) throws Throwable {
|
||||
// 目前,只有管理员,才记录操作日志!所以非管理员,直接调用,不进行记录
|
||||
Integer userType = WebFrameworkUtils.getLoginUserType();
|
||||
if (!Objects.equals(userType, UserTypeEnum.ADMIN.getValue())) {
|
||||
return joinPoint.proceed();
|
||||
}
|
||||
|
||||
// 记录开始时间
|
||||
LocalDateTime startTime = LocalDateTime.now();
|
||||
try {
|
||||
// 执行原有方法
|
||||
Object result = joinPoint.proceed();
|
||||
// 记录正常执行时的操作日志
|
||||
this.log(joinPoint, operateLog, operation, startTime, result, null);
|
||||
return result;
|
||||
} catch (Throwable exception) {
|
||||
this.log(joinPoint, operateLog, operation, 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,
|
||||
cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog operateLog,
|
||||
Operation operation,
|
||||
LocalDateTime startTime, Object result, Throwable exception) {
|
||||
try {
|
||||
// 判断不记录的情况
|
||||
if (!isLogEnable(joinPoint, operateLog)) {
|
||||
return;
|
||||
}
|
||||
// 真正记录操作日志
|
||||
this.log0(joinPoint, operateLog, operation, startTime, result, exception);
|
||||
} catch (Throwable ex) {
|
||||
log.error("[log][记录操作日志时,发生异常,其中参数是 joinPoint({}) operateLog({}) apiOperation({}) result({}) exception({}) ]",
|
||||
joinPoint, operateLog, operation, result, exception, ex);
|
||||
}
|
||||
}
|
||||
|
||||
private void log0(ProceedingJoinPoint joinPoint,
|
||||
cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog operateLog,
|
||||
Operation operation,
|
||||
LocalDateTime startTime, Object result, Throwable exception) {
|
||||
OperateLog operateLogObj = new OperateLog();
|
||||
// 补全通用字段
|
||||
operateLogObj.setTraceId(TracerUtils.getTraceId());
|
||||
operateLogObj.setStartTime(startTime);
|
||||
// 补充用户信息
|
||||
fillUserFields(operateLogObj);
|
||||
// 补全模块信息
|
||||
fillModuleFields(operateLogObj, joinPoint, operateLog, operation);
|
||||
// 补全请求信息
|
||||
fillRequestFields(operateLogObj);
|
||||
// 补全方法信息
|
||||
fillMethodFields(operateLogObj, joinPoint, operateLog, startTime, result, exception);
|
||||
|
||||
// 异步记录日志
|
||||
operateLogFrameworkService.createOperateLog(operateLogObj);
|
||||
}
|
||||
|
||||
private static void fillUserFields(OperateLog operateLogObj) {
|
||||
operateLogObj.setUserId(WebFrameworkUtils.getLoginUserId());
|
||||
operateLogObj.setUserType(WebFrameworkUtils.getLoginUserType());
|
||||
}
|
||||
|
||||
private static void fillModuleFields(OperateLog operateLogObj,
|
||||
ProceedingJoinPoint joinPoint,
|
||||
cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog operateLog,
|
||||
Operation operation) {
|
||||
// module 属性
|
||||
if (operateLog != null) {
|
||||
operateLogObj.setModule(operateLog.module());
|
||||
}
|
||||
if (StrUtil.isEmpty(operateLogObj.getModule())) {
|
||||
Tag tag = getClassAnnotation(joinPoint, Tag.class);
|
||||
if (tag != null) {
|
||||
// 优先读取 @Tag 的 name 属性
|
||||
if (StrUtil.isNotEmpty(tag.name())) {
|
||||
operateLogObj.setModule(tag.name());
|
||||
}
|
||||
// 没有的话,读取 @API 的 description 属性
|
||||
if (StrUtil.isEmpty(operateLogObj.getModule()) && ArrayUtil.isNotEmpty(tag.description())) {
|
||||
operateLogObj.setModule(tag.description());
|
||||
}
|
||||
}
|
||||
}
|
||||
// name 属性
|
||||
if (operateLog != null) {
|
||||
operateLogObj.setName(operateLog.name());
|
||||
}
|
||||
if (StrUtil.isEmpty(operateLogObj.getName()) && operation != null) {
|
||||
operateLogObj.setName(operation.summary());
|
||||
}
|
||||
// type 属性
|
||||
if (operateLog != null && ArrayUtil.isNotEmpty(operateLog.type())) {
|
||||
operateLogObj.setType(operateLog.type()[0].getType());
|
||||
}
|
||||
if (operateLogObj.getType() == null) {
|
||||
RequestMethod requestMethod = obtainFirstMatchRequestMethod(obtainRequestMethod(joinPoint));
|
||||
OperateTypeEnum operateLogType = convertOperateLogType(requestMethod);
|
||||
operateLogObj.setType(operateLogType != null ? operateLogType.getType() : null);
|
||||
}
|
||||
// content 和 exts 属性
|
||||
operateLogObj.setContent(CONTENT.get());
|
||||
operateLogObj.setExts(EXTS.get());
|
||||
}
|
||||
|
||||
private static void fillRequestFields(OperateLog operateLogObj) {
|
||||
// 获得 Request 对象
|
||||
HttpServletRequest request = ServletUtils.getRequest();
|
||||
if (request == null) {
|
||||
return;
|
||||
}
|
||||
// 补全请求信息
|
||||
operateLogObj.setRequestMethod(request.getMethod());
|
||||
operateLogObj.setRequestUrl(request.getRequestURI());
|
||||
operateLogObj.setUserIp(ServletUtils.getClientIP(request));
|
||||
operateLogObj.setUserAgent(ServletUtils.getUserAgent(request));
|
||||
}
|
||||
|
||||
private static void fillMethodFields(OperateLog operateLogObj,
|
||||
ProceedingJoinPoint joinPoint,
|
||||
cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog operateLog,
|
||||
LocalDateTime startTime, Object result, Throwable exception) {
|
||||
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
|
||||
operateLogObj.setJavaMethod(methodSignature.toString());
|
||||
if (operateLog == null || operateLog.logArgs()) {
|
||||
operateLogObj.setJavaMethodArgs(obtainMethodArgs(joinPoint));
|
||||
}
|
||||
if (operateLog == null || operateLog.logResultData()) {
|
||||
operateLogObj.setResultData(obtainResultData(result));
|
||||
}
|
||||
operateLogObj.setDuration((int) (LocalDateTimeUtil.between(startTime, LocalDateTime.now()).toMillis()));
|
||||
// (正常)处理 resultCode 和 resultMsg 字段
|
||||
if (result instanceof CommonResult) {
|
||||
CommonResult<?> commonResult = (CommonResult<?>) result;
|
||||
operateLogObj.setResultCode(commonResult.getCode());
|
||||
operateLogObj.setResultMsg(commonResult.getMsg());
|
||||
} else {
|
||||
operateLogObj.setResultCode(SUCCESS.getCode());
|
||||
}
|
||||
// (异常)处理 resultCode 和 resultMsg 字段
|
||||
if (exception != null) {
|
||||
operateLogObj.setResultCode(INTERNAL_SERVER_ERROR.getCode());
|
||||
operateLogObj.setResultMsg(ExceptionUtil.getRootCauseMessage(exception));
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isLogEnable(ProceedingJoinPoint joinPoint,
|
||||
cn.iocoder.yudao.framework.operatelog.core.annotations.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>) OperateLogAspect::isIgnoreArgs);
|
||||
}
|
||||
if (Map.class.isAssignableFrom(clazz)) {
|
||||
return isIgnoreArgs(((Map<?, ?>) object).values());
|
||||
}
|
||||
// obj
|
||||
return object instanceof MultipartFile
|
||||
|| object instanceof HttpServletRequest
|
||||
|| object instanceof HttpServletResponse
|
||||
|| object instanceof BindingResult;
|
||||
}
|
||||
|
||||
}
|
@ -1 +0,0 @@
|
||||
package cn.iocoder.yudao.framework.operatelog.core;
|
@ -1,110 +0,0 @@
|
||||
package cn.iocoder.yudao.framework.operatelog.core.service;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 操作日志
|
||||
*
|
||||
* @author 芋道源码
|
||||
*/
|
||||
@Data
|
||||
public class OperateLog {
|
||||
|
||||
/**
|
||||
* 链路追踪编号
|
||||
*/
|
||||
private String traceId;
|
||||
|
||||
/**
|
||||
* 用户编号
|
||||
*/
|
||||
private Long userId;
|
||||
/**
|
||||
* 用户类型
|
||||
*/
|
||||
private Integer userType;
|
||||
|
||||
/**
|
||||
* 操作模块
|
||||
*/
|
||||
private String module;
|
||||
|
||||
/**
|
||||
* 操作名
|
||||
*/
|
||||
private String name;
|
||||
|
||||
/**
|
||||
* 操作分类
|
||||
*/
|
||||
private Integer type;
|
||||
|
||||
/**
|
||||
* 操作明细
|
||||
*/
|
||||
private String content;
|
||||
|
||||
/**
|
||||
* 拓展字段
|
||||
*/
|
||||
private Map<String, Object> exts;
|
||||
|
||||
/**
|
||||
* 请求方法名
|
||||
*/
|
||||
private String requestMethod;
|
||||
|
||||
/**
|
||||
* 请求地址
|
||||
*/
|
||||
private String requestUrl;
|
||||
|
||||
/**
|
||||
* 用户 IP
|
||||
*/
|
||||
private String userIp;
|
||||
|
||||
/**
|
||||
* 浏览器 UserAgent
|
||||
*/
|
||||
private String userAgent;
|
||||
|
||||
/**
|
||||
* Java 方法名
|
||||
*/
|
||||
private String javaMethod;
|
||||
|
||||
/**
|
||||
* Java 方法的参数
|
||||
*/
|
||||
private String javaMethodArgs;
|
||||
|
||||
/**
|
||||
* 开始时间
|
||||
*/
|
||||
private LocalDateTime startTime;
|
||||
|
||||
/**
|
||||
* 执行时长,单位:毫秒
|
||||
*/
|
||||
private Integer duration;
|
||||
|
||||
/**
|
||||
* 结果码
|
||||
*/
|
||||
private Integer resultCode;
|
||||
|
||||
/**
|
||||
* 结果提示
|
||||
*/
|
||||
private String resultMsg;
|
||||
|
||||
/**
|
||||
* 结果数据
|
||||
*/
|
||||
private String resultData;
|
||||
|
||||
}
|
@ -1,17 +0,0 @@
|
||||
package cn.iocoder.yudao.framework.operatelog.core.service;
|
||||
|
||||
/**
|
||||
* 操作日志 Framework Service 接口
|
||||
*
|
||||
* @author 芋道源码
|
||||
*/
|
||||
public interface OperateLogFrameworkService {
|
||||
|
||||
/**
|
||||
* 记录操作日志
|
||||
*
|
||||
* @param operateLog 操作日志请求
|
||||
*/
|
||||
void createOperateLog(OperateLog operateLog);
|
||||
|
||||
}
|
@ -1,28 +0,0 @@
|
||||
package cn.iocoder.yudao.framework.operatelog.core.service;
|
||||
|
||||
import cn.hutool.core.bean.BeanUtil;
|
||||
import cn.iocoder.yudao.module.system.api.logger.OperateLogApi;
|
||||
import cn.iocoder.yudao.module.system.api.logger.dto.OperateLogCreateReqDTO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.scheduling.annotation.Async;
|
||||
|
||||
/**
|
||||
* 操作日志 Framework Service 实现类
|
||||
*
|
||||
* 基于 {@link OperateLogApi} 实现,记录操作日志
|
||||
*
|
||||
* @author 芋道源码
|
||||
*/
|
||||
@RequiredArgsConstructor
|
||||
public class OperateLogFrameworkServiceImpl implements OperateLogFrameworkService {
|
||||
|
||||
private final OperateLogApi operateLogApi;
|
||||
|
||||
@Override
|
||||
@Async
|
||||
public void createOperateLog(OperateLog operateLog) {
|
||||
OperateLogCreateReqDTO reqDTO = BeanUtil.toBean(operateLog, OperateLogCreateReqDTO.class);
|
||||
operateLogApi.createOperateLog(reqDTO);
|
||||
}
|
||||
|
||||
}
|
@ -1,21 +0,0 @@
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
@ -1,6 +0,0 @@
|
||||
/**
|
||||
* 用户操作日志:记录用户的操作,用于对用户的操作的审计与追溯,永久保存。
|
||||
*
|
||||
* @author 芋道源码
|
||||
*/
|
||||
package cn.iocoder.yudao.framework.operatelog;
|
@ -1 +0,0 @@
|
||||
cn.iocoder.yudao.framework.operatelog.config.YudaoOperateLogAutoConfiguration
|
@ -1,6 +1,5 @@
|
||||
package cn.iocoder.yudao.framework.tenant.core.context;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import cn.iocoder.yudao.framework.common.enums.DocumentEnum;
|
||||
import com.alibaba.ttl.TransmittableThreadLocal;
|
||||
|
||||
@ -30,16 +29,6 @@ public class TenantContextHolder {
|
||||
return TENANT_ID.get();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得租户编号 String
|
||||
*
|
||||
* @return 租户编号
|
||||
*/
|
||||
public static String getTenantIdStr() {
|
||||
Long tenantId = getTenantId();
|
||||
return StrUtil.toStringOrNull(tenantId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得租户编号。如果不存在,则抛出 NullPointerException 异常
|
||||
*
|
||||
|
@ -77,6 +77,15 @@
|
||||
<groupId>com.github.yulichang</groupId>
|
||||
<artifactId>mybatis-plus-join-boot-starter</artifactId> <!-- MyBatis 联表查询 -->
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.fhs-opensource</groupId> <!-- VO 数据翻译 -->
|
||||
<artifactId>easy-trans-spring-boot-starter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fhs-opensource</groupId>
|
||||
<artifactId>easy-trans-mybatis-plus-extend</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
||||
|
@ -3,6 +3,8 @@ package cn.iocoder.yudao.framework.mybatis.core.dataobject;
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableLogic;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fhs.core.trans.vo.TransPojo;
|
||||
import lombok.Data;
|
||||
import org.apache.ibatis.type.JdbcType;
|
||||
|
||||
@ -12,10 +14,14 @@ import java.time.LocalDateTime;
|
||||
/**
|
||||
* 基础实体对象
|
||||
*
|
||||
* 为什么实现 {@link TransPojo} 接口?
|
||||
* 因为使用 Easy-Trans TransType.SIMPLE 模式,集成 MyBatis Plus 查询
|
||||
*
|
||||
* @author 芋道源码
|
||||
*/
|
||||
@Data
|
||||
public abstract class BaseDO implements Serializable {
|
||||
@JsonIgnoreProperties(value = "transMap") // 由于 Easy-Trans 会添加 transMap 属性,避免 Jackson 在 Spring Cache 反序列化报错
|
||||
public abstract class BaseDO implements Serializable, TransPojo {
|
||||
|
||||
/**
|
||||
* 创建时间
|
||||
|
@ -1 +0,0 @@
|
||||
package cn.iocoder.yudao.framework;
|
@ -0,0 +1,18 @@
|
||||
package cn.iocoder.yudao.framework.translate.config;
|
||||
|
||||
import cn.iocoder.yudao.framework.translate.core.TranslateUtils;
|
||||
import com.fhs.trans.service.impl.TransService;
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
|
||||
@AutoConfiguration
|
||||
public class YudaoTranslateAutoConfiguration {
|
||||
|
||||
@Bean
|
||||
@SuppressWarnings({"InstantiationOfUtilityClass", "SpringJavaInjectionPointsAutowiringInspection"})
|
||||
public TranslateUtils translateUtils(TransService transService) {
|
||||
TranslateUtils.init(transService);
|
||||
return new TranslateUtils();
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,37 @@
|
||||
package cn.iocoder.yudao.framework.translate.core;
|
||||
|
||||
import cn.hutool.core.collection.CollUtil;
|
||||
import com.fhs.core.trans.vo.VO;
|
||||
import com.fhs.trans.service.impl.TransService;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* VO 数据翻译 Utils
|
||||
*
|
||||
* @author 芋道源码
|
||||
*/
|
||||
public class TranslateUtils {
|
||||
|
||||
private static TransService transService;
|
||||
|
||||
public static void init(TransService transService) {
|
||||
TranslateUtils.transService = transService;
|
||||
}
|
||||
|
||||
/**
|
||||
* 数据翻译
|
||||
*
|
||||
* 使用场景:无法使用 @TransMethodResult 注解的场景,只能通过手动触发翻译
|
||||
*
|
||||
* @param data 数据
|
||||
* @return 翻译结果
|
||||
*/
|
||||
public static <T extends VO> List<T> translate(List<T> data) {
|
||||
if (CollUtil.isNotEmpty((data))) {
|
||||
transService.transBatch(data);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,4 @@
|
||||
/**
|
||||
* 使用 Easy-Trans 提升使用 VO 数据翻译的开发效率
|
||||
*/
|
||||
package cn.iocoder.yudao.framework.translate;
|
@ -1,2 +1,3 @@
|
||||
cn.iocoder.yudao.framework.datasource.config.YudaoDataSourceAutoConfiguration
|
||||
cn.iocoder.yudao.framework.mybatis.config.YudaoMybatisAutoConfiguration
|
||||
cn.iocoder.yudao.framework.mybatis.config.YudaoMybatisAutoConfiguration
|
||||
cn.iocoder.yudao.framework.translate.config.YudaoTranslateAutoConfiguration
|
@ -5,7 +5,7 @@ import cn.iocoder.yudao.framework.common.util.servlet.ServletUtils;
|
||||
import cn.iocoder.yudao.framework.security.core.LoginUser;
|
||||
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
|
||||
import cn.iocoder.yudao.module.system.api.logger.OperateLogApi;
|
||||
import cn.iocoder.yudao.module.system.api.logger.dto.OperateLogV2CreateReqDTO;
|
||||
import cn.iocoder.yudao.module.system.api.logger.dto.OperateLogCreateReqDTO;
|
||||
import com.mzt.logapi.beans.LogRecord;
|
||||
import com.mzt.logapi.service.ILogRecordService;
|
||||
import jakarta.annotation.Resource;
|
||||
@ -30,7 +30,7 @@ public class LogRecordServiceImpl implements ILogRecordService {
|
||||
@Override
|
||||
public void record(LogRecord logRecord) {
|
||||
// 1. 补全通用字段
|
||||
OperateLogV2CreateReqDTO reqDTO = new OperateLogV2CreateReqDTO();
|
||||
OperateLogCreateReqDTO reqDTO = new OperateLogCreateReqDTO();
|
||||
reqDTO.setTraceId(TracerUtils.getTraceId());
|
||||
// 补充用户信息
|
||||
fillUserFields(reqDTO);
|
||||
@ -40,12 +40,10 @@ public class LogRecordServiceImpl implements ILogRecordService {
|
||||
fillRequestFields(reqDTO);
|
||||
|
||||
// 2. 异步记录日志
|
||||
operateLogApi.createOperateLogV2(reqDTO);
|
||||
// TODO 测试结束删除或搞个开关
|
||||
log.info("操作日志 ===> {}", reqDTO);
|
||||
operateLogApi.createOperateLog(reqDTO);
|
||||
}
|
||||
|
||||
private static void fillUserFields(OperateLogV2CreateReqDTO reqDTO) {
|
||||
private static void fillUserFields(OperateLogCreateReqDTO reqDTO) {
|
||||
// 使用 SecurityFrameworkUtils。因为要考虑,rpc、mq、job,它其实不是 web;
|
||||
LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
|
||||
if (loginUser == null) {
|
||||
@ -55,7 +53,7 @@ public class LogRecordServiceImpl implements ILogRecordService {
|
||||
reqDTO.setUserType(loginUser.getUserType());
|
||||
}
|
||||
|
||||
public static void fillModuleFields(OperateLogV2CreateReqDTO reqDTO, LogRecord logRecord) {
|
||||
public static void fillModuleFields(OperateLogCreateReqDTO reqDTO, LogRecord logRecord) {
|
||||
reqDTO.setType(logRecord.getType()); // 大模块类型,例如:CRM 客户
|
||||
reqDTO.setSubType(logRecord.getSubType());// 操作名称,例如:转移客户
|
||||
reqDTO.setBizId(Long.parseLong(logRecord.getBizNo())); // 业务编号,例如:客户编号
|
||||
@ -63,7 +61,7 @@ public class LogRecordServiceImpl implements ILogRecordService {
|
||||
reqDTO.setExtra(logRecord.getExtra()); // 拓展字段,有些复杂的业务,需要记录一些字段 ( JSON 格式 ),例如说,记录订单编号,{ orderId: "1"}
|
||||
}
|
||||
|
||||
private static void fillRequestFields(OperateLogV2CreateReqDTO reqDTO) {
|
||||
private static void fillRequestFields(OperateLogCreateReqDTO reqDTO) {
|
||||
// 获得 Request 对象
|
||||
HttpServletRequest request = ServletUtils.getRequest();
|
||||
if (request == null) {
|
||||
|
@ -1,6 +1,7 @@
|
||||
package cn.iocoder.yudao.framework.apilog.config;
|
||||
|
||||
import cn.iocoder.yudao.framework.apilog.core.filter.ApiAccessLogFilter;
|
||||
import cn.iocoder.yudao.framework.apilog.core.interceptor.ApiAccessLogInterceptor;
|
||||
import cn.iocoder.yudao.framework.apilog.core.service.ApiAccessLogFrameworkService;
|
||||
import cn.iocoder.yudao.framework.apilog.core.service.ApiAccessLogFrameworkServiceImpl;
|
||||
import cn.iocoder.yudao.framework.apilog.core.service.ApiErrorLogFrameworkService;
|
||||
@ -10,23 +11,26 @@ import cn.iocoder.yudao.framework.web.config.WebProperties;
|
||||
import cn.iocoder.yudao.framework.web.config.YudaoWebAutoConfiguration;
|
||||
import cn.iocoder.yudao.module.infra.api.logger.ApiAccessLogApi;
|
||||
import cn.iocoder.yudao.module.infra.api.logger.ApiErrorLogApi;
|
||||
import jakarta.servlet.Filter;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.boot.web.servlet.FilterRegistrationBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
|
||||
import jakarta.servlet.Filter;
|
||||
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
@AutoConfiguration(after = YudaoWebAutoConfiguration.class)
|
||||
public class YudaoApiLogAutoConfiguration {
|
||||
public class YudaoApiLogAutoConfiguration implements WebMvcConfigurer {
|
||||
|
||||
@Bean
|
||||
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
|
||||
public ApiAccessLogFrameworkService apiAccessLogFrameworkService(ApiAccessLogApi apiAccessLogApi) {
|
||||
return new ApiAccessLogFrameworkServiceImpl(apiAccessLogApi);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
|
||||
public ApiErrorLogFrameworkService apiErrorLogFrameworkService(ApiErrorLogApi apiErrorLogApi) {
|
||||
return new ApiErrorLogFrameworkServiceImpl(apiErrorLogApi);
|
||||
}
|
||||
@ -49,4 +53,9 @@ public class YudaoApiLogAutoConfiguration {
|
||||
return bean;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addInterceptors(InterceptorRegistry registry) {
|
||||
registry.addInterceptor(new ApiAccessLogInterceptor());
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -0,0 +1,65 @@
|
||||
package cn.iocoder.yudao.framework.apilog.core.annotations;
|
||||
|
||||
import cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum;
|
||||
|
||||
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 ApiAccessLog {
|
||||
|
||||
// ========== 开关字段 ==========
|
||||
|
||||
/**
|
||||
* 是否记录访问日志
|
||||
*/
|
||||
boolean enable() default true;
|
||||
/**
|
||||
* 是否记录请求参数
|
||||
*
|
||||
* 默认记录,主要考虑请求数据一般不大。可手动设置为 false 进行关闭
|
||||
*/
|
||||
boolean requestEnable() default true;
|
||||
/**
|
||||
* 是否记录响应结果
|
||||
*
|
||||
* 默认不记录,主要考虑响应数据可能比较大。可手动设置为 true 进行打开
|
||||
*/
|
||||
boolean responseEnable() default false;
|
||||
/**
|
||||
* 敏感参数数组
|
||||
*
|
||||
* 添加后,请求参数、响应结果不会记录该参数
|
||||
*/
|
||||
String[] sanitizeKeys() default {};
|
||||
|
||||
// ========== 模块字段 ==========
|
||||
|
||||
/**
|
||||
* 操作模块
|
||||
*
|
||||
* 为空时,会尝试读取 {@link io.swagger.v3.oas.annotations.tags.Tag#name()} 属性
|
||||
*/
|
||||
String operateModule() default "";
|
||||
/**
|
||||
* 操作名
|
||||
*
|
||||
* 为空时,会尝试读取 {@link io.swagger.v3.oas.annotations.Operation#summary()} 属性
|
||||
*/
|
||||
String operateName() default "";
|
||||
/**
|
||||
* 操作分类
|
||||
*
|
||||
* 实际并不是数组,因为枚举不能设置 null 作为默认值
|
||||
*/
|
||||
OperateTypeEnum[] operateType() default {};
|
||||
|
||||
}
|
@ -1,6 +1,5 @@
|
||||
package cn.iocoder.yudao.framework.operatelog.core.enums;
|
||||
package cn.iocoder.yudao.framework.apilog.core.enums;
|
||||
|
||||
import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@ -15,9 +14,6 @@ public enum OperateTypeEnum {
|
||||
|
||||
/**
|
||||
* 查询
|
||||
*
|
||||
* 绝大多数情况下,不会记录查询动作,因为过于大量显得没有意义。
|
||||
* 在有需要的时候,通过声明 {@link OperateLog} 注解来记录
|
||||
*/
|
||||
GET(1),
|
||||
/**
|
@ -1,38 +1,56 @@
|
||||
package cn.iocoder.yudao.framework.apilog.core.filter;
|
||||
|
||||
import cn.hutool.core.collection.CollUtil;
|
||||
import cn.hutool.core.date.LocalDateTimeUtil;
|
||||
import cn.hutool.core.exceptions.ExceptionUtil;
|
||||
import cn.hutool.core.map.MapUtil;
|
||||
import cn.iocoder.yudao.framework.apilog.core.service.ApiAccessLog;
|
||||
import cn.hutool.core.util.ArrayUtil;
|
||||
import cn.hutool.core.util.BooleanUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import cn.iocoder.yudao.framework.apilog.core.annotations.ApiAccessLog;
|
||||
import cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum;
|
||||
import cn.iocoder.yudao.framework.apilog.core.service.ApiAccessLogFrameworkService;
|
||||
import cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants;
|
||||
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
|
||||
import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
|
||||
import cn.iocoder.yudao.framework.common.util.monitor.TracerUtils;
|
||||
import cn.iocoder.yudao.framework.common.util.servlet.ServletUtils;
|
||||
import cn.iocoder.yudao.framework.web.config.WebProperties;
|
||||
import cn.iocoder.yudao.framework.web.core.filter.ApiRequestFilter;
|
||||
import cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import cn.iocoder.yudao.module.infra.api.logger.dto.ApiAccessLogCreateReqDTO;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.method.HandlerMethod;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
|
||||
import static cn.iocoder.yudao.framework.apilog.core.interceptor.ApiAccessLogInterceptor.*;
|
||||
import static cn.iocoder.yudao.framework.common.util.json.JsonUtils.toJsonString;
|
||||
|
||||
/**
|
||||
* API 访问日志 Filter
|
||||
*
|
||||
* 目的:记录 API 访问日志到数据库中
|
||||
*
|
||||
* @author 芋道源码
|
||||
*/
|
||||
@Slf4j
|
||||
public class ApiAccessLogFilter extends ApiRequestFilter {
|
||||
|
||||
private static final String[] SANITIZE_KEYS = new String[]{"password", "token", "accessToken", "refreshToken"};
|
||||
|
||||
private final String applicationName;
|
||||
|
||||
private final ApiAccessLogFrameworkService apiAccessLogFrameworkService;
|
||||
@ -44,6 +62,7 @@ public class ApiAccessLogFilter extends ApiRequestFilter {
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("NullableProblems")
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
|
||||
throws ServletException, IOException {
|
||||
// 获得开始时间
|
||||
@ -66,45 +85,166 @@ public class ApiAccessLogFilter extends ApiRequestFilter {
|
||||
|
||||
private void createApiAccessLog(HttpServletRequest request, LocalDateTime beginTime,
|
||||
Map<String, String> queryString, String requestBody, Exception ex) {
|
||||
ApiAccessLog accessLog = new ApiAccessLog();
|
||||
ApiAccessLogCreateReqDTO accessLog = new ApiAccessLogCreateReqDTO();
|
||||
try {
|
||||
this.buildApiAccessLogDTO(accessLog, request, beginTime, queryString, requestBody, ex);
|
||||
boolean enable = buildApiAccessLog(accessLog, request, beginTime, queryString, requestBody, ex);
|
||||
if (!enable) {
|
||||
return;
|
||||
}
|
||||
apiAccessLogFrameworkService.createApiAccessLog(accessLog);
|
||||
} catch (Throwable th) {
|
||||
log.error("[createApiAccessLog][url({}) log({}) 发生异常]", request.getRequestURI(), toJsonString(accessLog), th);
|
||||
}
|
||||
}
|
||||
|
||||
private void buildApiAccessLogDTO(ApiAccessLog accessLog, HttpServletRequest request, LocalDateTime beginTime,
|
||||
private boolean buildApiAccessLog(ApiAccessLogCreateReqDTO accessLog, HttpServletRequest request, LocalDateTime beginTime,
|
||||
Map<String, String> queryString, String requestBody, Exception ex) {
|
||||
// 判断:是否要记录操作日志
|
||||
HandlerMethod handlerMethod = (HandlerMethod) request.getAttribute(ATTRIBUTE_HANDLER_METHOD);
|
||||
ApiAccessLog accessLogAnnotation = null;
|
||||
if (handlerMethod != null) {
|
||||
accessLogAnnotation = handlerMethod.getMethodAnnotation(ApiAccessLog.class);
|
||||
if (accessLogAnnotation != null && BooleanUtil.isFalse(accessLogAnnotation.enable())) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 处理用户信息
|
||||
accessLog.setUserId(WebFrameworkUtils.getLoginUserId(request));
|
||||
accessLog.setUserType(WebFrameworkUtils.getLoginUserType(request));
|
||||
accessLog.setUserId(WebFrameworkUtils.getLoginUserId(request))
|
||||
.setUserType(WebFrameworkUtils.getLoginUserType(request));
|
||||
// 设置访问结果
|
||||
CommonResult<?> result = WebFrameworkUtils.getCommonResult(request);
|
||||
if (result != null) {
|
||||
accessLog.setResultCode(result.getCode());
|
||||
accessLog.setResultMsg(result.getMsg());
|
||||
accessLog.setResultCode(result.getCode()).setResultMsg(result.getMsg());
|
||||
} else if (ex != null) {
|
||||
accessLog.setResultCode(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode());
|
||||
accessLog.setResultMsg(ExceptionUtil.getRootCauseMessage(ex));
|
||||
accessLog.setResultCode(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode())
|
||||
.setResultMsg(ExceptionUtil.getRootCauseMessage(ex));
|
||||
} else {
|
||||
accessLog.setResultCode(0);
|
||||
accessLog.setResultMsg("");
|
||||
accessLog.setResultCode(GlobalErrorCodeConstants.SUCCESS.getCode()).setResultMsg("");
|
||||
}
|
||||
// 设置请求字段
|
||||
accessLog.setTraceId(TracerUtils.getTraceId()).setApplicationName(applicationName)
|
||||
.setRequestUrl(request.getRequestURI()).setRequestMethod(request.getMethod())
|
||||
.setUserAgent(ServletUtils.getUserAgent(request)).setUserIp(ServletUtils.getClientIP(request));
|
||||
String[] sanitizeKeys = accessLogAnnotation != null ? accessLogAnnotation.sanitizeKeys() : null;
|
||||
Boolean requestEnable = accessLogAnnotation != null ? accessLogAnnotation.requestEnable() : Boolean.TRUE;
|
||||
if (!BooleanUtil.isFalse(requestEnable)) { // 默认记录,所以判断 !false
|
||||
Map<String, Object> requestParams = MapUtil.<String, Object>builder()
|
||||
.put("query", sanitizeMap(queryString, sanitizeKeys))
|
||||
.put("body", sanitizeJson(requestBody, sanitizeKeys)).build();
|
||||
accessLog.setRequestParams(toJsonString(requestParams));
|
||||
}
|
||||
Boolean responseEnable = accessLogAnnotation != null ? accessLogAnnotation.responseEnable() : Boolean.FALSE;
|
||||
if (BooleanUtil.isTrue(responseEnable)) { // 默认不记录,默认强制要求 true
|
||||
accessLog.setResponseBody(sanitizeJson(result, sanitizeKeys));
|
||||
}
|
||||
// 设置其它字段
|
||||
accessLog.setTraceId(TracerUtils.getTraceId());
|
||||
accessLog.setApplicationName(applicationName);
|
||||
accessLog.setRequestUrl(request.getRequestURI());
|
||||
Map<String, Object> requestParams = MapUtil.<String, Object>builder().put("query", queryString).put("body", requestBody).build();
|
||||
accessLog.setRequestParams(toJsonString(requestParams));
|
||||
accessLog.setRequestMethod(request.getMethod());
|
||||
accessLog.setUserAgent(ServletUtils.getUserAgent(request));
|
||||
accessLog.setUserIp(ServletUtils.getClientIP(request));
|
||||
// 持续时间
|
||||
accessLog.setBeginTime(beginTime);
|
||||
accessLog.setEndTime(LocalDateTime.now());
|
||||
accessLog.setDuration((int) LocalDateTimeUtil.between(accessLog.getBeginTime(), accessLog.getEndTime(), ChronoUnit.MILLIS));
|
||||
accessLog.setBeginTime(beginTime).setEndTime(LocalDateTime.now())
|
||||
.setDuration((int) LocalDateTimeUtil.between(accessLog.getBeginTime(), accessLog.getEndTime(), ChronoUnit.MILLIS));
|
||||
|
||||
// 操作模块
|
||||
if (handlerMethod != null) {
|
||||
Tag tagAnnotation = handlerMethod.getBeanType().getAnnotation(Tag.class);
|
||||
Operation operationAnnotation = handlerMethod.getMethodAnnotation(Operation.class);
|
||||
String operateModule = accessLogAnnotation != null ? accessLogAnnotation.operateModule() :
|
||||
tagAnnotation != null ? StrUtil.nullToDefault(tagAnnotation.name(), tagAnnotation.description()) : null;
|
||||
String operateName = accessLogAnnotation != null ? accessLogAnnotation.operateName() :
|
||||
operationAnnotation != null ? operationAnnotation.summary() : null;
|
||||
OperateTypeEnum operateType = accessLogAnnotation != null && accessLogAnnotation.operateType().length > 0 ?
|
||||
accessLogAnnotation.operateType()[0] : parseOperateLogType(request);
|
||||
accessLog.setOperateModule(operateModule).setOperateName(operateName).setOperateType(operateType.getType());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// ========== 解析 @ApiAccessLog、@Swagger 注解 ==========
|
||||
|
||||
private static OperateTypeEnum parseOperateLogType(HttpServletRequest request) {
|
||||
RequestMethod requestMethod = RequestMethod.resolve(request.getMethod());
|
||||
if (requestMethod == null) {
|
||||
return OperateTypeEnum.OTHER;
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
// ========== 请求和响应的脱敏逻辑,移除类似 password、token 等敏感字段 ==========
|
||||
|
||||
private static String sanitizeMap(Map<String, ?> map, String[] sanitizeKeys) {
|
||||
if (CollUtil.isNotEmpty(map)) {
|
||||
return null;
|
||||
}
|
||||
if (sanitizeKeys != null) {
|
||||
MapUtil.removeAny(map, sanitizeKeys);
|
||||
}
|
||||
MapUtil.removeAny(map, SANITIZE_KEYS);
|
||||
return JsonUtils.toJsonString(map);
|
||||
}
|
||||
|
||||
private static String sanitizeJson(String jsonString, String[] sanitizeKeys) {
|
||||
if (StrUtil.isEmpty(jsonString)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
JsonNode rootNode = JsonUtils.parseTree(jsonString);
|
||||
sanitizeJson(rootNode, sanitizeKeys);
|
||||
return JsonUtils.toJsonString(rootNode);
|
||||
} catch (Exception e) {
|
||||
// 脱敏失败的情况下,直接忽略异常,避免影响用户请求
|
||||
log.error("[sanitizeJson][脱敏({}) 发生异常]", jsonString, e);
|
||||
return jsonString;
|
||||
}
|
||||
}
|
||||
|
||||
private static String sanitizeJson(CommonResult<?> commonResult, String[] sanitizeKeys) {
|
||||
if (commonResult == null) {
|
||||
return null;
|
||||
}
|
||||
String jsonString = toJsonString(commonResult);
|
||||
try {
|
||||
JsonNode rootNode = JsonUtils.parseTree(jsonString);
|
||||
sanitizeJson(rootNode.get("data"), sanitizeKeys); // 只处理 data 字段,不处理 code、msg 字段,避免错误被脱敏掉
|
||||
return JsonUtils.toJsonString(rootNode);
|
||||
} catch (Exception e) {
|
||||
// 脱敏失败的情况下,直接忽略异常,避免影响用户请求
|
||||
log.error("[sanitizeJson][脱敏({}) 发生异常]", jsonString, e);
|
||||
return jsonString;
|
||||
}
|
||||
}
|
||||
|
||||
private static void sanitizeJson(JsonNode node, String[] sanitizeKeys) {
|
||||
// 情况一:数组,遍历处理
|
||||
if (node.isArray()) {
|
||||
for (JsonNode childNode : node) {
|
||||
sanitizeJson(childNode, sanitizeKeys);
|
||||
}
|
||||
return;
|
||||
}
|
||||
// 情况二:非 Object,只是某个值,直接返回
|
||||
if (!node.isObject()) {
|
||||
return;
|
||||
}
|
||||
// 情况三:Object,遍历处理
|
||||
Iterator<Map.Entry<String, JsonNode>> iterator = node.properties().iterator();
|
||||
while (iterator.hasNext()) {
|
||||
Map.Entry<String, JsonNode> entry = iterator.next();
|
||||
if (ArrayUtil.contains(sanitizeKeys, entry.getKey())
|
||||
|| ArrayUtil.contains(SANITIZE_KEYS, entry.getKey())) {
|
||||
iterator.remove();
|
||||
continue;
|
||||
}
|
||||
sanitizeJson(entry.getValue(), sanitizeKeys);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -0,0 +1,67 @@
|
||||
package cn.iocoder.yudao.framework.apilog.core.interceptor;
|
||||
|
||||
import cn.hutool.core.collection.CollUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import cn.iocoder.yudao.framework.common.util.servlet.ServletUtils;
|
||||
import cn.iocoder.yudao.framework.common.util.spring.SpringUtils;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.util.StopWatch;
|
||||
import org.springframework.web.method.HandlerMethod;
|
||||
import org.springframework.web.servlet.HandlerInterceptor;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* API 访问日志 Interceptor
|
||||
*
|
||||
* 目的:在非 prod 环境时,打印 request 和 response 两条日志到日志文件(控制台)中。
|
||||
*
|
||||
* @author 芋道源码
|
||||
*/
|
||||
@Slf4j
|
||||
public class ApiAccessLogInterceptor implements HandlerInterceptor {
|
||||
|
||||
public static final String ATTRIBUTE_HANDLER_METHOD = "HANDLER_METHOD";
|
||||
|
||||
private static final String ATTRIBUTE_STOP_WATCH = "ApiAccessLogInterceptor.StopWatch";
|
||||
|
||||
@Override
|
||||
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
|
||||
// 记录 HandlerMethod,提供给 ApiAccessLogFilter 使用
|
||||
HandlerMethod handlerMethod = handler instanceof HandlerMethod ? (HandlerMethod) handler : null;
|
||||
if (handlerMethod != null) {
|
||||
request.setAttribute(ATTRIBUTE_HANDLER_METHOD, handlerMethod);
|
||||
}
|
||||
|
||||
// 打印 request 日志
|
||||
if (!SpringUtils.isProd()) {
|
||||
Map<String, String> queryString = ServletUtils.getParamMap(request);
|
||||
String requestBody = ServletUtils.isJsonRequest(request) ? ServletUtils.getBody(request) : null;
|
||||
if (CollUtil.isEmpty(queryString) && StrUtil.isEmpty(requestBody)) {
|
||||
log.info("[preHandle][开始请求 URL({}) 无参数]", request.getRequestURI());
|
||||
} else {
|
||||
log.info("[preHandle][开始请求 URL({}) 参数({})]", request.getRequestURI(),
|
||||
StrUtil.nullToDefault(requestBody, queryString.toString()));
|
||||
}
|
||||
// 计时
|
||||
StopWatch stopWatch = new StopWatch();
|
||||
stopWatch.start();
|
||||
request.setAttribute(ATTRIBUTE_STOP_WATCH, stopWatch);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
|
||||
// 打印 response 日志
|
||||
if (!SpringUtils.isProd()) {
|
||||
StopWatch stopWatch = (StopWatch) request.getAttribute(ATTRIBUTE_STOP_WATCH);
|
||||
stopWatch.stop();
|
||||
log.info("[afterCompletion][完成请求 URL({}) 耗时({} ms)]",
|
||||
request.getRequestURI(), stopWatch.getTotalTimeMillis());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -1,85 +0,0 @@
|
||||
package cn.iocoder.yudao.framework.apilog.core.service;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* API 访问日志
|
||||
*
|
||||
* @author 芋道源码
|
||||
*/
|
||||
@Data
|
||||
public class ApiAccessLog {
|
||||
|
||||
/**
|
||||
* 链路追踪编号
|
||||
*/
|
||||
private String traceId;
|
||||
/**
|
||||
* 用户编号
|
||||
*/
|
||||
private Long userId;
|
||||
/**
|
||||
* 用户类型
|
||||
*/
|
||||
private Integer userType;
|
||||
/**
|
||||
* 应用名
|
||||
*/
|
||||
@NotNull(message = "应用名不能为空")
|
||||
private String applicationName;
|
||||
|
||||
/**
|
||||
* 请求方法名
|
||||
*/
|
||||
@NotNull(message = "http 请求方法不能为空")
|
||||
private String requestMethod;
|
||||
/**
|
||||
* 访问地址
|
||||
*/
|
||||
@NotNull(message = "访问地址不能为空")
|
||||
private String requestUrl;
|
||||
/**
|
||||
* 请求参数
|
||||
*/
|
||||
@NotNull(message = "请求参数不能为空")
|
||||
private String requestParams;
|
||||
/**
|
||||
* 用户 IP
|
||||
*/
|
||||
@NotNull(message = "ip 不能为空")
|
||||
private String userIp;
|
||||
/**
|
||||
* 浏览器 UA
|
||||
*/
|
||||
@NotNull(message = "User-Agent 不能为空")
|
||||
private String userAgent;
|
||||
|
||||
/**
|
||||
* 开始请求时间
|
||||
*/
|
||||
@NotNull(message = "开始请求时间不能为空")
|
||||
private LocalDateTime beginTime;
|
||||
/**
|
||||
* 结束请求时间
|
||||
*/
|
||||
@NotNull(message = "结束请求时间不能为空")
|
||||
private LocalDateTime endTime;
|
||||
/**
|
||||
* 执行时长,单位:毫秒
|
||||
*/
|
||||
@NotNull(message = "执行时长不能为空")
|
||||
private Integer duration;
|
||||
/**
|
||||
* 结果码
|
||||
*/
|
||||
@NotNull(message = "错误码不能为空")
|
||||
private Integer resultCode;
|
||||
/**
|
||||
* 结果提示
|
||||
*/
|
||||
private String resultMsg;
|
||||
|
||||
}
|
@ -1,5 +1,7 @@
|
||||
package cn.iocoder.yudao.framework.apilog.core.service;
|
||||
|
||||
import cn.iocoder.yudao.module.infra.api.logger.dto.ApiAccessLogCreateReqDTO;
|
||||
|
||||
/**
|
||||
* API 访问日志 Framework Service 接口
|
||||
*
|
||||
@ -10,7 +12,8 @@ public interface ApiAccessLogFrameworkService {
|
||||
/**
|
||||
* 创建 API 访问日志
|
||||
*
|
||||
* @param apiAccessLog API 访问日志
|
||||
* @param reqDTO API 访问日志
|
||||
*/
|
||||
void createApiAccessLog(ApiAccessLog apiAccessLog);
|
||||
void createApiAccessLog(ApiAccessLogCreateReqDTO reqDTO);
|
||||
|
||||
}
|
||||
|
@ -1,6 +1,5 @@
|
||||
package cn.iocoder.yudao.framework.apilog.core.service;
|
||||
|
||||
import cn.hutool.core.bean.BeanUtil;
|
||||
import cn.iocoder.yudao.module.infra.api.logger.ApiAccessLogApi;
|
||||
import cn.iocoder.yudao.module.infra.api.logger.dto.ApiAccessLogCreateReqDTO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@ -20,8 +19,7 @@ public class ApiAccessLogFrameworkServiceImpl implements ApiAccessLogFrameworkSe
|
||||
|
||||
@Override
|
||||
@Async
|
||||
public void createApiAccessLog(ApiAccessLog apiAccessLog) {
|
||||
ApiAccessLogCreateReqDTO reqDTO = BeanUtil.copyProperties(apiAccessLog, ApiAccessLogCreateReqDTO.class);
|
||||
public void createApiAccessLog(ApiAccessLogCreateReqDTO reqDTO) {
|
||||
apiAccessLogApi.createApiAccessLog(reqDTO);
|
||||
}
|
||||
|
||||
|
@ -1,107 +0,0 @@
|
||||
package cn.iocoder.yudao.framework.apilog.core.service;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* API 错误日志
|
||||
*
|
||||
* @author 芋道源码
|
||||
*/
|
||||
@Data
|
||||
public class ApiErrorLog {
|
||||
|
||||
/**
|
||||
* 链路编号
|
||||
*/
|
||||
private String traceId;
|
||||
/**
|
||||
* 账号编号
|
||||
*/
|
||||
private Long userId;
|
||||
/**
|
||||
* 用户类型
|
||||
*/
|
||||
private Integer userType;
|
||||
/**
|
||||
* 应用名
|
||||
*/
|
||||
@NotNull(message = "应用名不能为空")
|
||||
private String applicationName;
|
||||
|
||||
/**
|
||||
* 请求方法名
|
||||
*/
|
||||
@NotNull(message = "http 请求方法不能为空")
|
||||
private String requestMethod;
|
||||
/**
|
||||
* 访问地址
|
||||
*/
|
||||
@NotNull(message = "访问地址不能为空")
|
||||
private String requestUrl;
|
||||
/**
|
||||
* 请求参数
|
||||
*/
|
||||
@NotNull(message = "请求参数不能为空")
|
||||
private String requestParams;
|
||||
/**
|
||||
* 用户 IP
|
||||
*/
|
||||
@NotNull(message = "ip 不能为空")
|
||||
private String userIp;
|
||||
/**
|
||||
* 浏览器 UA
|
||||
*/
|
||||
@NotNull(message = "User-Agent 不能为空")
|
||||
private String userAgent;
|
||||
|
||||
/**
|
||||
* 异常时间
|
||||
*/
|
||||
@NotNull(message = "异常时间不能为空")
|
||||
private LocalDateTime exceptionTime;
|
||||
/**
|
||||
* 异常名
|
||||
*/
|
||||
@NotNull(message = "异常名不能为空")
|
||||
private String exceptionName;
|
||||
/**
|
||||
* 异常发生的类全名
|
||||
*/
|
||||
@NotNull(message = "异常发生的类全名不能为空")
|
||||
private String exceptionClassName;
|
||||
/**
|
||||
* 异常发生的类文件
|
||||
*/
|
||||
@NotNull(message = "异常发生的类文件不能为空")
|
||||
private String exceptionFileName;
|
||||
/**
|
||||
* 异常发生的方法名
|
||||
*/
|
||||
@NotNull(message = "异常发生的方法名不能为空")
|
||||
private String exceptionMethodName;
|
||||
/**
|
||||
* 异常发生的方法所在行
|
||||
*/
|
||||
@NotNull(message = "异常发生的方法所在行不能为空")
|
||||
private Integer exceptionLineNumber;
|
||||
/**
|
||||
* 异常的栈轨迹异常的栈轨迹
|
||||
*/
|
||||
@NotNull(message = "异常的栈轨迹不能为空")
|
||||
private String exceptionStackTrace;
|
||||
/**
|
||||
* 异常导致的根消息
|
||||
*/
|
||||
@NotNull(message = "异常导致的根消息不能为空")
|
||||
private String exceptionRootCauseMessage;
|
||||
/**
|
||||
* 异常导致的消息
|
||||
*/
|
||||
@NotNull(message = "异常导致的消息不能为空")
|
||||
private String exceptionMessage;
|
||||
|
||||
|
||||
}
|
@ -1,5 +1,7 @@
|
||||
package cn.iocoder.yudao.framework.apilog.core.service;
|
||||
|
||||
import cn.iocoder.yudao.module.infra.api.logger.dto.ApiErrorLogCreateReqDTO;
|
||||
|
||||
/**
|
||||
* API 错误日志 Framework Service 接口
|
||||
*
|
||||
@ -10,7 +12,8 @@ public interface ApiErrorLogFrameworkService {
|
||||
/**
|
||||
* 创建 API 错误日志
|
||||
*
|
||||
* @param apiErrorLog API 错误日志
|
||||
* @param reqDTO API 错误日志
|
||||
*/
|
||||
void createApiErrorLog(ApiErrorLog apiErrorLog);
|
||||
void createApiErrorLog(ApiErrorLogCreateReqDTO reqDTO);
|
||||
|
||||
}
|
||||
|
@ -1,6 +1,5 @@
|
||||
package cn.iocoder.yudao.framework.apilog.core.service;
|
||||
|
||||
import cn.hutool.core.bean.BeanUtil;
|
||||
import cn.iocoder.yudao.module.infra.api.logger.ApiErrorLogApi;
|
||||
import cn.iocoder.yudao.module.infra.api.logger.dto.ApiErrorLogCreateReqDTO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@ -20,8 +19,7 @@ public class ApiErrorLogFrameworkServiceImpl implements ApiErrorLogFrameworkServ
|
||||
|
||||
@Override
|
||||
@Async
|
||||
public void createApiErrorLog(ApiErrorLog apiErrorLog) {
|
||||
ApiErrorLogCreateReqDTO reqDTO = BeanUtil.copyProperties(apiErrorLog, ApiErrorLogCreateReqDTO.class);
|
||||
public void createApiErrorLog(ApiErrorLogCreateReqDTO reqDTO) {
|
||||
apiErrorLogApi.createApiErrorLog(reqDTO);
|
||||
}
|
||||
|
||||
|
@ -3,7 +3,6 @@ package cn.iocoder.yudao.framework.web.core.handler;
|
||||
import cn.hutool.core.exceptions.ExceptionUtil;
|
||||
import cn.hutool.core.map.MapUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import cn.iocoder.yudao.framework.apilog.core.service.ApiErrorLog;
|
||||
import cn.iocoder.yudao.framework.apilog.core.service.ApiErrorLogFrameworkService;
|
||||
import cn.iocoder.yudao.framework.common.exception.ServiceException;
|
||||
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
|
||||
@ -11,6 +10,7 @@ import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
|
||||
import cn.iocoder.yudao.framework.common.util.monitor.TracerUtils;
|
||||
import cn.iocoder.yudao.framework.common.util.servlet.ServletUtils;
|
||||
import cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils;
|
||||
import cn.iocoder.yudao.module.infra.api.logger.dto.ApiErrorLogCreateReqDTO;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.exception.ExceptionUtils;
|
||||
@ -46,6 +46,7 @@ import static cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeC
|
||||
@Slf4j
|
||||
public class GlobalExceptionHandler {
|
||||
|
||||
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
|
||||
private final String applicationName;
|
||||
|
||||
private final ApiErrorLogFrameworkService apiErrorLogFrameworkService;
|
||||
@ -237,10 +238,10 @@ public class GlobalExceptionHandler {
|
||||
|
||||
private void createExceptionLog(HttpServletRequest req, Throwable e) {
|
||||
// 插入错误日志
|
||||
ApiErrorLog errorLog = new ApiErrorLog();
|
||||
ApiErrorLogCreateReqDTO errorLog = new ApiErrorLogCreateReqDTO();
|
||||
try {
|
||||
// 初始化 errorLog
|
||||
initExceptionLog(errorLog, req, e);
|
||||
buildExceptionLog(errorLog, req, e);
|
||||
// 执行插入 errorLog
|
||||
apiErrorLogFrameworkService.createApiErrorLog(errorLog);
|
||||
} catch (Throwable th) {
|
||||
@ -248,7 +249,7 @@ public class GlobalExceptionHandler {
|
||||
}
|
||||
}
|
||||
|
||||
private void initExceptionLog(ApiErrorLog errorLog, HttpServletRequest request, Throwable e) {
|
||||
private void buildExceptionLog(ApiErrorLogCreateReqDTO errorLog, HttpServletRequest request, Throwable e) {
|
||||
// 处理用户信息
|
||||
errorLog.setUserId(WebFrameworkUtils.getLoginUserId(request));
|
||||
errorLog.setUserType(WebFrameworkUtils.getLoginUserType(request));
|
||||
|
@ -44,9 +44,11 @@ public class YudaoXssAutoConfiguration implements WebMvcConfigurer {
|
||||
@ConditionalOnMissingBean(name = "xssJacksonCustomizer")
|
||||
@ConditionalOnBean(ObjectMapper.class)
|
||||
@ConditionalOnProperty(value = "yudao.xss.enable", havingValue = "true")
|
||||
public Jackson2ObjectMapperBuilderCustomizer xssJacksonCustomizer(XssCleaner xssCleaner) {
|
||||
public Jackson2ObjectMapperBuilderCustomizer xssJacksonCustomizer(XssProperties properties,
|
||||
PathMatcher pathMatcher,
|
||||
XssCleaner xssCleaner) {
|
||||
// 在反序列化时进行 xss 过滤,可以替换使用 XssStringJsonSerializer,在序列化时进行处理
|
||||
return builder -> builder.deserializerByType(String.class, new XssStringJsonDeserializer(xssCleaner));
|
||||
return builder -> builder.deserializerByType(String.class, new XssStringJsonDeserializer(properties, pathMatcher, xssCleaner));
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -1,12 +1,16 @@
|
||||
package cn.iocoder.yudao.framework.xss.core.json;
|
||||
|
||||
import cn.iocoder.yudao.framework.common.util.servlet.ServletUtils;
|
||||
import cn.iocoder.yudao.framework.xss.config.XssProperties;
|
||||
import cn.iocoder.yudao.framework.xss.core.clean.XssCleaner;
|
||||
import com.fasterxml.jackson.core.JsonParser;
|
||||
import com.fasterxml.jackson.core.JsonToken;
|
||||
import com.fasterxml.jackson.databind.DeserializationContext;
|
||||
import com.fasterxml.jackson.databind.deser.std.StringDeserializer;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.util.PathMatcher;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
@ -20,10 +24,29 @@ import java.io.IOException;
|
||||
@AllArgsConstructor
|
||||
public class XssStringJsonDeserializer extends StringDeserializer {
|
||||
|
||||
/**
|
||||
* 属性
|
||||
*/
|
||||
private final XssProperties properties;
|
||||
/**
|
||||
* 路径匹配器
|
||||
*/
|
||||
private final PathMatcher pathMatcher;
|
||||
|
||||
private final XssCleaner xssCleaner;
|
||||
|
||||
@Override
|
||||
public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
|
||||
// 1. 白名单 URL 的处理
|
||||
HttpServletRequest request = ServletUtils.getRequest();
|
||||
if (request != null) {
|
||||
String uri = ServletUtils.getRequest().getRequestURI();
|
||||
if (properties.getExcludeUrls().stream().anyMatch(excludeUrl -> pathMatcher.match(excludeUrl, uri))) {
|
||||
return p.getText();
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 真正使用 xssCleaner 进行过滤
|
||||
if (p.hasToken(JsonToken.VALUE_STRING)) {
|
||||
return xssCleaner.clean(p.getText());
|
||||
}
|
||||
|
Reference in New Issue
Block a user