Aop 获取接口的执行时间、入参、响应

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");
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值