• P6Spy监控你的Spring boot数据库操作


    一、简介:

    p6Spy通过劫持JDBC驱动,在调用实际`JDBC`驱动前拦截调用的目标语,达到`SQL`语句日志记录的目的。
    它包括`P6Log`和`P6Outage`两个模块。

    P6Log 用来拦截和记录任务应用程序的 JDBC 语句
    P6Outage 专门用来检测和记录超过配置条件里时间的 SQL 语句

    二、使用步骤:

    1.导入pom

    <!-- 控制台 SQL日志打印插件 -->
    <dependency>
       <groupId>p6spy</groupId>
       <artifactId>p6spy</artifactId>
       <version>3.8.1</version>
    </dependency>

    2.在 spy.properties中指定p6spy配置

    # 使用日志系统记录 sql
    appender=com.p6spy.engine.spy.appender.Slf4JLogger
    # 自定义日志打印
    logMessageFormat=cc.mrbird.febs.common.configure.P6spySqlFormatConfigure
    # 是否开启慢 SQL记录
    outagedetection=true
    # 慢 SQL记录标准 2 秒
    outagedetectioninterval=2
    # 开启过滤
    filter=true
    # 包含 QRTZ的不打印
    exclude=QRTZ,select 1

    3.实现MessageFormattingStrategy接口,编写sql输出格式化

    import cc.mrbird.febs.common.utils.DateUtil;
    import com.p6spy.engine.spy.appender.MessageFormattingStrategy;
    import org.apache.commons.lang3.StringUtils;
    import java.time.LocalDateTime;
    import java.time.format.DateTimeFormatter;
    
    /**
     * SQL格式化输出
     */
    
    public class P6spySqlFormatConfigure implements MessageFormattingStrategy {
    
        /**
         * sql格式化输出
         */
        @Override
        public String formatMessage(int connectionId, String now, long elapsed, String category, String prepared, String sql, String url) {
            return StringUtils.isNotBlank(sql) ? formatFullTime(LocalDateTime.now(), DateUtil.FULL_TIME_SPLIT_PATTERN)
                    + " | 耗时 " + elapsed + " ms | SQL 语句:" + StringUtils.LF + sql.replaceAll("[\s]+", StringUtils.SPACE) + ";" : StringUtils.EMPTY;
        }
    
        /**
         * 日期格式化
         */
        public  String formatFullTime(LocalDateTime localDateTime, String pattern) {
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
            return localDateTime.format(dateTimeFormatter);
        }
    }

    4、编写application.yml配置文件

    spring:
      datasource:
        dynamic:
          # 是否开启 SQL日志输出,生产环境建议关闭,有性能损耗
          p6spy: true
          hikari:
            connection-timeout: 30000
            max-lifetime: 1800000
            max-pool-size: 15
            min-idle: 5
            connection-test-query: select 1
            pool-name: FebsHikariCP
          # 配置默认数据源
          primary: base
          datasource:
            # 数据源-1,名称为 base
            base:
              username: root
              password: 13037489030
              driver-class-name: com.mysql.jdbc.Driver
              url: jdbc:mysql://127.0.0.1:3306/febs_base?characterEncoding=UTF-8

    三、结语:

    每次访问数据库都对打印一条sql

  • 相关阅读:
    Qt发送事件与自定义事件
    Qt文本流和数据流
    Qt文件操作
    Qt 布局管理器
    Qt 标准对话框
    Qt 对话框QDailog及其类型
    Qt 对象间的父子关系
    Qt 信号与槽
    Qt 计算器界面实现
    C++ 多态、虚函数(virtual 关键字)、静态联编、动态联编
  • 原文地址:https://www.cnblogs.com/XueTing/p/14051851.html
Copyright © 2020-2023  润新知