aop结合slf4j实现项目中用户日志再控制台输出

​个人名片:
😊作者简介:一个为了让更多人看见许舒雅的宝贝的小白先生
🤡个人主页:🔗 许舒雅的宝贝
🐼座右铭:深夜两点半的夜灯依旧闪烁,凌晨四点的闹钟不止你一个。
🎅学习目标: 坚持前端的学习进度,做一个全栈开发工程师

目录

📍 1.自定义注解SystemLog

📍 2.定义切面类

📍 3.测试 

📍 4.对切面类进行优化


📍 1.自定义注解SystemLog

/**
 * @author 小白程序员
 * @date 2023/7/22 13:57
 */
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface SystemLog {

    String businessName();
}

 定义一个SystemLog注解,方便再使用时,直接使用注解进行实现日志输出。

📍 2.定义切面类

/**
 * @author 小白程序员
 * @date 2023/7/22 14:00
 */
@Component
@Aspect
@Slf4j
public class LogAspect {

    @Pointcut("@annotation(com.jianyin.common.annotation.SystemLog)")
    public void pt(){

    }

    @Around("pt()")
    public Object printLog(ProceedingJoinPoint joinPoint) throws Throwable{
        Object ret;
            try {
                handleBefore(joinPoint);
                ret = joinPoint.proceed();
                handleAfter(ret);
            } finally {
                log.info("=========================End========================="+System.lineSeparator());
            }
            return ret;
    }

    private void handleAfter(Object ret) {
        // 打印出参
        log.info("Response       : {}", JSON.toJSONString(ret));
    }

    private void handleBefore(ProceedingJoinPoint joinPoint) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        //获取被增强方法上的注解对象
        SystemLog systemLog = getSystemLog(joinPoint);
        log.info("=========================Start=========================");
        // 打印请求 URL
        log.info("URL            : {}",request.getRequestURL());
        // 打印描述信息
        log.info("BusinessName   : {}", systemLog.businessName());
        // 打印 Http method
        log.info("HTTP Method    : {}", request.getMethod());
        // 打印调用 controller 的全路径以及执行方法
        log.info("Class Method   : {}.{}", joinPoint.getSignature().getDeclaringTypeName(),((MethodSignature) joinPoint.getSignature()).getName());
        // 打印请求的 IP
        log.info("IP             : {}",request.getRemoteHost());
        // 打印请求入参
        log.info("Request Args   : {}", JSON.toJSONString(joinPoint.getArgs()));
    }

    private SystemLog getSystemLog(ProceedingJoinPoint joinPoint) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        return methodSignature.getMethod().getAnnotation(SystemLog.class);
    }

}

以上就完成了对aop的使用,做简单说明:

  1. 该类使用了注解@Component和@Aspect,表示它是一个组件并且是一个切面类。

  2. 使用@Pointcut注解定义了一个切点,该切点会匹配带有@SystemLog注解的方法。

  3. 使用@Around注解定义了一个环绕通知方法printLog,在目标方法执行前后进行处理。

  4. printLog方法中,首先调用handleBefore方法打印请求相关信息,然后调用目标方法并获取返回值,最后调用handleAfter方法打印返回值。

  5. handleBefore方法中通过RequestContextHolder获取当前请求的HttpServletRequest对象,并使用ServletRequestAttributes进行类型转换。

  6. 调用getSystemLog方法获取目标方法上的@SystemLog注解对象,然后使用log打印请求的URL、业务名称、HTTP方法、类方法、IP和请求参数。

  7. handleAfter方法通过JSON.toJSONString方法将返回值转换为字符串,并使用log打印返回值。

📍 3.测试 

会发现一个问题,多线程情况下,会遇到打印日志紊乱,这个不难理解,一个页面存在多个请求的时候,多个线程同时工作,然后进入了切面类,打印日志也需要时间,所以一定会出现打印紊乱的问题。如果页面发出仅有一个请求,你会发现打印不会紊乱。

📍 4.对切面类进行优化

/**
 * @author 小白程序员
 * @date 2023/7/22 14:00
 */
@Component
@Aspect
@Slf4j
public class LogAspect {

    private final Lock lock = new ReentrantLock();
    @Pointcut("@annotation(com.jianyin.common.annotation.SystemLog)")
    public void pt(){

    }

    @Around("pt()")
    public Object printLog(ProceedingJoinPoint joinPoint) throws Throwable{
        Object ret;
        synchronized (lock){
            try {
                handleBefore(joinPoint);
                ret = joinPoint.proceed();
                handleAfter(ret);
            } finally {
                log.info("=========================End========================="+System.lineSeparator());
            }
            return ret;
        }
    }

    private void handleAfter(Object ret) {
        // 打印出参
        log.info("Response       : {}", JSON.toJSONString(ret));
    }

    private void handleBefore(ProceedingJoinPoint joinPoint) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        //获取被增强方法上的注解对象
        SystemLog systemLog = getSystemLog(joinPoint);
        log.info("=========================Start=========================");
        // 打印请求 URL
        log.info("URL            : {}",request.getRequestURL());
        // 打印描述信息
        log.info("BusinessName   : {}", systemLog.businessName());
        // 打印 Http method
        log.info("HTTP Method    : {}", request.getMethod());
        // 打印调用 controller 的全路径以及执行方法
        log.info("Class Method   : {}.{}", joinPoint.getSignature().getDeclaringTypeName(),((MethodSignature) joinPoint.getSignature()).getName());
        // 打印请求的 IP
        log.info("IP             : {}",request.getRemoteHost());
        // 打印请求入参
        log.info("Request Args   : {}", JSON.toJSONString(joinPoint.getArgs()));
    }

    private SystemLog getSystemLog(ProceedingJoinPoint joinPoint) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        return methodSignature.getMethod().getAnnotation(SystemLog.class);
    }

}

加上一个锁进行限制当前进程没有执行完毕,等待当前进程执行完毕再执行下一个进程。

这篇文章就到这里了,下次见!

🥇原创不易,还希望各位大佬支持一下!

👍点赞,你的认可是我创作的动力 !

🌟收藏,你的青睐是我努力的方向!

✏️评论,你的意见是我进步的财富!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

许舒雅的宝贝

你的鼓励是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值