优秀的编程知识分享平台

网站首页 > 技术文章 正文

如何在Spring Boot中实现自定义的日志切面?

nanyue 2024-12-29 04:54:04 技术文章 4 ℃

日志作为现在很多微服务架构中进行系统监控、拍错和性能分析的关键手段之一,如何记录日志就成了需要我们注意的关键,在Spring Boot中提供了非常丰富日志操作功能,并且支持了与不同日志框架的集成,但是对于一些特定的场景,我们还需要实现一些自定的日志记录操作,例如对于日志时间的记录、输入输出参数的记录,方法执行时间的记录等等。这个时候就需要我们通过AOP来实现自定义的日志切面来实现相关的操作了。

AOP基础知识简述

AOP(Aspect-Oriented Programming,面向切面编程)是一种编程范式,通过将横切关注点(例如日志、安全性、事务等)从业务逻辑中分离出来的方式,然后通过声明式的方式将横切关注点应用到目标方法上,而无需修改目标方法的代码来实现日志、安全、事务等操作的管理。

在Spring中,AOP的核心概念包括,如下几个。

  • 切面(Aspect):横切关注点的模块化,通常包含一个或多个切点和通知。
  • 切点(Pointcut):定义在哪些方法上应用通知,通常是方法的执行。
  • 通知(Advice):切面中具体的操作,分为前置通知、后置通知、异常通知等。

下面我们就来看看如何在Spring Boot中实现一个简单的日志切面操作。

在Spring Boot中配置AOP

在Spring Boot中默认支持了Spring AOP,所以我们就可以快速实现AOP操作。Spring Boot中默认启动了AOP的支持,所以不需要手动操作只需要在配置类上添加@EnableAspectJAutoProxy注解就可以开启AOP的相关操作。如下所示。

@Configuration
@EnableAspectJAutoProxy
public class AopConfig {
}

自定义日志切面的实现

接下来,我们就需要创建一个简单的日志切面类来实现对于方法执行时间、参数记录等操作,如下所示。

创建日志切面类

创建一个切面类,并使用@Aspect注解标记它为切面,然后再这个切面上就可以通过@Around注解来指定相关拦截方法进行日志的记录。

@Aspect
@Component
public class LoggingAspect {

    private static final Logger logger = LoggerFactory.getLogger(LoggingAspect.class);

    // 定义切点,拦截所有public方法
    @Pointcut("execution(public * com.example.demo.service..*(..))")
    public void loggableMethods() {}

    @Around("loggableMethods()")
    public Object logMethodExecution(JoinPoint joinPoint) throws Throwable {
        // 记录方法执行前的日志
        long startTime = System.currentTimeMillis();
        logger.info("Executing method: {} with arguments: {}", joinPoint.getSignature(), Arrays.toString(joinPoint.getArgs()));

        // 执行目标方法
        Object result = joinPoint.proceed();

        // 记录方法执行后的日志
        long endTime = System.currentTimeMillis();
        logger.info("Method executed: {} and returned: {} in {} ms", joinPoint.getSignature(), result, endTime - startTime);

        return result;
    }
}

配置日志记录

这里我们通过SLF4J作为日志操作的框架,在之前的博客中我们介绍过Spring Boot中默认支持的是Logback日志框架,我们可以通过如下的方式来调整日志级别以及日志的输出格式。

logging.level.com.example.demo.aspect=INFO
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} - %msg%n

优化和扩展

处理方法异常

如果在方法执行的过程中出现了异常,我们也可以通过在切面中对异常进行捕获并且对日志进行记录。可以通过@Around通知中的Throwable参数来对异常操作进行日志记录,如下所示。

@Around("loggableMethods()")
public Object logMethodExecution(JoinPoint joinPoint) throws Throwable {
    long startTime = System.currentTimeMillis();
    logger.info("Executing method: {} with arguments: {}", joinPoint.getSignature(), Arrays.toString(joinPoint.getArgs()));

    try {
        Object result = joinPoint.proceed();
        long endTime = System.currentTimeMillis();
        logger.info("Method executed: {} and returned: {} in {} ms", joinPoint.getSignature(), result, endTime - startTime);
        return result;
    } catch (Throwable throwable) {
        logger.error("Method execution failed: {} with exception: {}", joinPoint.getSignature(), throwable.getMessage());
        throw throwable; // Re-throw the exception after logging
    }
}

记录特定的返回值类型

当然,除了上面的操作之外,我们还可以对返回值或者是返回的方法进行日志的过滤,例如我们可以对返回为String类型的数据进行过滤其他的操作正常记录。

@Around("loggableMethods()")
public Object logMethodExecution(JoinPoint joinPoint) throws Throwable {
    Object result = joinPoint.proceed();

    // 只记录返回类型为String的结果
    if (result instanceof String) {
        logger.info("Method returned a String: {}", result);
    }

    return result;
}

自定义注解控制日志

当然,通过上面的方式我们只是简单的记录了指定的方法进行日志记录,但是并不是想让所有的方法都进行记录,所以需要通过注解的方式来进行有选择性的日志记录,这个时候,我们就可以通过自定义的日志注解和切点表达式来进行日志的选择性记录。如下所示。

创建自定义注解

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 LogExecution {
}

然后,修改切点表达式,使其仅拦截带有@LogExecution注解的方法,如下所示。

@Pointcut("@annotation(com.example.demo.annotation.LogExecution)")
public void loggableMethodsWithAnnotation() {}

@Around("loggableMethodsWithAnnotation()")
public Object logMethodExecutionWithAnnotation(JoinPoint joinPoint) throws Throwable {
    long startTime = System.currentTimeMillis();
    logger.info("Executing method: {} with arguments: {}", joinPoint.getSignature(), Arrays.toString(joinPoint.getArgs()));
    Object result = joinPoint.proceed();
    long endTime = System.currentTimeMillis();
    logger.info("Method executed: {} and returned: {} in {} ms", joinPoint.getSignature(), result, endTime - startTime);
    return result;
}

接下来只需要在需要进行日志记录的方法上添加上指定的@LogExecution注解就可以实现选择性的日志记录操作了。

package com.example.demo.service;

import com.example.demo.annotation.LogExecution;
import org.springframework.stereotype.Service;

@Service
public class MyService {

    @LogExecution
    public String someMethod(String input) {
        return "Processed: " + input;
    }
}

总结

通过Spring AOP,我们可以在Spring Boot应用中实现自定义的日志切面操作,上面我们介绍了一个简单的日志切面操作,当然在实际场景中我们还可以通过日志切面操作加上异步的方式将日志写入到远程记录中来帮助我们更好的分析记录日志。

最近发表
标签列表