Spring-AOP-自定义日志模块


自定义日志开发

场景:如果项目中的一些修改记录比较重要,需要记录下来,可以直接自定义日志的开发。

自定义注解类

@Target(ElementType.METHOD)//作用于方法上
@Retention(RetentionPolicy.RUNTIME)//注解不仅被保存到class文件中,jvm加载class文件之后,仍然存在;
@Documented//标记注解
public @interface MyLog {
    /**
     * 用户操作哪个模块
     */
    String title() default "";


    /**
     * 记录用户操作的动作
     */
    String action() default "";
}

配置织入点(以上面自定义注解为表示)

/**
     * 配置织入点(以@MyLog注解为标志)
     * 只要出现 @MyLog注解都会进入
     */

    @Pointcut("@annotation(com.example.secondhandmall.aop.annotation.MyLog)")
    public void logPointCut(){
        log.debug("logPointCut");
    }

环绕增强

/**
     * 环绕增强
     * @param point
     * @return
     * @throws Throwable
     */

    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long beginTime = System.currentTimeMillis();
        MDC.put("TRACE_ID", UUID.randomUUID().toString());
        //执行方法
        Object result = point.proceed();

        //执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;

        //保存日志
        try {
//            TODO 暂时不写日志
            saveSysLog(point, time);
        } catch (Exception e) {
            log.error("e={}",e);
        }
//        正常请求到这里结束清除请求链路信息
        MDC.remove("TRACE_ID");
        return result;
    }

保存日志

**
     * 把日志保存
     * @Author:      liuxl
     * @UpdateUser:
     * @Version:     0.0.1
     * @param joinPoint
     * @param time
     * @return       void
     * @throws
     */

    private void saveSysLog(ProceedingJoinPoint joinPoint, long time) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        SysLog sysLog = new SysLog();
        MyLog myLog = method.getAnnotation(MyLog.class);
        if(myLog != null){
            //注解上的描述
            sysLog.setOperation(myLog.title()+"-"+myLog.action());
        }
        //请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        sysLog.setMethod(className + "." + methodName + "()");
        //打印该方法耗时时间
        log.info("请求{}.{}耗时{}毫秒",className,methodName,time);
        Object[] args = joinPoint.getArgs();
        String params=null;
        try {
            //请求的参数
            if(args.length!=0){
                params= JSON.toJSONString(args);
            }
        } catch (Exception e) {
            params = Arrays.toString(args);
        }
        sysLog.setParams(params);
        //获取request
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        //设置IP地址
        sysLog.setIp(IPUtils.getIpAddr(request));
        log.info("Ip{},接口地址{},请求方式{},入参:{}",sysLog.getIp(),request.getRequestURL(),request.getMethod(),sysLog.getParams());
        //用户名
        String token = request.getHeader(Constant.ACCESS_TOKEN);
        if(null == token && null !=request.getParameterMap() && null != request.getParameterMap().get(Constant.ACCESS_TOKEN)){
//            尝试从url取一下token
            token = request.getParameterMap().get(Constant.ACCESS_TOKEN)[0];
        }
        String userId= JwtTokenUtil.getUserId(token);
        String username= JwtTokenUtil.getUserName(token);
        sysLog.setUsername(username);
        sysLog.setUserId(userId);
        sysLog.setTime((int) time);
        sysLog.setId(UUID.randomUUID().toString());
        sysLog.setCreateTime(new Date());
        log.info(sysLog.toString());
        sysLogMapper.insertSelective(sysLog);

    }

合体

@Aspect
@Component
@Slf4j
public class SysLogAspect {
    //环绕增强
    @Autowired
    private SysLogMapper sysLogMapper;

/**
     * 配置织入点(以@MyLog注解为标志)
     * 只要出现 @MyLog注解都会进入
     */

    @Pointcut("@annotation(com.example.secondhandmall.aop.annotation.MyLog)")
    public void logPointCut(){
        log.debug("logPointCut");
    }

/**
     * 环绕增强
     * @param point
     * @return
     * @throws Throwable
     */

    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long beginTime = System.currentTimeMillis();
        MDC.put("TRACE_ID", UUID.randomUUID().toString());
        //执行方法
        Object result = point.proceed();

        //执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;

        //保存日志
        try {
//            TODO 暂时不写日志
            saveSysLog(point, time);
        } catch (Exception e) {
            log.error("e={}",e);
        }
//        正常请求到这里结束清除请求链路信息
        MDC.remove("TRACE_ID");
        return result;
    }
/**
     * 把日志保存
     * @Author:      
     * @UpdateUser:
     * @Version:     0.0.1
     * @param joinPoint
     * @param time
     * @return       void
     * @throws
     */

    private void saveSysLog(ProceedingJoinPoint joinPoint, long time) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        SysLog sysLog = new SysLog();
        MyLog myLog = method.getAnnotation(MyLog.class);
        if(myLog != null){
            //注解上的描述
            sysLog.setOperation(myLog.title()+"-"+myLog.action());
        }
        //请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        sysLog.setMethod(className + "." + methodName + "()");
        //打印该方法耗时时间
        log.info("请求{}.{}耗时{}毫秒",className,methodName,time);
        Object[] args = joinPoint.getArgs();
        String params=null;
        try {
            //请求的参数
            if(args.length!=0){
                params= JSON.toJSONString(args);
            }
        } catch (Exception e) {
            params = Arrays.toString(args);
        }
        sysLog.setParams(params);
        //获取request
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        //设置IP地址
        sysLog.setIp(IPUtils.getIpAddr(request));
        log.info("Ip{},接口地址{},请求方式{},入参:{}",sysLog.getIp(),request.getRequestURL(),request.getMethod(),sysLog.getParams());
        //用户名
        String token = request.getHeader(Constant.ACCESS_TOKEN);
        if(null == token && null !=request.getParameterMap() && null != request.getParameterMap().get(Constant.ACCESS_TOKEN)){
//            尝试从url取一下token
            token = request.getParameterMap().get(Constant.ACCESS_TOKEN)[0];
        }
        String userId= JwtTokenUtil.getUserId(token);
        String username= JwtTokenUtil.getUserName(token);
        sysLog.setUsername(username);
        sysLog.setUserId(userId);
        sysLog.setTime((int) time);
        sysLog.setId(UUID.randomUUID().toString());
        sysLog.setCreateTime(new Date());
        log.info(sysLog.toString());
        sysLogMapper.insertSelective(sysLog);

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

王惠龙

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值