当前位置:   article > 正文

使用AOP实现日志埋点_使用spring的aop实现日志埋点

使用spring的aop实现日志埋点

添加aop日志埋点

常用的添加日志埋点的位置是提供给外部服务调用的接口

这里用springboot的@RestController接口演示

1.添加依赖

添加aop相关依赖,包含Aspect等类

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-aop</artifactId>
  <version>2.4.5</version>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5

添加接口相关依赖(任何实现方式均可)

<!-- 添加springboot的依赖 springmvc -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
  <version>2.4.5</version>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

2.基础代码

创建SpringBootApplication启动类

创建配置文件,指定端口等

server:
  port: 8091
  • 1
  • 2

简单编写一个演示服务

略,返回一个String就行

把接口暴露出来
在这里插入图片描述

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    UserService userService;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String queryAllUser() {
        return userService.queryAllUser();
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String queryById(@PathVariable("id") String id) {
        return userService.queryUserById(id);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

测试通过

在这里插入图片描述

3.编写切面相关代码

注解扩展,对于自定义注解的类,注解中加自定义属性,增加调用日志,包括方法名,参数,返回结果,调用时间等

定义切面注解

这里添加自定义的属性,实现更多扩展

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface TestServiceWatcher {
    String annoArg0();
    String annoArg1();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

切面类打印语句,项目中用自己的日志框架

logger.info(annoArg0+" "+annoArg1+" "+ new Date()+" "+paramsMap.toString());
  • 1

打印结果

定义切面

4.切面类完整代码

@Aspect
@Component("serviceWatcher")
public class ServiceWatcher {
    // 日志在实际项目中采用日志框架,指定打印日志的位置与格式,这里方便演示直接打印在控制台中
    Logger logger = Logger.getLogger("AppServiceWatcherLogger");

    // 增强方法
    @Around("@annotation(com.example.aop.demo.aoplogger.TestServiceWatcher)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        if (!isParamsOpen()) {
            return null;
        }
        String name = null;
        try {
            name = getName(joinPoint);
        } catch (Exception e) {
        }
        String func = null;
        try {
            func = getFunc(joinPoint);
        } catch (Exception e) {
        }
        return callFunctionAndMarkResult(joinPoint, getFuncName(joinPoint), name, func);
    }

    protected Object callFunctionAndMarkResult(ProceedingJoinPoint joinPoint, String funcName, String name, String func) throws Throwable {
        long start = System.currentTimeMillis();
        try {
            Object resultObject = joinPoint.proceed();
            Map<String, Object> paramsMap = isParamsOpen() ? getParamsMap(joinPoint.getArgs(), resultObject) : null;
            logger.info(name + " " + func + " " + new Date() + " " + paramsMap.toString());
            return resultObject;
        } catch (Exception Exception) {
            Map<String, Object> paramsMap = isParamsOpen() ? getParamsMap(joinPoint.getArgs(), null) : null;
            //异常日志 一定打印日志
            logger.warning(name + " " + func + " " + new Date() + " " + paramsMap.toString());
            throw new RuntimeException();
        } catch (Throwable throwable) {
            Map<String, Object> paramsMap = isParamsOpen() ? getParamsMap(joinPoint.getArgs(), null) : null;
            //异常日志 一定打印日志
            logger.warning(name + " " + func + " " + new Date() + " " + paramsMap.toString());
            throw throwable;
        } finally {
        }
    }

    // 取注解上的对象
    protected String getName(ProceedingJoinPoint joinPoint) {
        try {
            return ((TestServiceWatcher) getAnnotation(joinPoint, TestServiceWatcher.class)).annoArg0();
        } catch (NoSuchMethodException e) {
            return "";
        }
    }

    protected String getFunc(ProceedingJoinPoint joinPoint) {
        try {
            return ((TestServiceWatcher) getAnnotation(joinPoint, TestServiceWatcher.class)).annoArg1();
        } catch (NoSuchMethodException e) {
            return "";
        }
    }

    /**
     * 是否开启日志记录,可以通过配置文件的方式赋值
     */
    protected boolean isParamsOpen() {
        // 获取配置文件
        return true;
    }

    /**
     * 获取关键入参,用于记录在日志中
     */
    protected Map<String, Object> getParamsMap(Object args, Object resultObject) {
        Map<String, Object> paramsMap = new HashMap<>(16);
        try {
            paramsMap.put("input params", args == null ? "null" : args);
            paramsMap.put("result", resultObject == null ? "null" : resultObject);
        } catch (Exception e) {
        }
        return paramsMap;
    }

    protected String getFuncName(ProceedingJoinPoint joinPoint) {
        String className = ((MethodSignature) joinPoint.getSignature()).getMethod().getDeclaringClass().getName();
        className = className.substring(className.lastIndexOf(".") + 1);
        return className + "." + ((MethodSignature) joinPoint.getSignature()).getMethod().getName();
    }

    /**
     * 获取切点注解
     */
    protected Object getAnnotation(ProceedingJoinPoint joinPoint, Class annotation) throws NoSuchMethodException {
        String methodName = joinPoint.getSignature().getName();
        Class<?> classTarget = joinPoint.getTarget().getClass();
        Class<?>[] par = ((MethodSignature) joinPoint.getSignature()).getParameterTypes();
        Method objMethod = classTarget.getMethod(methodName, par);
        return objMethod.getAnnotation(annotation);
    }
}
  • 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
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
给业务方法增加注解
@Service
public class UserServiceImpl implements UserService {
    @Override
    // 新增的切面注解
    @TestServiceWatcher(annoArg0 = "参数0",annoArg1 = "参数1")
    public String queryAllUser() {
        return "{all}";
    }

    @Override
    // 新增的切面注解
    @TestServiceWatcher(annoArg0 = "参数0",annoArg1 = "参数1")
    public String queryUserById(String id) {
        return "user:"+id;
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

调用接口结果验证
在这里插入图片描述

无参方法

2021-06-14 20:21:37.473  INFO 2932 --- [nio-8091-exec-1] AppServiceWatcherLogger                  : 参数0 参数1 Mon Jun 14 20:21:37 CST 2021 {result={all}, input params=[Ljava.lang.Object;@6c7428b3}
  • 1

有参方法

2021-06-14 20:22:27.655  INFO 2932 --- [nio-8091-exec-2] AppServiceWatcherLogger                  : 参数0 参数1 Mon Jun 14 20:22:27 CST 2021 {result=user:2, input params=[Ljava.lang.Object;@45ef4fca}
  • 1

实在懒得写的就下源码,非常简单就不传git了
https://download.csdn.net/download/wdays83892469/19651108

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/266731
推荐阅读
相关标签
  

闽ICP备14008679号