AOP+@注解 实现测试、日志和鉴权

2022-01-14134

@Aspect

@Component

@Slf4j

public class LoggerAspect {

 private static final Logger logger = LoggerFactory.getLogger(LoggerAspect.class);

    @Pointcut("@annotation(com.lqcoder.annotationdemo.annotation.OutputLog)")

    public void weblog(){

    }

    @Around("weblog()")

    public Object around(ProceedingJoinPoint point) throws Throwable {

        long beginTime = System.currentTimeMillis();

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        HttpServletRequest request = attributes.getRequest();

        List<Object> logArgs = Arrays.stream(point.getArgs())

                .filter(arg -> (!(arg instanceof HttpServletRequest) && !(arg instanceof HttpServletResponse)))

                .collect(Collectors.toList());

        try {

            logger.info("请求url={}, 请求参数={}", request.getRequestURI(), JSON.toJSONString(logArgs));

        } catch (Exception e) {

            logger.error("请求参数获取异常", e);

        }

        Object result = point.proceed();

        //执行时长(毫秒)

        long time = System.currentTimeMillis() - beginTime;

        try {

            logger.info("请求耗时={}ms, 返回结果={}", time, JSON.toJSONString(result));

        } catch (Exception e) {

            logger.error("返回参数获取异常", e);

        }

        return result;

    }

}


下一篇:数据库性能调优