SpringBoot基础系列之AOP结合SpEL实现日志输出中两点注意事项

本文涉及的产品
日志服务 SLS,月写入数据量 50GB 1个月
简介: 使用 AOP 来打印日志大家一把都很熟悉了,最近在使用的过程中,发现了几个有意思的问题,一个是 SpEL 的解析,一个是参数的 JSON 格式输出

image.png


使用 AOP 来打印日志大家一把都很熟悉了,最近在使用的过程中,发现了几个有意思的问题,一个是 SpEL 的解析,一个是参数的 JSON 格式输出


I. 项目环境



1. 项目依赖


本项目借助SpringBoot 2.2.1.RELEASE + maven 3.5.3 + IDEA进行开发

开一个 web 服务用于测试


<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>
复制代码


II. AOP & SpEL



关于 AOP 与 SpEL 的知识点,之前都有过专门的介绍,这里做一个聚合,一个非常简单的日志输出切面,在需要打印日志的方法上,添加注解@Log,这个注解中定义一个key,作为日志输出的标记;key 支持 SpEL 表达式


1. AOP 切面


注解定义

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {
    String key();
}
复制代码


切面逻辑

@Slf4j
@Aspect
@Component
public class AopAspect implements ApplicationContextAware {
    private ExpressionParser parser = new SpelExpressionParser();
    private ParameterNameDiscoverer parameterNameDiscoverer = new DefaultParameterNameDiscoverer();
    @Around("@annotation(logAno)")
    public Object around(ProceedingJoinPoint joinPoint, Log logAno) throws Throwable {
        long start = System.currentTimeMillis();
        String key = loadKey(logAno.key(), joinPoint);
        try {
            return joinPoint.proceed();
        } finally {
            log.info("key: {}, args: {}, cost: {}", key,
                    JSONObject.toJSONString(joinPoint.getArgs()),
                    System.currentTimeMillis() - start);
        }
    }
    private String loadKey(String key, ProceedingJoinPoint joinPoint) {
        if (key == null) {
            return key;
        }
        StandardEvaluationContext context = new StandardEvaluationContext();
        context.setBeanResolver(new BeanFactoryResolver(applicationContext));
        String[] params = parameterNameDiscoverer.getParameterNames(((MethodSignature) joinPoint.getSignature()).getMethod());
        Object[] args = joinPoint.getArgs();
        for (int i = 0; i < args.length; i++) {
            context.setVariable(params[i], args[i]);
        }
        return parser.parseExpression(key).getValue(context, String.class);
    }
    private ApplicationContext applicationContext;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
复制代码


上面这个逻辑比较简单,和大家熟知的使用姿势没有太大的区别


2. StandardEvaluationContext 安全问题


关于StandardEvaluationContext的注入问题,有兴趣的可以查询一下相关文章;对于安全校验较高的,要求只能使用SimpleEvaluationContext,使用它的话,SpEL 的能力就被限制了


如加一个测试

@Data
@Accessors(chain = true)
public class DemoDo {
    private String name;
    private Integer age;
}
复制代码


服务类

@Service
public class HelloService {
    @Log(key = "#demo.getName()")
    public String say(DemoDo demo, String prefix) {
        return prefix + ":" + demo;
    }
}
复制代码


为了验证SimpleEvaluationContext,我们修改一下上面的loadKeys方法

private String loadKey(String key, ProceedingJoinPoint joinPoint) {
    if (key == null) {
        return key;
    }
    SimpleEvaluationContext context = new SimpleEvaluationContext.Builder().build();
    String[] params = parameterNameDiscoverer.getParameterNames(((MethodSignature) joinPoint.getSignature()).getMethod());
    Object[] args = joinPoint.getArgs();
    for (int i = 0; i < args.length; i++) {
        context.setVariable(params[i], args[i]);
    }
    return parser.parseExpression(key).getValue(context, String.class);
}
复制代码


启动测试

@SpringBootApplication
public class Application {
    public Application(HelloService helloService) {
        helloService.say(new DemoDo().setName("一灰灰blog").setAge(18), "welcome");
    }
    public static void main(String[] args) {
        SpringApplication.run(Application.class);
    }
}
复制代码

网络异常,图片无法展示
|


直接提示方法找不到!!!


3. gson 序列化问题


上面的 case 中,使用的 FastJson 对传参进行序列化,接下来我们采用 Gson 来做序列化


<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
</dependency>
复制代码

然后新增一个特殊的方法

@Service
public class HelloService {
    /**
     * 字面量,注意用单引号包裹起来
     * @param key
     * @return
     */
    @Log(key = "'yihuihuiblog'")
    public String hello(String key, HelloService helloService) {
        return key + "_" + helloService.say(new DemoDo().setName(key).setAge(10), "prefix");
    }
}
复制代码


注意上面方法的第二个参数,非常有意思的是,传参是自己的实例;再次执行

public Application(HelloService helloService) {
    helloService.say(new DemoDo().setName("一灰灰blog").setAge(18), "welcome");
    String ans = helloService.hello("一灰灰", helloService);
    System.out.println(ans);
}
复制代码


直接抛了异常

网络异常,图片无法展示
|

这就很尴尬了,一个输出日志的辅助工具,因为序列化直接导致接口不可用,这就不优雅了;而我们作为日志输出的切面,又是没有办法控制这个传参的,没办法要求使用的参数,一定能序列化,这里需要额外注意 (比较好的方式就是简单对象都实现

toString,然后输出 toString 的结果;而不是 json 串)


4. 小结


虽然上面一大串的内容,总结下来,也就两点


