springAOP 从源码角度通过注解实现 日志打印

1.指定切面类:一般通过注解进行
2.指定切点:
3.监听

创造切点

@Retention(RetentionPolicy.RUNTIME) // 指定运行时
@Target({ElementType.METHOD})    // 可以加在方法上
public @interface SystemLog {
    // 可以向注解里面传递参数 例如 :businessName = “更新用户信息”
    String businessName() ;
}

RetentionPolicy:源码
在这里插入图片描述

指定切面类

HttpServletRequest的使用方法

@Component
@Aspect // 标记是切面类
@Slf4j
public class LogAspect {

    // 确定切点 , 加上 @SystemLog注解的全部是切点
    @Pointcut("@annotation(com.sangeng.annotation.SystemLog)")
    public void pt(){

    }

    //环绕通知 ,在之前之后 都会打印
   // ProceedingJoinPoint :获取目标 **方法** 的信息
    @Around("pt()")
  public void printLog(ProceedingJoinPoint joinPoint) throws Throwable {
      Object ret;

      try {
          // 运行之前打印信息
        handleBefore(joinPoint) ;
        // joinPoint.proceed(): 获取对应方法的返回结果
        Object proceed = joinPoint.proceed();
          // 运行之后打印信息
        handleAfter(proceed) ;

      }finally {
        log.info("--------END---------"+System.lineSeparator());
      }


    }

  private void handleAfter(Object ret) {
    log.info("Response       : {}",  JSON.toJSONString(ret));
  }
// ProceedingJoinPoint 是一个接口 !!
  private void handleBefore(ProceedingJoinPoint joinPoint) {

        // 获取requet  从request中获取 request.getRequestURL() ,RequestContextHolder是保存在本地线程之中的 threadlocal
    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());

    // joinPoint 打印调用 controller 的全路径以及执行方法
    log.info("Class Method   : {}.{}", joinPoint.getSignature().getDeclaringTypeName(),
            ((MethodSignature) joinPoint.getSignature()).getName());
    // 打印请求的 IP
    log.info("IP             : {}",request.getRemoteHost());

    // joinPoint 打印请求入参
    log.info("Request Args   : {}", JSON.toJSONString(joinPoint.getArgs()));
    // 打印出参
    // 结束后换行 System.lineSeparator():系统的换行符  linux 和windows的不一样
    log.info("=======End=======" + System.lineSeparator());
  }


  //获取注解信息
  private SystemLog getSystemLog(ProceedingJoinPoint joinPoint) {
    MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    return signature.getMethod().getAnnotation(SystemLog.class);
  }
}

ProceedingJoinPoint 实现类的 源码
在这里插入图片描述

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值