赞
踩
常用的添加日志埋点的位置是提供给外部服务调用的接口
这里用springboot的@RestController接口演示
添加aop相关依赖,包含Aspect等类
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<version>2.4.5</version>
</dependency>
添加接口相关依赖(任何实现方式均可)
<!-- 添加springboot的依赖 springmvc -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.4.5</version>
</dependency>
创建SpringBootApplication启动类
创建配置文件,指定端口等
server:
port: 8091
简单编写一个演示服务
略,返回一个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); } }
测试通过
注解扩展,对于自定义注解的类,注解中加自定义属性,增加调用日志,包括方法名,参数,返回结果,调用时间等
这里添加自定义的属性,实现更多扩展
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface TestServiceWatcher {
String annoArg0();
String annoArg1();
}
切面类打印语句,项目中用自己的日志框架
logger.info(annoArg0+" "+annoArg1+" "+ new Date()+" "+paramsMap.toString());
打印结果
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); } }
@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; } }
调用接口结果验证
无参方法
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}
有参方法
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}
实在懒得写的就下源码,非常简单就不传git了
https://download.csdn.net/download/wdays83892469/19651108
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。