  • SpEL 若采用的是SimpleEvaluationContext,那么注意 spel 的功能是减弱的,一些特性不支持
  • 若将方法参数 json 序列化输出,那么需要注意某些类在序列化的过程中,可能会抛异常

(看到这里的小伙伴,不妨点个赞,顺手关注下微信公众号”一灰灰 blog“,我的公众号已经寂寞的长草了 😭)



相关实践学习
日志服务之使用Nginx模式采集日志
本文介绍如何通过日志服务控制台创建Nginx模式的Logtail配置快速采集Nginx日志并进行多维度分析。
目录
打赏
0
0
0
0
13
分享
相关文章
Spring Boot中的AOP实现
Spring AOP(面向切面编程)允许开发者在不修改原有业务逻辑的情况下增强功能,基于代理模式拦截和增强方法调用。Spring Boot通过集成Spring AOP和AspectJ简化了AOP的使用,只需添加依赖并定义切面类。关键概念包括切面、通知和切点。切面类使用`@Aspect`和`@Component`注解标注,通知定义切面行为,切点定义应用位置。Spring Boot自动检测并创建代理对象,支持JDK动态代理和CGLIB代理。通过源码分析可深入了解其实现细节,优化应用功能。
101 6
SpringBoot入门(6)- 添加Logback日志
SpringBoot入门(6)- 添加Logback日志
138 5
Spring Boot中的日志框架选择
在Spring Boot开发中,日志管理至关重要。常见的日志框架有Logback、Log4j2、Java Util Logging和Slf4j。选择合适的日志框架需考虑性能、灵活性、社区支持及集成配置。本文以Logback为例,演示了如何记录不同级别的日志消息,并强调合理配置日志框架对提升系统可靠性和开发效率的重要性。
Spring Boot 3 集成Spring AOP实现系统日志记录
本文介绍了如何在Spring Boot 3中集成Spring AOP实现系统日志记录功能。通过定义`SysLog`注解和配置相应的AOP切面,可以在方法执行前后自动记录日志信息,包括操作的开始时间、结束时间、请求参数、返回结果、异常信息等,并将这些信息保存到数据库中。此外,还使用了`ThreadLocal`变量来存储每个线程独立的日志数据,确保线程安全。文中还展示了项目实战中的部分代码片段,以及基于Spring Boot 3 + Vue 3构建的快速开发框架的简介与内置功能列表。此框架结合了当前主流技术栈,提供了用户管理、权限控制、接口文档自动生成等多项实用特性。
87 8
什么是AOP?如何与Spring Boot一起使用?
什么是AOP?如何与Spring Boot一起使用?
113 5
SpringBoot入门(6)- 添加Logback日志
SpringBoot入门(6)- 添加Logback日志
78 1
SpringBoot项目使用AOP及自定义注解保存操作日志
SpringBoot项目使用AOP及自定义注解保存操作日志
79 1
SpringBoot | SpringBoot 是如何实现日志的?
休息日闲着无聊看了下 SpringBoot 中的日志实现,把我的理解跟大家说下。
SpringBoot | SpringBoot 是如何实现日志的?
基于SpringBoot实现让日志像诗一样有韵律
基于SpringBoot实现让日志像诗一样有韵律
198 0
基于SpringBoot实现让日志像诗一样有韵律(日志追踪)
基于SpringBoot实现让日志像诗一样有韵律(日志追踪)
332 0

热门文章

最新文章

AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等