【SpringBoot】SpringBoot中使用AOP实现日志记录功能
- 前言
- 一、AOP基本概念
- 二、项目准备
- 三、实现日志记录切面
- 1、创建自定义日志注解
- 2、实现日志切面
- 3、配置AOP
- 四、使用示例
- 1. 在Controller中使用
- 2. 在Service中使用
- 六、高级配置
- 1. 日志内容格式化
- 2. 异步日志记录
- 3. 日志脱敏处理
前言
在开发企业级应用时,完善的日志记录系统对于问题排查、系统监控和用户行为分析都至关重要。传统的日志记录方式往往需要在每个方法中手动添加日志代码,这不仅增加了代码量,也使得业务逻辑与日志记录代码耦合在一起。Spring
AOP(面向切面编程)为我们提供了一种优雅的解决方案,可以无侵入式地实现日志记录功能。
本文将详细介绍如何在SpringBoot项目中利用AOP实现统一的日志记录功能。
一、AOP基本概念
在开始实现之前,我们先了解几个AOP的核心概念:
-
切面(Aspect):横切关注点的模块化,如日志记录就是一个切面
-
连接点(Joinpoint):程序执行过程中的某个特定点,如方法调用或异常抛出
-
通知(Advice):在切面的某个连接点上执行的动作
-
切入点(Pointcut):匹配连接点的谓词,用于确定哪些连接点需要执行通知
-
目标对象(Target Object):被一个或多个切面通知的对象
二、项目准备
需要创建一个SpringBoot项目,添加以下依赖:
<dependencies><!-- Spring Boot Starter Web --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- Spring Boot Starter AOP --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId></dependency><!-- Lombok 简化代码 --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency>
</dependencies>
三、实现日志记录切面
1、创建自定义日志注解
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Log {/*** 操作名称* @return*/String operation() default "";/*** 操作的类型* @return*/BusinessType businessType() default BusinessType.OTHER;
}
2、实现日志切面
创建一个切面类,实现日志切面功能。
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;@Aspect
@Component
public class LoggingAspect {private static final Logger logger = LoggerFactory.getLogger(LoggingAspect.class);/*** 定义切入点:所有带有@Loggable注解的方法*/@Pointcut("@annotation(com.yourpackage.Loggable)")public void loggableMethods() {}/*** 环绕通知:记录方法执行前后的日志*/@Around("loggableMethods()")public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {MethodSignature signature = (MethodSignature) joinPoint.getSignature();Method method = signature.getMethod();Loggable loggable = method.getAnnotation(Loggable.class);String methodName = joinPoint.getTarget().getClass().getName() + "." + method.getName();// 记录方法开始日志if (loggable.recordParams()) {logger.info("===> 开始执行 {},参数: {}", methodName, Arrays.toString(joinPoint.getArgs()));} else {logger.info("===> 开始执行 {}", methodName);}long startTime = System.currentTimeMillis();try {// 执行目标方法Object result = joinPoint.proceed();// 记录方法结束日志long elapsedTime = System.currentTimeMillis() - startTime;if (loggable.recordResult()) {logger.info("<=== 执行完成 {},耗时: {}ms,结果: {}", methodName, elapsedTime, result);} else {logger.info("<=== 执行完成 {},耗时: {}ms", methodName, elapsedTime);}return result;} catch (Exception e) {// 记录异常日志long elapsedTime = System.currentTimeMillis() - startTime;logger.error("<=== 执行异常 {},耗时: {}ms,异常: {}", methodName, elapsedTime, e.getMessage(), e);throw e;}}/*** 对Controller层的方法进行日志记录*/@Pointcut("execution(* com.yourpackage.controller..*.*(..))")public void controllerLog() {}@Before("controllerLog()")public void doBefore(JoinPoint joinPoint) {// 获取请求信息ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();if (attributes == null) {return;}HttpServletRequest request = attributes.getRequest();// 记录请求信息logger.info("==============================请求开始==============================");logger.info("请求URL: {}", request.getRequestURL().toString());logger.info("HTTP方法: {}", request.getMethod());logger.info("IP地址: {}", request.getRemoteAddr());logger.info("类方法: {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());logger.info("请求参数: {}", Arrays.toString(joinPoint.getArgs()));}@AfterReturning(returning = "result", pointcut = "controllerLog()")public void doAfterReturning(Object result) {logger.info("返回结果: {}", result);logger.info("==============================请求结束==============================");}
}
3、配置AOP
确保SpringBoot应用启用了AOP支持(默认就是启用的),如果需要自定义配置,可以在application.properties中添加。
# AOP配置
spring.aop.auto=true
spring.aop.proxy-target-class=true
四、使用示例
1. 在Controller中使用
@RestController
@RequestMapping("/api/user")
public class UserController {@GetMapping("/{id}")@Loggable("根据ID获取用户信息")public User getUser(@PathVariable Long id) {// 业务逻辑return userService.getUserById(id);}@PostMapping@Loggable(value = "创建新用户", recordParams = false)public User createUser(@RequestBody User user) {// 业务逻辑return userService.createUser(user);}
}
2. 在Service中使用
@Service
public class UserService {@Loggable("根据ID查询用户")public User getUserById(Long id) {// 业务逻辑}@Loggable(value = "创建用户", recordResult = false)public User createUser(User user) {// 业务逻辑}
}
六、高级配置
1. 日志内容格式化
我们可以创建一个工具类来美化日志输出:
public class LogFormatUtils {public static String formatMethodCall(String className, String methodName, Object[] args) {StringBuilder sb = new StringBuilder();sb.append(className).append(".").append(methodName).append("(");if (args != null && args.length > 0) {for (int i = 0; i < args.length; i++) {if (i > 0) {sb.append(", ");}sb.append(formatArg(args[i]));}}sb.append(")");return sb.toString();}private static String formatArg(Object arg) {if (arg == null) {return "null";}// 对于基本类型和字符串直接返回if (arg instanceof Number || arg instanceof Boolean || arg instanceof Character || arg instanceof String) {return arg.toString();}// 对于集合和数组,只显示大小if (arg.getClass().isArray()) {return "array[" + Array.getLength(arg) + "]";}if (arg instanceof Collection) {return "collection[" + ((Collection<?>) arg).size() + "]";}if (arg instanceof Map) {return "map[" + ((Map<?, ?>) arg).size() + "]";}// 其他复杂对象只显示类名return arg.getClass().getSimpleName();}
}
然后在切面中使用:
@Around("loggableMethods()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {MethodSignature signature = (MethodSignature) joinPoint.getSignature();String methodCall = LogFormatUtils.formatMethodCall(joinPoint.getTarget().getClass().getSimpleName(),signature.getName(),joinPoint.getArgs());logger.info("===> 调用: {}", methodCall);// ... 其他逻辑
}
2. 异步日志记录
对于一些并发场景,可以考虑异步记录日志以减少性能影响:
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {@Overridepublic Executor getAsyncExecutor() {ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();executor.setCorePoolSize(5);executor.setMaxPoolSize(10);executor.setQueueCapacity(100);executor.setThreadNamePrefix("AsyncLogger-");executor.initialize();return executor;}
}// 然后在切面方法上添加@Async注解
@Async
@Around("loggableMethods()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {// 日志记录逻辑
}
3. 日志脱敏处理
对于敏感信息如手机号、身份证号等,需要进行脱敏处理:
public class SensitiveInfoUtils {private static final String PHONE_REGEX = "(\\d{3})\\d{4}(\\d{4})";private static final String ID_CARD_REGEX = "(\\d{4})\\d{10}(\\w{4})";public static String desensitize(Object arg) {if (arg == null) {return null;}String str = arg.toString();// 手机号脱敏if (str.matches("\\d{11}")) {return str.replaceAll(PHONE_REGEX, "$1****$2");}// 身份证号脱敏if (str.matches("\\d{18}|\\d{17}[xX]")) {return str.replaceAll(ID_CARD_REGEX, "$1**********$2");}// 其他敏感信息处理...return str;}
}// 在LogFormatUtils中使用
private static String formatArg(Object arg) {// ... 其他逻辑return SensitiveInfoUtils.desensitize(arg);
}