来个切面日志打印请求和响应信息
为了偷个懒,不用每次在请求接口和响应信息的时候都打印一下日志信息,索性就用切面来实现,这样爽歪歪。
一、依赖
我用的是jdk11,springboot是2.7.13的版本,对应引入的切面的依赖是:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
二、切面
import com.alibaba.fastjson2.JSON;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
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.util.Arrays;
import java.util.Objects;
@Aspect
@Component
public class InterfaceAspect {
private final Logger logger = LoggerFactory.getLogger(InterfaceAspect.class);
@Around("execution(public * com.demo.cn.controller..*.*(..))")
public Object controllerLog(ProceedingJoinPoint pdj) throws Throwable{
HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
long startTime = System.currentTimeMillis();//开始时间
//获取参数数组
Object[] args = pdj.getArgs();
//执行原方法并获取返回结果
Object ret = pdj.proceed(args);
long endTime = System.currentTimeMillis();
// 记录下请求内容
logger.info("请求信息: URL={}, IP={}, PARAMS={}, CLASS_METHOD={}, SPEND_TIME={}",
request.getRequestURL(),
request.getRemoteAddr(),
Arrays.toString(args),
pdj.getSignature().getDeclaringTypeName() + "." + pdj.getSignature().getName(),
(endTime - startTime) + "毫秒");
logger.info("响应结果:{}", JSON.toJSONString(ret.toString()));
return ret;
}
就这样就可以了,很简单,却很方便排查问题。
-------------你知道的越多,不知道的越多--------------