使用Spring的AOP打印HTTP接口出入參日志
前言
最近在維護一個運營端的系統,和前端聯調的過程中,經常需要排查一些交互上的問題,每次都得看前端代碼的傳參和后端代碼的出參,于是打算給HTTP接口加上出入參日志。
但看著目前的HTTP接口有點多,那么有什么快捷的方式呢?答案就是實用Spring的AOP功能,簡單實用。
思路
定義個一個SpringAOP的配置類,里邊獲取請求的URL、請求的入參、相應的出參,通過日志打印出來。
SpringBoot的aop依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
示例
1.編寫一個HTTP接口
定義了一個Controller,里邊就一個方法,方法請求類型是get,出入參都是簡單的一個字符串字段。
package com.example.springbootaoplog.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author hongcunlin
*/
@RestController
@RequestMapping("/index")
public class IndexController {
@GetMapping("/indexContent")
public String indexContent(String param) {
return "test";
}
}
2.編寫一個AOP日志配置
這算是本文的重點了,定義一個AOP的內容,首先是切點,再者是請求前日志打印,最后請求后日志打印
package com.example.springbootaoplog.config;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
/**
* aop日志打印配置
*
* @author hongcunlin
*/
@Slf4j
@Aspect
@Component
public class AopLogConfig {
/**
* 切點路徑:Controller層的所有方法
*/
@Pointcut("execution(public * com.example.springbootaoplog.controller.*.*(..))")
public void methodPath() {
}
/**
* 入參
*
* @param joinPoint 切點
*/
@Before(value = "methodPath()")
public void before(JoinPoint joinPoint) {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
String url = requestAttributes.getRequest().getRequestURL().toString();
log.info("請求 = {}, 入參 = {}", url, JSON.toJSONString(joinPoint.getArgs()));
}
/**
* 出參
*
* @param res 返回
*/
@AfterReturning(returning = "res", pointcut = "methodPath()")
public void after(Object res) {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
String url = requestAttributes.getRequest().getRequestURL().toString();
log.info("請求 = {}, 入參 = {}", url, JSON.toJSONString(res));
}
}
3.結果測試
我們通過瀏覽器的URL,針對我們編寫的http接口,發起一次get請求:
可以看到,日志里邊打印了我們預期的請求的URL和出入參了:
說明我們的程序是正確的了。
最后
本文分享了通過Spring的AOP功能,完成HTTP接口的出入參日志的打印的方法,同時也說明,越是基礎的東西,越是實用。