package com.jxz.manager.aop; import com.fasterxml.jackson.databind.ObjectMapper; import com.jxz.common.constants.SysConst; import com.jxz.core.entity.security.AuthUserDetail; 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.security.core.context.SecurityContextHolder; 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(); Integer userId = null; String userName = ""; try { AuthUserDetail principal = (AuthUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); userId = principal.getAuthUserId(); userName = principal.getUsername(); } catch (Exception e) { log.warn("Could not get user login information, maybe not logged in, e", e); } if (totalRuntime > SysConst.MAX_INTERFACE_RUNTIME) { log.error(getClass().getSimpleName() + " totalRuntime: {} ms, userId: {}, userName: {}, PointcutPath: {}, PointcutArgs: {}, response: {}", totalRuntime, userId, userName, pointcutPath, joinPoint.getArgs(), response); } else { log.info(getClass().getSimpleName() + " totalRuntime: {} ms, userId: {}, userName: {}, PointcutPath: {}", totalRuntime, userId, userName, pointcutPath); } } else { log.warn("response: null"); } } }
Aop 获取接口的执行时间、入参、响应
最新推荐文章于 2024-06-24 14:51:27 发布