Springboot中自定义注解,实现日志记录

Springboot中自定义注解,实现日志记录

Spring中有很多的注解,通过简单的注解就能实现当时在xml文件中的各种配置,非常的方便,在项目中我们可以通过自定义注解实现一些功能,也会很方便,比如说在需要的方法上加上自定义的注解来实现记录入参,以及方法的执行时间,来判断是哪个方法出现异常或者执行速度慢,这个在需要的方法上实现很简单,但是我们把它做成自定义注解的形式,不会污染代码本身逻辑,还能实现功能,方便使用,提取出了公共的代码。Springboot自定义注解分了两个部分1.定义注解,2.Aop实现注解
接下来我们来实现一个自定义注解来进行日志记录。

1定义注解


@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SysLog {
    String value() default "";
}

其中
@Documented (注解信息会被添加到Java文档中)
@Retention(RetentionPolicy.RUNTIME) (注解的生命周期,表示注解会被保留到什么阶段,可以选择编译阶段(SOURCE)、类加载阶段(CLASS),或运行阶段(RUNTIME) 生命周期排序 SOURCE<CLASS<RUNTTIME)
@Target注解作用的位置,ElementType.METHOD表示该注解作用于方法上

2.Aop实现注解

代码中要使用Aop 需要先引入相关jar

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

切面类:

然后
@Aspect
@Component
public class SysLogAspect {
    private static final ThreadLocal<Long> beginTimeThreadLocal = new NamedThreadLocal<>("beginTime");
    private static final Logger log = LoggerFactory.getLogger(SysLogAspect.class);
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Pointcut("@annotation(com.jbgz.dnfcomputer.aop.SysLog)")
    public void LogAspect() {

    }


    /**
     * 前置通知 (在方法执行之前返回)用于拦截Controller层记录用户的操作的开始时间
     * @param joinPoint 切点
     * @throws InterruptedException
     */
    @Before("LogAspect()")
    public void doBefore(JoinPoint joinPoint) throws InterruptedException {
        Long beforeSecond = System.currentTimeMillis();
        //获取当前方法上注解的值
        SysLog sysLog = ((MethodSignature) joinPoint.getSignature()).getMethod().getAnnotation(SysLog.class);
        //获取当前方法参数
        Object[] args = joinPoint.getArgs();
        //获取切点所在类名
        String className = joinPoint.getTarget().getClass().getSimpleName();
        //获取切点方法名
        String method = joinPoint.getSignature().getName();
        beginTimeThreadLocal.set(beforeSecond);
        Thread thread = Thread.currentThread();
        log.info("公共日志-开始-当前线程{}\n--类:{} \n--方法:{}\n--方法上注解:{}\n--传入参数数组:{}", thread.getName(), className, method, sysLog.value(), Arrays.toString(args));
    }

    @After("LogAspect()")
    public void after(JoinPoint joinPoint) {
        Thread thread = Thread.currentThread();
        Long beforeSecond = beginTimeThreadLocal.get();
        Long afterSecond = System.currentTimeMillis();
        Long spendTime = (afterSecond - beforeSecond) / 1000;
        log.info("公共日志-结束-当前线程{}--- 消耗时间 {}s", thread.getName(), spendTime);

    }
}

代码中通过ThreadLocal记录开始的时间,

//定义 切入点,就是SysLog那个注解
@Pointcut("@annotation(com.jbgz.dnfcomputer.aop.SysLog)")
    public void LogAspect() {
    }

将其在controller上标注:

 @PostMapping("/test")
    @SysLog("测试自定义注解表单提交方式")
    public Result test(String param1, Integer param2) {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return new Result(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getDescribe(),param1+" "+param2);
    }
   @PostMapping("/test2")
    @SysLog("测试自定义注解请求体中参数")
    public Result test(@RequestBody JSONObject map) {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return new Result(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getDescribe(),map);
    }

发出请求:
(发送请求工具介绍)在这里插入图片描述
控制台输出:在这里插入图片描述
测试json形式参数:
在这里插入图片描述
日志:在这里插入图片描述
这样我们就实现了对请求方法的日志记录,并且记录下相关入参,方便发现错误。但是不会使方法本身的代码混淆。
我们也能通过环绕的方式对相关参数进行加解密再执行方法便实现了类似拦截器的对参数加解密的功能。
欢迎大家指正,共同进步。

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值