使用SpringMVC对请求做处理时,都会记录请求和响应数据,保存到日志,方便开发排查问题,方便BUG的定位等,而使用AOP完成很明显是最方便的
代码示例
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
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.Objects;
/**
* 请求参数、响应参数
*/
@Slf4j
@Aspect
@Component
public class WebLogAspect {
@Around("execution(* com.gxzn.controller..*.*(..))")
public Object logUpdateUser(ProceedingJoinPoint joinPoint) throws Throwable {
// 开始时间
long startTime = System.currentTimeMillis();
// 请求地址
HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
String path = request.getRequestURI();
// 目标参数
Object[] args = joinPoint.getArgs();
log.debug("请求:{} ---> {}", path, args);
// 调用目标方法
Object result = joinPoint.proceed();
// 结束时间
long endTime = System.currentTimeMillis();
log.debug("响应:{} ---> {} ---> 耗时:{}", path, result, endTime - startTime);
return result;
}
}
需要依赖
<!--AOP-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>