引言
在项目中,不管是在开发阶段和后续的维护阶段,前后端调用的出入参都是有很大作用的,可以帮助我们及时排查和定位问题。
常见的做法是通过AOP实现,在Controller方法执行前后打印出入参。由于实现比较简单,需要了解AOP,网上的教程也很多,这里就不多说,直接给出一个示例,以供大家参考。
环境
组件名称 | 版本 |
---|---|
JDK | 17 |
SpringBoot | 3.2.0 |
实现
说明:
-
切点是定义在使用
@RestController
注解类的所有方法上 -
@Before
注解指定的方法在切面切入目标方法之前执行 -
@AfterReturning
捕获方法执行后的返回值
ini
复制代码
package com.zl.test.config.log; import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSONObject; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; 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; import org.springframework.web.multipart.MultipartFile; import java.util.Map; @Slf4j @Aspect @Component public class AopLogConfig { @Pointcut("within(@org.springframework.web.bind.annotation.RestController *)") public void controllerPointCut() { } @Before(value = "controllerPointCut()") public void before(JoinPoint joinPoint) { ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); String url = requestAttributes.getRequest().getRequestURL().toString(); Map<String, String[]> parameterMap = requestAttributes.getRequest().getParameterMap(); Object[] args = joinPoint.getArgs(); Object[] arguments = new Object[args.length]; for (int i = 0; i < args.length; i++) { if (args[i] instanceof ServletRequest || args[i] instanceof ServletResponse || args[i] instanceof MultipartFile) { continue; } arguments[i] = args[i]; } String body = JSONObject.toJSONString(arguments); log.info("请求URL: {}, 请求参数: {}, 请求body: {}", url, JSON.toJSONString(parameterMap), body); } @AfterReturning(returning = "res", pointcut = "controllerPointCut()") public void after(Object res) { ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); String url = requestAttributes.getRequest().getRequestURL().toString(); log.info("请求URL: {}, 返回值: {}", url, JSON.toJSONString(res)); } }