使用AOP和注解动态打印日志

使用AOP和注解动态打印日志

主要打印类名、方法名、请求url、入参以及花费时间

@Component
@Aspect
@Slf4j
@RequiredArgsConstructor
public class LogAspect {
    
    private final ObjectMapper objectMapper;

    @Pointcut("@annotation(com.iot.cpe.common.MyLog)")
    public void aspect() {
    }

    @Around("aspect()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert attributes != null;
        HttpServletRequest request = attributes.getRequest();
        Signature signature = joinPoint.getSignature();
        //类名
        String typeName = signature.getDeclaringType().getSimpleName();
        //方法名
        String methodName = signature.getName();
        //请求url
        String url = request.getRequestURI();
        //入参列表
        String[] paramNames = ((MethodSignature) signature).getParameterNames();
        Object[] paramValues = joinPoint.getArgs();

        StringBuilder requestLog = new StringBuilder();
        requestLog.append("【").append(typeName).append("-").append(methodName).append("】 URL:").append(url).append(", Param:{");
        int paramLength = null == paramNames ? 0 : paramNames.length;
        if (paramLength != 0) {
            for (int i = 0; i < paramLength - 1; i++) {
                requestLog.append(paramNames[i]).append("=").append(objectMapper.writeValueAsString(paramValues[i])).append(", ");
            }
            requestLog.append(paramNames[paramLength - 1]).append("=").append(objectMapper.writeValueAsString(paramValues[paramLength - 1])).append("}");
        }
        log.info(requestLog.toString());

        Object proceed = joinPoint.proceed();
        long end = System.currentTimeMillis();
        //打印花费时间
        log.info("【{}-{}】 spend time:{}ms", typeName, methodName, end - start);
        return proceed;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值