添加操作日志服务.

This commit is contained in:
lijiahang
2023-10-11 15:54:06 +08:00
parent 2028d1ee0f
commit 730a20a3e2
12 changed files with 117 additions and 29 deletions

View File

@@ -1,9 +1,11 @@
package com.orion.ops.framework.biz.operator.log.config;
import com.alibaba.fastjson.serializer.ValueFilter;
import com.orion.ops.framework.biz.operator.log.core.aspect.OperatorLogAspect;
import com.orion.ops.framework.biz.operator.log.core.config.OperatorLogConfig;
import com.orion.ops.framework.biz.operator.log.core.service.OperatorLogFrameworkService;
import com.orion.ops.framework.biz.operator.log.core.service.OperatorLogFrameworkServiceDelegate;
import com.orion.ops.framework.biz.operator.log.core.uitls.OperatorLogs;
import com.orion.ops.framework.common.constant.AutoConfigureOrderConst;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
@@ -12,6 +14,8 @@ import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import javax.annotation.Resource;
/**
* 操作日志配置类
*
@@ -24,6 +28,9 @@ import org.springframework.context.annotation.Primary;
@EnableConfigurationProperties(OperatorLogConfig.class)
public class OrionOperatorLogAutoConfiguration {
@Resource
private ValueFilter desensitizeValueFilter;
/**
* 操作日志委托类
*
@@ -48,6 +55,8 @@ public class OrionOperatorLogAutoConfiguration {
@ConditionalOnBean(OperatorLogFrameworkServiceDelegate.class)
public OperatorLogAspect operatorLogAspect(OperatorLogConfig operatorLogConfig,
OperatorLogFrameworkService service) {
// 设置脱敏过滤器
OperatorLogs.setDesensitizeValueFilter(desensitizeValueFilter);
return new OperatorLogAspect(operatorLogConfig, service);
}

View File

@@ -5,6 +5,7 @@ import com.alibaba.fastjson.serializer.ValueFilter;
import com.orion.lang.define.thread.ExecutorBuilder;
import com.orion.lang.define.wrapper.Ref;
import com.orion.lang.utils.Strings;
import com.orion.lang.utils.json.matcher.ReplacementFormatters;
import com.orion.ops.framework.biz.operator.log.core.annotation.OperatorLog;
import com.orion.ops.framework.biz.operator.log.core.config.OperatorLogConfig;
import com.orion.ops.framework.biz.operator.log.core.enums.ReturnType;
@@ -70,6 +71,8 @@ public class OperatorLogAspect {
@Around("@annotation(o)")
public Object around(ProceedingJoinPoint joinPoint, OperatorLog o) throws Throwable {
long start = System.currentTimeMillis();
// 先清空上下文
OperatorLogs.clear();
try {
// 执行
Object result = joinPoint.proceed();
@@ -192,9 +195,8 @@ public class OperatorLogAspect {
* @param extra extra
*/
private void fillExtra(OperatorLogModel model, Map<String, Object> extra) {
// 脱敏
if (extra != null) {
model.setExtra(JSON.toJSONString(extra, desensitizeValueFilter));
model.setExtra(JSON.toJSONString(extra));
}
}
@@ -209,7 +211,7 @@ public class OperatorLogAspect {
OperatorType type = OperatorTypeHolder.get(o.value());
model.setModule(type.getModule());
model.setType(type.getType());
model.setLogInfo(Strings.format(type.getTemplate(), extra));
model.setLogInfo(ReplacementFormatters.format(type.getTemplate(), extra));
}
/**

View File

@@ -0,0 +1,26 @@
package com.orion.ops.framework.biz.operator.log.core.constant;
/**
* 操作日志常量
*
* @author Jiahang Li
* @version 1.0.0
* @since 2023/10/10 19:00
*/
public interface OperatorLogKeys {
String ID = "id";
String ID_LIST = "idList";
String CODE = "code";
String NAME = "name";
String USERNAME = "username";
String TITLE = "title";
String VALUE = "value";
}

View File

