只需在控制器方法上加上注解,就能保存日志
Maven依赖
需要引入SpringBoot的AOP依赖
1 2 3 4
| <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
|
数据表
一张普通的日志表
1 2 3 4 5 6 7 8 9 10 11
| CREATE TABLE `sys_operation_log` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '编号', `type` tinyint(1) NOT NULL COMMENT '操作类型(1:查询,2:插入,3:更新,4:删除)', `module` varchar(50) NOT NULL COMMENT '模块名称', `operation` varchar(50) NOT NULL COMMENT '操作描述', `successful` tinyint(1) NOT NULL DEFAULT '1' COMMENT '是否成功(0:否,1:是)', `remark` text COMMENT '备注', `create_time` datetime NOT NULL COMMENT '操作时间', `create_user` bigint(20) unsigned NOT NULL COMMENT '操作用户编号', PRIMARY KEY (`id`) USING BTREE ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COMMENT='系统操作日志表';
|
Service/Dao/Bean
使用MyBatisPlus快速创建CRUD,过于简单就不贴代码了
其中,LogTypeEnum这个枚举类后面为注解类使用而定义
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| @Getter @AllArgsConstructor public enum LogTypeEnum {
QUERY(1, "查询"),
SAVE(2, "新增"),
UPDATE(3, "更新"),
DELETE(4, "删除");
private Integer value;
private String name; }
|
注解类
首先需要定义一个@interface自定义注解类(字段根据实际使用环境来添加)
1 2 3 4 5 6 7 8 9 10 11
| @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface OperationLog {
LogTypeEnum type();
String module() default "system";
String operation();
}
|
切面
定义好注解类之后我们需要添加一个切面来实现注解
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| @Aspect @Component public class OperationLogAdvice { @Resource private SysOperationLogService sysOperationLogService; @Around(value = "@annotation(com.zjars.teamconfigure.common.annotation.OperationLog)") public Object saveLog(ProceedingJoinPoint joinPoint) throws Throwable { MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); OperationLog operationLog = methodSignature.getMethod().getDeclaredAnnotation(OperationLog.class); String operation = operationLog.operation(); String module = operationLog.module(); LogTypeEnum type = operationLog.type(); SysOperationLog sysOperationLog = new SysOperationLog() .setOperation(operation) .setModule(module) .setType(type.getValue()) .setCreateUser(1L) .setCreateTime(LocalDateTime.now()); try { Object proceed = joinPoint.proceed(); sysOperationLogService.save(sysOperationLog); return proceed; }catch (Exception e){ sysOperationLog.setSuccessful(false).setRemark(e.getMessage()); sysOperationLogService.save(sysOperationLog); throw e; } } }
|
使用
到这一步就完成了注解类集成日志记录的操作了,接下来只需要在使用的控制器方法上加上@OperationLog就可以了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| @OperationLog(type = LogTypeEnum.SAVE, operation = "新增XXX") @PostMapping("/save") public void save(XXX xxx) { } @OperationLog(type = LogTypeEnum.UPDATE, operation = "更新XXX") @PostMapping("/update") public void update(XXX xxx) { } @OperationLog(type = LogTypeEnum.DELETE, operation = "删除XXX") @PostMapping("/delete") public void delete(XXX xxx) { }
|
调用接口后,会自动插入到日志表中