@Component
@Aspect
@Slf4j
public class RequestAspect {
@Pointcut("within(@org.springframework.web.bind.annotation.RestController *) || within(@org.springframework.stereotype.Controller *)")
public void logController() {
}
@Before("logController()")
public void logBefore(JoinPoint joinPoint) {
Object[] args = null;
try {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
//url
log.info("请求信息:url={},method={}", request.getRequestURI(), request.getMethod());
RequestEnv.addConfig("startTime", System.currentTimeMillis());
RequestEnv.addConfig("requestUri", request.getRequestURI());
ArrayList<String> params = new ArrayList<>();
RequestEnv.addConfig("params", params);
//参数
args = joinPoint.getArgs();
if (args != null && args.length != 0) {
for (int i = 0; i < args.length; i++) {
Object argStr = args[i];
//特殊参数不打印
if (
(argStr instanceof MultipartFile)
|| (argStr instanceof BindingResult)
|| (argStr instanceof Model)
|| (argStr instanceof ModelMap)
|| (argStr instanceof ModelAndView)
|| (argStr instanceof HttpServletRequest)
|| (argStr instanceof HttpServletResponse)
|| (argStr instanceof HttpSession)
) {
continue;
}
try {
argStr = JSON.toJSONString(args[i]);
} catch (Exception e) {
log.error("参数获取失败:{},{}", args[i], e);
}
params.add(argStr.toString());
log.info("请求参数{}:{}", i + 1, argStr.toString().length() > 2000 ? argStr.toString().substring(0, 2000) : argStr);
}
}
} catch (Exception e) {
log.error("请求参数解析出错:{},{}", args, e);
}
}
@AfterReturning(value = "logController()", returning = "object")
public void logAfter(JoinPoint joinPoint, Object object) {
String rstStr = JSON.toJSONString(object);
Long startTime = RequestEnv.getConfig("startTime");
String requestUri = RequestEnv.getConfig("requestUri");
List<String> params = RequestEnv.getConfig("params");
if (Objects.nonNull(startTime) && StringUtils.isNotBlank(requestUri)) {
long times = System.currentTimeMillis() - startTime;
if (times > 1000) {
log.warn("[接口检测警告],接口:{},请求时长:{},请求参数:{},返回内容:{}", requestUri, times, JSON.toJSONString(params), rstStr);
} else {
log.info("接口:{},请求时长:{},返回内容:{}", requestUri, times, rstStr.length() > 2000 ? rstStr.substring(0, 2000) : rstStr);
}
} else {
log.info("返回内容:{}", rstStr.length() > 2000 ? rstStr.substring(0, 2000) : rstStr);
}
}
}
03-23
225
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)