Spring Boot AOP 实现 API 请求日志切面

Spring Boot AOP 实现 API 请求日志切面

前言

在后端业务中,对每次请求的入参、被请求类、方法,以及出参、执行耗时等信息进行日志打印,是很有必要的首先。首先,它提供了系统运行中的一份关键数据,帮助了解API调用的顺序、参数、响应等信息,对于追踪和定位问题非常有帮助。其次,API请求日志可以用于系统的性能分析与优化,我们可以根据日志信息,定位耗时较长的接口,并对其进行优化。

今天我们就来实现如用使用 Spring 中的 AOP 来对接口进行自动日志生成。

AOP

什么是 AOP?

AOP(Aspect-Oriented Programming,面向切面编程)是一个编程范式,它提供了一种能力,让开发者能够模块化跨多个对象的横切关注点(例如日志、事务管理、安全等)。

AOP 的主要概念

  • 切点 (Pointcuts) : 切入点描述了在哪些连接点(方法执行、字段访问等)上应用切面的逻辑。在Spring AOP中,切入点使用表达式语言来定义。例如,可以指定一个包路径、类、接口或注解来选择特定的切入点。
  • 通知 (Advices) : 定义在特定切点上要执行的代码。有如下几种类型:前置通知(Before)、后置通知(After)、返回通知(AfterReturning)、异常通知(AfterThrowing)和环绕通知(Around)。
  • 切面 (Aspects) : 切面将切点和通知结合起来,定义了在何处和何时应用特定的逻辑。

实战

环境与依赖

  1. 环境
  • java 8
  • Spring Boot 2.6.13
  1. maven 依赖
xml 复制代码
<dependencies>
    <!-- commons-langs 工具库 -->
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
    </dependency>
    
    <!-- AOP 切面 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>
​
    <!-- knife4j -->
    <dependency>
        <groupId>com.github.xiaoymin</groupId>
        <artifactId>knife4j-openapi2-spring-boot-starter</artifactId>
        <version>4.3.0</version>
    </dependency>
    
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
​
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
​
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>
  1. application.yml
yaml 复制代码
spring:
  application:
    name: aop-log-demo
  # 支持 swagger3
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher

knife4j 配置类

less 复制代码
/**
 * Knief4j Api文档配置
 * 默认访问 <a href="http://localhost:8080/doc.html"/>
 */
@Configuration
@EnableSwagger2WebMvc
@Profile({"dev"})
public class Knife4jConfig {
​
    @Bean
    public Docket createApiDoc() {
        return new Docket(DocumentationType.SWAGGER_2).apiInfo(buildApiInfo()).select()
                // Controller 扫描包路径
                .apis(RequestHandlerSelectors.basePackage("controller路径")).paths(PathSelectors.any()).build();
    }
​
    private ApiInfo buildApiInfo() {
        return new ApiInfoBuilder().title("项目名").description("项目描述").termsOfServiceUrl("你的服务url").contact(new Contact("你的用户名", "https://github.com/limincai", "你的邮箱")).version("版本号").build();
    }
}

日志切面

aspect 注解说明

在配置 AOP 切面之前,我们需要了解下 aspectj 相关注解的作用:

  • @Aspect:声明该类为一个切面类;
  • @Pointcut:定义一个切点,后面跟随一个表达式,表达式可以定义为切某个注解,也可以切某个 package 下的方法;

切点定义好后,就是围绕这个切点做文章了:

  • @Before: 在切点之前,织入相关代码;
  • @After: 在切点之后,织入相关代码;
  • @AfterReturning: 在切点返回内容后,织入相关代码,一般用于对返回值做些加工处理的场景;
  • @AfterThrowing: 用来处理当织入的代码抛出异常后的逻辑处理;
  • @Around: 环绕,可以在切入点前后织入代码,并且可以自由的控制何时执行切点;

定义日志切面类

less 复制代码
/**
 * 请求相应日志 AOP
 */
@Aspect
@Component
@Slf4j
public class LogAop {
​
    /**
     * 执行拦截
     */
    @Around("execution(* com.mincai.aoplogdemo.controller.*.*(..))")
    public Object doInterceptor(ProceedingJoinPoint point) throws Throwable {
        // 计时
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        // 获取请求路径
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest httpServletRequest = ((ServletRequestAttributes) requestAttributes).getRequest();
        // 生成请求唯一 id
        String requestId = UUID.randomUUID().toString();
        String url = httpServletRequest.getRequestURI();
        // 获取请求参数
        Object[] args = point.getArgs();
        String reqParam = "[" + StringUtils.join(args, ", ") + "]";
        // 输出请求日志
        log.info("request start,id: {}, path: {}, ip: {}, params: {}", requestId, url,
                httpServletRequest.getRemoteHost(), reqParam);
        // 执行原方法
        Object result = point.proceed();
        // 输出响应日志
        stopWatch.stop();
        long totalTimeMillis = stopWatch.getTotalTimeMillis();
        log.info("request end, id: {}, cost: {}ms", requestId, totalTimeMillis);
        return result;
    }
}

测试

  1. 新增一个 User 类进行模拟数据
arduino 复制代码
​
/**
 * 用户实体类
 */
@Data
public class User {
​
    private String userAccount;
​
    private String password;
}
  1. 添加一个测试接口
less 复制代码
@RestController
@Slf4j
public class DemoController {
​
    @PostMapping("/user/login")
    public Object userLogin(@RequestBody User user) {
        if ("limincai".equals(user.getUserAccount()) && "limincai".equals(user.getPassword())) {
            return true;
        }
        throw new RuntimeException("账号或密码错误");
    }
}

目录结构如图所示

  1. 启动项目,测试接口

浏览器访问 http://localhost:8080/doc.html

找到写好的测试接口传入参数进行测试

可以看到,在控制台中,打印出了请求ip,请求资源,参数和请求耗时等信息。

大功告成!

相关推荐
Amagi.几秒前
Spring中Bean的作用域
java·后端·spring
2402_8575893624 分钟前
Spring Boot新闻推荐系统设计与实现
java·spring boot·后端
繁依Fanyi28 分钟前
旅游心动盲盒:开启个性化旅行新体验
java·服务器·python·算法·eclipse·tomcat·旅游
J老熊32 分钟前
Spring Cloud Netflix Eureka 注册中心讲解和案例示范
java·后端·spring·spring cloud·面试·eureka·系统架构
蜜桃小阿雯35 分钟前
JAVA开源项目 旅游管理系统 计算机毕业设计
java·开发语言·jvm·spring cloud·开源·intellij-idea·旅游
CoderJia程序员甲35 分钟前
重学SpringBoot3-集成Redis(四)之Redisson
java·spring boot·redis·缓存
sco528236 分钟前
SpringBoot 集成 Ehcache 实现本地缓存
java·spring boot·后端
OLDERHARD1 小时前
Java - LeetCode面试经典150题 - 矩阵 (四)
java·leetcode·面试
原机小子1 小时前
在线教育的未来:SpringBoot技术实现
java·spring boot·后端
慕明翰1 小时前
Springboot集成JSP报 404
java·开发语言·spring boot