package com.jxz.manager.aop;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jxz.core.common.constants.SysConst;
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.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 获取接口的响应时间
*
* @author jiangXueZhi
* @date 2023/6/21
*/
@Aspect
@Component
@Slf4j
public class MgrRuntimeAop {
ThreadLocal<Long> startTime = new ThreadLocal<>();
private final ObjectMapper mapper;
@Autowired
public MgrRuntimeAop(ObjectMapper mapper) {
this.mapper = mapper;
}
@Pointcut(value = "execution(* com.jxz.manager.controller..*.*(..))")
public void executionService() {
}
@Before("executionService()")
public void doBefore(JoinPoint joinPoint) {
//开始计时
startTime.set(System.currentTimeMillis());
for (Object object : joinPoint.getArgs()) {
if (object instanceof MultipartFile
|| object instanceof HttpServletRequest
|| object instanceof HttpServletResponse) {
continue;
}
try {
if (log.isDebugEnabled()) {
log.debug(
joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName()
+ " : request parameter : " + mapper.writeValueAsString(object)
);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
@AfterReturning(returning = "response", pointcut = "executionService()")
public void doAfterReturning(JoinPoint joinPoint, Object response) throws Throwable {
if (response != null) {
long totalRuntime = System.currentTimeMillis() - startTime.get();
log.info("response parameter : " + mapper.writeValueAsString(response));
String pointcutPath = joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName();
if (totalRuntime > SysConst.MAX_INTERFACE_RUNTIME) {
log.error(getClass().getSimpleName() + " totalRuntime: {} ms, PointcutPath: {}, PointcutArgs: {}, response: {}", totalRuntime, pointcutPath, joinPoint.getArgs(), response);
} else {
log.info(getClass().getSimpleName() + " totalRuntime: {} ms, PointcutPath: {}", totalRuntime, pointcutPath);
}
} else {
log.warn("response: null");
}
}
}
AOP 监控接口的响应时间
最新推荐文章于 2024-05-23 09:15:38 发布