@@ -1,6 +1,8 @@
package com.orion.ops.framework.biz.operator.log.core.uitls;
import com.orion.lang.utils.reflect.BeanMap;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.ValueFilter;
import com.orion.ops.framework.biz.operator.log.core.constant.OperatorLogKeys;
import java.util.HashMap;
import java.util.Map;
@@ -12,10 +14,12 @@ import java.util.Map;
* @version 1.0.0
* @since 2023/10/10 11:32
*/
public class OperatorLogs {
public class OperatorLogs implements OperatorLogKeys {
private static final String UN_SAVE_FLAG = "__un__save__";
private static ValueFilter desensitizeValueFilter;
private static final ThreadLocal<Map<String, Object>> EXTRA_HOLDER = new ThreadLocal<>();
private OperatorLogs() {
@@ -54,7 +58,7 @@ public class OperatorLogs {
add((Map<String, ?>) obj);
return;
}
initMap().putAll(BeanMap.create(obj));
initMap().putAll(JSON.parseObject(JSON.toJSONString(obj, desensitizeValueFilter)));
}
/**
@@ -115,4 +119,8 @@ public class OperatorLogs {
return map;
}
public static void setDesensitizeValueFilter(ValueFilter desensitizeValueFilter) {
OperatorLogs.desensitizeValueFilter = desensitizeValueFilter;
}
}

View File

@@ -34,7 +34,6 @@ public class DesensitizeJsonSerializer extends JsonSerializer<Object> implements
return this;
}
return prov.findValueSerializer(property.getType(), property);
}
@Override

View File

@@ -9,6 +9,7 @@ import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.orion.lang.constant.Const;
import com.orion.lang.utils.Strings;
import com.orion.lang.utils.ansi.AnsiAppender;
import com.orion.lang.utils.ansi.style.AnsiFont;
import com.orion.lang.utils.ansi.style.color.AnsiForeground;
@@ -42,7 +43,7 @@ public class CodeGenerator {
// 作者
String author = Const.ORION_AUTHOR;
// 模块
String module = "asset";
String module = "infra";
// 生成的表
Table[] tables = {
// Template.create("preference", "用户偏好", "preference")
@@ -56,9 +57,8 @@ public class CodeGenerator {
// .values("value", 1, 2)
// .color("blue", "green")
// .build(),
Template.create("host_identity", "主机身份", "host")
.vue("asset", "host-identity")
.enableCardView()
Template.create("operator_log", "操作日志", "operator.log")
.disableUnitTest()
.build()
};
// jdbc 配置 - 使用配置文件
@@ -124,7 +124,7 @@ public class CodeGenerator {
ag.execute(engine);
// 打印提示信息
printTips();
printTips(module);
}
/**
@@ -327,7 +327,9 @@ public class CodeGenerator {
// cache dto 文件
new String[]{"/templates/orion-server-module-cache-dto.java.vm", "${type}CacheDTO.java", "entity.dto"},
// cache key define 文件
new String[]{"/templates/orion-server-module-cache-key-define.java.vm", "${type}CacheKeyDefine.java", "define"},
new String[]{"/templates/orion-server-module-cache-key-define.java.vm", "${type}CacheKeyDefine.java", "define.cache"},
// operator log define 文件
new String[]{"/templates/orion-server-module-operator-key-define.java.vm", "${type}OperatorType.java", "define.operator"},
// -------------------- 后端 - provider --------------------
// api 文件
new String[]{"/templates/orion-server-provider-api.java.vm", "${type}Api.java", "api"},
@@ -404,12 +406,13 @@ public class CodeGenerator {
/**
* 打印提示信息
*/
private static void printTips() {
private static void printTips(String module) {
String line = AnsiAppender.create()
.append(AnsiForeground.BRIGHT_GREEN.and(AnsiFont.BOLD), "\n:: 代码生成完毕 ^_^ ::\n")
.append(AnsiForeground.BRIGHT_BLUE.and(AnsiFont.BOLD), "- 后端代码复制后请先 clean 模块父工程\n")
.append(AnsiForeground.BRIGHT_BLUE.and(AnsiFont.BOLD), "- 后端代码需要自行修改缓存逻辑\n")
.append(AnsiForeground.BRIGHT_BLUE.and(AnsiFont.BOLD), "- 后端代码修改完成后请先执行单元测试检测是否正常\n")
.append(AnsiForeground.BRIGHT_BLUE.and(AnsiFont.BOLD), "- 需要在 " + Strings.firstUpper(module) + "OperatorTypeRunner 添加 xxxOperatorType.init() 来初始化操作日志类型 \n")
.append(AnsiForeground.BRIGHT_BLUE.and(AnsiFont.BOLD), "- vue 代码需要注意同一模块的 router 需要自行合并\n")
.append(AnsiForeground.BRIGHT_BLUE.and(AnsiFont.BOLD), "- vue 枚举需要自行更改数据类型\n")
.append(AnsiForeground.BRIGHT_BLUE.and(AnsiFont.BOLD), "- 菜单 sql 执行完成后 需要在菜单页面刷新缓存\n")

View File

@@ -118,7 +118,6 @@ public class VelocityTemplateEngine extends AbstractTemplateEngine {
this.replacePackageName(customFiles, tableInfo, objectMap);
// 添加注释元数据
this.addApiCommentMeta(tableInfo, objectMap);
// 生成后端文件
this.generatorServerFile(customFiles, tableInfo, objectMap);
// 生成前端文件
@@ -138,13 +137,13 @@ public class VelocityTemplateEngine extends AbstractTemplateEngine {
@NotNull TableInfo tableInfo) {
// 生成文件副本
List<CustomFile> files = originCustomerFile.stream().map(s ->
new CustomFile.Builder()
.enableFileOverride()
.templatePath(s.getTemplatePath())
.filePath(s.getFilePath())
.fileName(s.getFileName())
.packageName(s.getPackageName())
.build())
new CustomFile.Builder()
.enableFileOverride()
.templatePath(s.getTemplatePath())
.filePath(s.getFilePath())
.fileName(s.getFileName())
.packageName(s.getPackageName())
.build())
.collect(Collectors.toList());
// 获取 table
Table table = tables.get(tableInfo.getName());

View File

@@ -1,6 +1,7 @@
package ${package.Controller};
import com.orion.lang.define.wrapper.DataGrid;
import com.orion.ops.framework.biz.operator.log.core.annotation.OperatorLog;
import com.orion.ops.framework.common.validator.group.Page;
import com.orion.ops.framework.log.core.annotation.IgnoreLog;
import com.orion.ops.framework.log.core.enums.IgnoreLogMode;
@@ -48,6 +49,7 @@ public class ${table.controllerName} {
@Resource
private ${type}Service ${typeLower}Service;
@OperatorLog(${type}OperatorType.CREATE)
@PostMapping("/create")
@Operation(summary = "${apiComment.create}")
@PreAuthorize("@ss.hasPermission('${package.ModuleName}:${typeHyphen}:create')")
@@ -55,6 +57,7 @@ public class ${table.controllerName} {
return ${typeLower}Service.create${type}(request);
}
@OperatorLog(${type}OperatorType.UPDATE)
@PutMapping("/update")
@Operation(summary = "${apiComment.updateById}")
@PreAuthorize("@ss.hasPermission('${package.ModuleName}:${typeHyphen}:update')")
@@ -96,6 +99,7 @@ public class ${table.controllerName} {
return ${typeLower}Service.get${type}Page(request);
}
@OperatorLog(${type}OperatorType.DELETE)
@DeleteMapping("/delete")
@Operation(summary = "${apiComment.deleteById}")
@Parameter(name = "id", description = "id", required = true)
@@ -104,6 +108,7 @@ public class ${table.controllerName} {
return ${typeLower}Service.delete${type}ById(id);
}
@OperatorLog(${type}OperatorType.DELETE)
@DeleteMapping("/batch-delete")
@Operation(summary = "${apiComment.batchDelete}")
@Parameter(name = "idList", description = "idList", required = true)
@@ -112,6 +117,7 @@ public class ${table.controllerName} {
return ${typeLower}Service.batchDelete${type}ByIdList(idList);
}
@OperatorLog(${type}OperatorType.EXPORT)
@PostMapping("/export")
@Operation(summary = "${apiComment.export}")
@PreAuthorize("@ss.hasPermission('${package.ModuleName}:${typeHyphen}:export')")

View File

@@ -0,0 +1,33 @@
package ${currentPackage};
import com.orion.ops.framework.biz.operator.log.core.model.OperatorType;
import static com.orion.ops.framework.biz.operator.log.core.holder.OperatorTypeHolder.set;
/**
* $!{table.comment} 操作日志类型
*
* @author ${author}
* @version ${since}
* @since ${date}
*/
public class ${type}OperatorType {
private static final String MODULE = "${package.ModuleName}:${typeHyphen}";
public static final String CREATE = "${typeHyphen}:create";
public static final String UPDATE = "${typeHyphen}:update";
public static final String DELETE = "${typeHyphen}:delete";
public static final String EXPORT = "${typeHyphen}:export";
public static void init() {
set(new OperatorType(MODULE, CREATE, "创建$!{table.comment}"));
set(new OperatorType(MODULE, UPDATE, "更新$!{table.comment}"));
set(new OperatorType(MODULE, DELETE, "删除$!{table.comment}"));
set(new OperatorType(MODULE, EXPORT, "导出$!{table.comment}"));
}
}

View File

@@ -4,11 +4,12 @@ import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.orion.lang.define.wrapper.DataGrid;
import com.orion.lang.utils.Strings;
import com.orion.lang.utils.collect.Lists;
import com.orion.office.excel.writer.exporting.ExcelExport;
import com.orion.ops.framework.biz.operator.log.core.uitls.OperatorLogs;
#if($cacheMeta.enableCache)
import com.orion.ops.framework.common.constant.Const;
#end
import com.orion.lang.utils.collect.Lists;
import com.orion.office.excel.writer.exporting.ExcelExport;
import com.orion.ops.framework.common.constant.ErrorMessage;
import com.orion.ops.framework.common.utils.FileNames;
import com.orion.ops.framework.common.utils.Valid;
@@ -49,6 +50,7 @@ public class ${table.serviceImplName} implements ${table.serviceName} {
@Override
public Long create${type}(${type}CreateRequest request) {
log.info("${type}Service-create${type} request: {}", JSON.toJSONString(request));
OperatorLogs.add(request);
// 转换
${type}DO record = ${type}Convert.MAPPER.to(request);
// 查询数据是否冲突
@@ -67,6 +69,7 @@ public class ${table.serviceImplName} implements ${table.serviceName} {
@Override
public Integer update${type}ById(${type}UpdateRequest request) {
log.info("${type}Service-update${type}ById id: {}, request: {}", request.getId(), JSON.toJSONString(request));
OperatorLogs.add(request);
// 查询
Long id = Valid.notNull(request.getId(), ErrorMessage.ID_MISSING);
${type}DO record = ${typeLower}DAO.selectById(id);
@@ -177,6 +180,7 @@ public class ${table.serviceImplName} implements ${table.serviceName} {
@Override
public Integer delete${type}ById(Long id) {
log.info("${type}Service-delete${type}ById id: {}", id);
OperatorLogs.add(OperatorLogs.ID, id);
// 检查数据是否存在
${type}DO record = ${typeLower}DAO.selectById(id);
Valid.notNull(record, ErrorMessage.DATA_ABSENT);
@@ -193,6 +197,7 @@ public class ${table.serviceImplName} implements ${table.serviceName} {
@Override
public Integer batchDelete${type}ByIdList(List<Long> idList) {
log.info("${type}Service-batchDelete${type}ByIdList idList: {}", idList);
OperatorLogs.add(OperatorLogs.ID_LIST, idList);
int effect = ${typeLower}DAO.deleteBatchIds(idList);
log.info("${type}Service-batchDelete${type}ByIdList effect: {}", effect);
#if($cacheMeta.enableCache)
@@ -220,6 +225,7 @@ public class ${table.serviceImplName} implements ${table.serviceName} {
@Override
public void export${type}(${type}QueryRequest request, HttpServletResponse response) throws IOException {
log.info("${type}Service.export${type} request: {}", JSON.toJSONString(request));
OperatorLogs.add(request);
// 条件
LambdaQueryWrapper<${type}DO> wrapper = this.buildQueryWrapper(request);
// 查询

View File

@@ -52,9 +52,8 @@ Authorization: {{token}}
"page": 1,
"limit": 10,
"id": "",
"username": "",
"password": "",
"nickname": "",
"username": "123123",
"nickname": "123123",
"avatar": "",
"mobile": "",
"email": "",

View File

@@ -3,12 +3,10 @@ package com.orion.ops.module.infra.controller;
import com.orion.lang.define.wrapper.DataGrid;
import com.orion.lang.define.wrapper.HttpWrapper;
import com.orion.lang.utils.collect.Lists;
import com.orion.ops.framework.biz.operator.log.core.annotation.OperatorLog;
import com.orion.ops.framework.common.validator.group.Page;
import com.orion.ops.framework.log.core.annotation.IgnoreLog;
import com.orion.ops.framework.log.core.enums.IgnoreLogMode;
import com.orion.ops.framework.web.core.annotation.RestWrapper;
import com.orion.ops.module.infra.define.operator.UserOperatorType;
import com.orion.ops.module.infra.entity.request.user.*;
import com.orion.ops.module.infra.entity.vo.SystemUserVO;
import com.orion.ops.module.infra.service.SystemUserRoleService;