• 通过日志监控service执行时间


    要监控到所有的service,就需要用到spring的aop插件

    一、pom.xml引入aop插件

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-aop</artifactId>
            </dependency>

    二、新建ServiceLogAspect文件(名字随便起),用来定义监控的配置

    import org.aspectj.lang.ProceedingJoinPoint;
    import org.aspectj.lang.annotation.Around;
    import org.aspectj.lang.annotation.Aspect;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.stereotype.Component;
    
    @Aspect
    @Component
    public class ServiceLogAspect {
        public static final Logger log = LoggerFactory.getLogger(ServiceLogAspect.class);
        /**
         * AOP通知:
         * 1. 前置通知:在方法调用之前执行
         * 2. 后置通知:在方法正常调用之后执行
         * 3. 环绕通知:在方法调用之前和之后,都分别可以执行的通知
         * 4. 异常通知:如果在方法调用过程中发生异常,则通知
         * 5. 最终通知:在方法调用之后执行
         */
    
        /**
         * 切面表达式:
         * execution 代表所要执行的表达式主体
         * 第一处 * 代表方法返回类型 *代表所有类型
         * 第二处 包名代表aop监控的类所在的包
         * 第三处 .. 代表该包以及其子包下的所有类方法
         * 第四处 * 代表类名,*代表所有类
         * 第五处 *(..) *代表类中的方法名,(..)表示方法中的任何参数
         *
         * @param joinPoint
         * @return
         * @throws Throwable
         */
        @Around("execution(* com.zb.service.impl..*.*(..))")
        public Object recordTimeLog(ProceedingJoinPoint joinPoint) throws Throwable {
    
            log.info("====== 开始执行 {}.{} ======",
                           joinPoint.getTarget().getClass(), // 目标class
                           joinPoint.getSignature().getName() // 目标方法
                    );
    
            // 记录开始时间
            long begin = System.currentTimeMillis();
    
            // 执行目标 service
            Object result = joinPoint.proceed();
    
            // 记录结束时间
            long end = System.currentTimeMillis();
    
            long takeTime = end - begin;
    
            if (takeTime > 3000) {
                log.error("====== 执行结束,耗时:{} 毫秒 ======", takeTime);
            } else if (takeTime > 2000) {
                log.warn("====== 执行结束,耗时:{} 毫秒 ======", takeTime);
            } else {
                log.info("====== 执行结束,耗时:{} 毫秒 ======", takeTime);
            }
    
            return result;
        }
    }

    如果想监控具体的sql语句执行时间,就在application.yml文件配置

    mybatis:
      mapper-locations: classpath*:mappers/*.xml
    #  监控具体的sql语句执行时间
      configuration:
        log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  • 相关阅读:
    ORA-01940: cannot drop a user that is currently connected解决方法
    Git基本用法简介
    C 入门 第十节 存储区
    C 入门 第九节 结构体指针
    C 入门 第八节 指针
    C 入门 第七节 结构体
    C 入门 第六节 自定义函数
    C 入门 第五节 多维数组 字符串数组
    C 入门 第四节
    C 入门 第三节
  • 原文地址:https://www.cnblogs.com/zhaobao1830/p/13370150.html
Copyright © 2020-2023  润新知