springboot 自定义注解 实现把相关日志插入日志表中

本文档展示了如何在SpringBoot项目中使用AOP和自定义注解来实现方法调用的日志记录。通过创建日志实体类、自定义注解、AOP切面以及在API接口上应用注解,可以方便地记录和存储方法执行的相关信息,如方法名、模块描述等,并将这些信息保存到数据库的日志表中。
摘要由CSDN通过智能技术生成

springboot aop 实现自定义注解(demo用到了mybatis-plus 对数据进行操作,所以代码中会有相关的注解)

码云demo:https://gitee.com/dongbingya/springboot

注:只实现该功能,相关方法不做解释说明。

1.首先在pom文件中添加aop依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

2.日志实体类

@Data
@TableName("systemlog")
public class SystemLog {

    @TableField("id")
    private String id;

    @TableField("title")
    private String title;

    @TableField("details")
    private String details;

    @TableField("create_time")
    private Date createTime;

    @TableField("method")
    private String method;

    @TableField("error")
    private String error;
}

3.自定义注解类
说明:

a.访问修饰符必须为public,不写默认为public;

b.该元素的类型只能是基本数据类型、String、Class、枚举类型、注解类型以及一维数组;

c.该元素的名称一般定义为名词,如果注解中只有一个元素,名字起为value最好;

d.()不是定义方法参数的地方,也不能在括号中定义任何参数,仅仅只是一个特殊的语法;

e.default代表默认值,值必须定义的类型一致;

f.如果没有默认值,代表后续使用注解时必须给该类型元素赋值。
在这里插入图片描述

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SysLog {

    String title() default "";//模块名称

    String describe() default "";//描述
}

4.aop切面类。对自定义注解进行功能操作,在这里实现了获取接口方法名等信息并一起添加到日志表中

@Aspect
@Component("logAspect")
public class LogAspect {

    @Autowired
    private SystemLogMapper systemLogMapper;

    private static final Logger log = LoggerFactory.getLogger(LogAspect.class);

    // 配置织入点
    @Pointcut("@annotation(com.dongbing.demo.modules.system.log.SysLog)")
    public void logPointCut() {
    }

    /**
     * 前置通知 用于拦截操作,在方法返回后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "logPointCut()")
    public void doBefore(JoinPoint joinPoint) {
        handleLog(joinPoint, null);
    }

    private void handleLog(JoinPoint joinPoint, Exception e) {

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        SystemLog systemLog = new SystemLog();
        //获取方法名
        String functionName = signature.getDeclaringTypeName() + "." + signature.getName() + "()";
        //获取注解对象
        SysLog annotation = signature.getMethod().getAnnotation(SysLog.class);
        if(annotation != null){
            systemLog.setId(UUID.randomUUID().toString().replace("-", ""));
            systemLog.setMethod(functionName);
            //获取注解中对方法的描述信息
            systemLog.setTitle(annotation.title());
            systemLog.setDetails(annotation.describe());
            systemLog.setCreateTime(new Date());
            if (e != null) {
                String err = e.getMessage();
                if (err != null && err.length() > 4000) {
                    err = err.substring(0, 4000);
                }
                systemLog.setError(err);
            }
        }
        //记录到数据库
        systemLogMapper.insert(systemLog);
        }

    /**
     * 是否存在注解,如果存在就获取
     */
    private static SysLog getAnnotationLog(JoinPoint joinPoint) throws Exception {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method != null) {
            return method.getAnnotation(SysLog.class);
        }
        return null;
    }
}

api接口方法上添加自定义的注解,填写相应的信息即可。

@RestController
public class LogController {

    //使用日志注解
    @SysLog(title = "用户模块",describe = "获取用户列表")
    @GetMapping("/sysLogGet")
    public String get(){
        return "Hello word!";
    }
}

6.数据库表字段格式和数据添加到表中后
在这里插入图片描述
在这里插入图片描述
码云有一些springboot整合的demo

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值