广告
返回顶部
首页 > 资讯 > 后端开发 > Python >springboot使用自定义注解实现aop切面日志
  • 366
分享到

springboot使用自定义注解实现aop切面日志

2024-04-02 19:04:59 366人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

平时我们在开发过程中,代码出现bug时为了更好的在服务器日志中寻找问题根源,会在接口的首尾打印日志,看下参数和返回值是否有问题。但是手动的logger.info() 去编写时工作量较

平时我们在开发过程中,代码出现bug时为了更好的在服务器日志中寻找问题根源,会在接口的首尾打印日志,看下参数和返回值是否有问题。但是手动的logger.info() 去编写时工作量较大,这时我们可以使用aop切面,为所有接口的首尾打印日志。

实现AOP切面日志一般有两种方式:

1、拦截所有接口controller,在首尾打印日志
2、拦截指定注解的接口,为有该注解的接口首尾打印日志

我们尝试用自定义注解来实现AOP日志的打印,这样拥有更高的灵活性。废话不多说,我们开始

1. 导入切面需要的依赖包

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

2. 自定义注解 AOPLog , 指定注解使用在方法上, 指定在运行时有效

Target:描述了注解修饰的对象范围

  • METHOD:用于描述方法
  • PACKAGE:用于描述包
  • PARAMETER:用于描述方法变量
  • TYPE:用于描述类、接口或enum类型

Retention: 表示注解保留时间长短

  • SOURCE:在源文件中有效,编译过程中会被忽略
  • CLASS:随源文件一起编译在class文件中,运行时忽略
  • RUNTIME:在运行时有效

只有定义为 RetentionPolicy.RUNTIME(在运行时有效)时,我们才能通过反射获取到注解,然后根据注解的一系列值,变更不同的操作。

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
 

// 指定注解使用在方法上
@Target(ElementType.METHOD)
// 指定生效至运行时
@Retention(RetentionPolicy.RUNTIME)
public @interface AOPLog {
 
    
    boolean isDetail() default false;
 
}

3. 设置切面类

import com.alibaba.fastJSON.jsON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
 
import java.lang.reflect.Method;
 

// 指定切面类
@Aspect
// 注入容器
@Component
public class AOPLogAspect {
 
    private static Logger log = LoggerFactory.getLogger(AOPLogAspect.class);
 
    
    @Pointcut("@annotation(com.xingyun.xybb.demo.annotation.AOPLog)")
    public void logPointCut() {
    }
 
    
    @Around("logPointCut()")
    public void logAround(ProceedingJoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        // 获取方法名称
        String methodName = signature.getName();
        // 获取入参
        Object[] param = joinPoint.getArgs();
        StringBuilder sb = new StringBuilder();
        for (Object o : param) {
            sb.append(o).append("; ");
        }
        log.info("进入方法[{}], 参数有[{}]", methodName, sb.toString());
 
        String resp = "";
        try {
            Object proceed = joinPoint.proceed();
            resp = JSON.toJSONString(proceed, SerializerFeature.WriteMapNullValue);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
 
        // 获取方法上的注解,判断如果isDetail值为true,则打印结束日志
        Method method = signature.getMethod();
        AOPLog annotation = method.getAnnotation(AOPLog.class);
        boolean isDetail = annotation.isDetail();
        if (isDetail) {
            log.info("方法[{}]执行结束, 返回值[{}]", methodName, resp);
        }
    }
 
}

4. 编写测试接口, 测试切面日志是否生效

import com.xingyun.xybb.common.response.XyResponseEntity;
import com.xingyun.xybb.demo.annotation.AOPLog;
import org.springframework.Http.ResponseEntity;
import org.springframework.WEB.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
 

@RestController
public class TestAOPLoGController {
    
    // 指定注解@AOPLog
    @AOPLog
    @GetMapping("/testAOP")
    public ResponseEntity<?> testAOPLog() {
        return XyResponseEntity.ok();
    }
 
    // 指定注解@AOPLog, 同时isDetail = true
    @AOPLog(isDetail = true)
    @GetMapping("/testAOPLogDetail")
    public ResponseEntity<?> testAOPLogDetail() {
        return XyResponseEntity.ok();
    }
 
}

5. 分别请求两测试接口

http://localhost:8499/demo/testAOP
http://localhost:8499/demo/testAOPLogDetail

控制台打印出

2019-12-26 14:00:56.336  ***.AOPLogAspect    : 进入方法[testAOPLog], 参数有[]
 
2019-12-26 14:01:00.372  ***.AOPLogAspect    : 进入方法[testAOPLogDetail], 参数有[]
2019-12-26 14:01:00.373  ***.AOPLogAspect    : 方法[testAOPLogDetail]执行结束, 返回值[{"body":{"retCode":200,"retEntity":null,"retMsg":"OK"},"headers":{},"statusCode":"OK","statusCodeValue":200}]

由此可看出,AOP切面拦截成功,打印出了日志,同时设置了 isDetail = true 时,打印出了结束日志。

自定义注解实现AOP切面打印日志完成。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程网。

--结束END--

本文标题: springboot使用自定义注解实现aop切面日志

本文链接: https://www.lsjlt.com/news/166702.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作