自定义注解,aop实现自定义注解的日志功能

功能:使用aop实现自定义注解日志记录
1、定义注解 LogAutoannotation
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LogAutoannotation {

    /*
       接口描述
     */
    String  desc()  default  "";
}
2、配置aop,注解配置 AutoAnnotationConfig
@Aspect
@Component
public class AutoAnnotationConfig {
    private Log log = LogFactory.getLog(AutoAnnotationConfig.class);

    /*
      定义切点
      切到标记注解的方法
     */
    @Pointcut("@annotation(com.junlaninfo.annotation.LogAutoannotation)")
    public void LogAnnotation() {
    }

    @Around("LogAnnotation()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        //定义开始的时间
        long begin = System.currentTimeMillis();
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        Signature signature = point.getSignature();
        MethodSignature signature1 = (MethodSignature) signature;
        Method method = signature1.getMethod();
        LogAutoannotation annotation = method.getAnnotation(LogAutoannotation.class);
        //接口描述信息
        String desc = annotation.desc();
        log.info("------------请求开始---------");
        log.info("接口描述信息"+desc);
        log.info("请求ip: "+request.getRemoteAddr());
        log.info("请求参数是:"+JSON.toJSONString(point.getArgs()));
        log.info("请求的方法类型:"+request.getMethod());
        Object proceed = point.proceed(); //得到方法的返回结果,结果是json的
        long end=System.currentTimeMillis();
        log.info("请求耗时:"+(end-begin));
        log.info("请求的返回结果:"+ JSON.toJSONString(proceed));
        return proceed;
    }
}

3、使用注解  TestController
@RestController
public class TestController {
    private Log log = LogFactory.getLog(TestController.class);

    @LogAutoannotation(desc = "测试自定义注解的")
    @GetMapping("test")
    public  String  test(String  name){
        return   "我是"+name;
    }
}

4、启动类
@SpringBootApplication
public class AutoannotationApplication {
    public static void main(String[] args) {
        SpringApplication.run(AutoannotationApplication.class, args);
    }
}


注意事项:
AutoAnnotationConfig类上需要加上@Aspect  @Component,不然日志不会生效

参考文档:

https://www.cnblogs.com/wenjunwei/p/9639909.html

https://www.toutiao.com/a6795903732807631363/?tt_from=weixin&utm_campaign=client_share&wxshare_count=1&timestamp=1584373143&app=news_article&utm_source=weixin&utm_medium=toutiao_android&req_id=202003162339030100260772032934B7D8&group_id=6795903732807631363

代码:

https://github.com/xuexionghui/Auto-annotate-AOP.git

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值