继上篇帖子之后 , 公司又要求将Druid Monitor的监控信息保存起来 , 因为Druid的监控记录在是缓存的,重启之后无法找回,所以需要做持久化,定期把监控记录转存到日志文件中 研究了半天 , 将经验贴出来 , 希望可以帮到大家 , 少走点弯路 .

首先贴出Druid官方给出的方法   https://github.com/alibaba/druid/wiki/%E6%80%8E%E4%B9%88%E4%BF%9D%E5%AD%98Druid%E7%9A%84%E7%9B%91%E6%8E%A7%E8%AE%B0%E5%BD%95

废话不多说 , 直接进入正题 .

  1. DataSource中增加配置:

    <!-- 每隔10分钟把监控数据输出到日志中 -->
    < property name ="timeBetweenLogStatsMillis" value ="600000" />
    <!-- 自定义实现输入监控数据到日志 -->
    < property name ="statLogger" ref ="localStatLogger" />
  2. 定义bean
    < bean id ="localStatLogger" class ="com.hyde.tracker.server.druid.LocalStatLogger" ></ bean>
  3. 类LocalStatLogger,重写API中的方法实现自定义的日志存储
    package com.hyde.tracker.server.druid;
    
    import static com.alibaba.druid.util.JdbcSqlStatUtils.rtrim;
    
    import java.net.URL;
    import java.util.ArrayList;
    import java.util.LinkedHashMap;
    import java.util.Map; import org.apache.log4j.PropertyConfigurator; import com.alibaba.druid.pool.DruidDataSourceStatLogger;
    import com.alibaba.druid.pool.DruidDataSourceStatLoggerAdapter;
    import com.alibaba.druid.pool.DruidDataSourceStatValue;
    import com.alibaba.druid.stat.JdbcSqlStatValue;
    import com.alibaba.druid.support.json.JSONUtils;
    import com.alibaba.druid.support.logging.Log;
    import com.alibaba.druid.support.logging.LogFactory; /**
     * @author WangHuijie<wanghuijie@carelink.cn>
     */
    public class LocalStatLogger extends DruidDataSourceStatLoggerAdapter implements DruidDataSourceStatLogger {     private static final Log LOGGER = LogFactory.getLog(LocalStatLogger.class);     /**
         * @see com.alibaba.druid.pool.DruidDataSourceStatLoggerAdapter#log(com.alibaba.druid.pool.DruidDataSourceStatValue)
         */
        @Override
        public void log(DruidDataSourceStatValue statValue) {
            
            Map<String, Object> map = new LinkedHashMap<String, Object>();         /*map.put("url", statValue.getUrl());
            map.put("dbType", statValue.getDbType());*/
            map.put("name", statValue.getName());
            map.put("activeCount", statValue.getActiveCount());         if (statValue.getActivePeak() > 0) {
                map.put("activePeak", statValue.getActivePeak());
                map.put("activePeakTime", statValue.getActivePeakTime());
            }
            map.put("poolingCount", statValue.getPoolingCount());
            if (statValue.getPoolingPeak() > 0) {
                map.put("poolingPeak", statValue.getPoolingPeak());
                map.put("poolingPeakTime", statValue.getPoolingPeakTime());
            }
            map.put("connectCount", statValue.getConnectCount());
            map.put("closeCount", statValue.getCloseCount());         if (statValue.getWaitThreadCount() > 0) {
                map.put("waitThreadCount", statValue.getWaitThreadCount());
            }         if (statValue.getNotEmptyWaitCount() > 0) {
                map.put("notEmptyWaitCount", statValue.getNotEmptyWaitCount());
            }         if (statValue.getNotEmptyWaitMillis() > 0) {
                map.put("notEmptyWaitMillis", statValue.getNotEmptyWaitMillis());
            }         if (statValue.getLogicConnectErrorCount() > 0) {
                map.put("logicConnectErrorCount", statValue.getLogicConnectErrorCount());
            }         if (statValue.getPhysicalConnectCount() > 0) {
                map.put("physicalConnectCount", statValue.getPhysicalConnectCount());
            }         if (statValue.getPhysicalCloseCount() > 0) {
                map.put("physicalCloseCount", statValue.getPhysicalCloseCount());
            }         if (statValue.getPhysicalConnectErrorCount() > 0) {
                map.put("physicalConnectErrorCount", statValue.getPhysicalConnectErrorCount());
            }         if (statValue.getExecuteCount() > 0) {
                map.put("executeCount", statValue.getExecuteCount());
            }         if (statValue.getErrorCount() > 0) {
                map.put("errorCount", statValue.getErrorCount());
            }         if (statValue.getCommitCount() > 0) {
                map.put("commitCount", statValue.getCommitCount());
            }         if (statValue.getRollbackCount() > 0) {
                map.put("rollbackCount", statValue.getRollbackCount());
            }         if (statValue.getPstmtCacheHitCount() > 0) {
                map.put("pstmtCacheHitCount", statValue.getPstmtCacheHitCount());
            }         if (statValue.getPstmtCacheMissCount() > 0) {
                map.put("pstmtCacheMissCount", statValue.getPstmtCacheMissCount());
            }         if (statValue.getStartTransactionCount() > 0) {
                map.put("startTransactionCount", statValue.getStartTransactionCount());
                map.put("transactionHistogram", rtrim(statValue.getTransactionHistogram()));
            }         if (statValue.getConnectCount() > 0) {
                map.put("connectionHoldTimeHistogram", rtrim(statValue.getConnectionHoldTimeHistogram()));
            }         if (statValue.getClobOpenCount() > 0) {
                map.put("clobOpenCount", statValue.getClobOpenCount());
            }         if (statValue.getBlobOpenCount() > 0) {
                map.put("blobOpenCount", statValue.getBlobOpenCount());
            }         if (statValue.getSqlSkipCount() > 0) {
                map.put("sqlSkipCount", statValue.getSqlSkipCount());
            }         ArrayList<Map<String, Object>> sqlList = new ArrayList<Map<String, Object>>();
            if (statValue.getSqlList().size() > 0) {
                for (JdbcSqlStatValue sqlStat : statValue.getSqlList()) {
                    Map<String, Object> sqlStatMap = new LinkedHashMap<String, Object>();
                    sqlStatMap.put("sql", sqlStat.getSql());                 if (sqlStat.getExecuteCount() > 0) {
                        sqlStatMap.put("executeCount", sqlStat.getExecuteCount());
                        sqlStatMap.put("executeMillisMax", sqlStat.getExecuteMillisMax());
                        sqlStatMap.put("executeMillisTotal", sqlStat.getExecuteMillisTotal());                     sqlStatMap.put("executeHistogram", rtrim(sqlStat.getExecuteHistogram()));
                        sqlStatMap.put("executeAndResultHoldHistogram", rtrim(sqlStat.getExecuteAndResultHoldHistogram()));
                    }                 long executeErrorCount = sqlStat.getExecuteErrorCount();
                    if (executeErrorCount > 0) {
                        sqlStatMap.put("executeErrorCount", executeErrorCount);
                    }                 int runningCount = sqlStat.getRunningCount();
                    if (runningCount > 0) {
                        sqlStatMap.put("runningCount", runningCount);
                    }                 int concurrentMax = sqlStat.getConcurrentMax();
                    if (concurrentMax > 0) {
                        sqlStatMap.put("concurrentMax", concurrentMax);
                    }                 if (sqlStat.getFetchRowCount() > 0) {
                        sqlStatMap.put("fetchRowCount", sqlStat.getFetchRowCount());
                        sqlStatMap.put("fetchRowCount", sqlStat.getFetchRowCountMax());
                        sqlStatMap.put("fetchRowHistogram", rtrim(sqlStat.getFetchRowHistogram()));
                    }                 if (sqlStat.getUpdateCount() > 0) {
                        sqlStatMap.put("updateCount", sqlStat.getUpdateCount());
                        sqlStatMap.put("updateCountMax", sqlStat.getUpdateCountMax());
                        sqlStatMap.put("updateHistogram", rtrim(sqlStat.getUpdateHistogram()));
                    }                 if (sqlStat.getInTransactionCount() > 0) {
                        sqlStatMap.put("inTransactionCount", sqlStat.getInTransactionCount());
                    }                 if (sqlStat.getClobOpenCount() > 0) {
                        sqlStatMap.put("clobOpenCount", sqlStat.getClobOpenCount());
                    }                 if (sqlStat.getBlobOpenCount() > 0) {
                        sqlStatMap.put("blobOpenCount", sqlStat.getBlobOpenCount());
                    }                 sqlList.add(sqlStatMap);
                }             map.put("sqlList", sqlList);
            }         String text = JSONUtils.toJSONString(map);
            
            beforeLog();
            LOGGER.info(text);
            afterLog();
        }
        
        /**
         * 在记录LOG前指定.properties文件
         */
        private void beforeLog() {
            
            propertyConfigure("/druid_log4j.properties");
        }
        
        /**
         * 在记录LOG后恢复指定本来的.properties文件
         */
        private void afterLog() {
            
            propertyConfigure("/log4j.properties");
        }
        
        /**
         * 指定.properties文件
         * @param filePath
         */
        private void propertyConfigure(String filePath) {
            
            URL resource = getClass().getResource(filePath);
            PropertyConfigurator.configure(resource);
        }
    }
  4. log4j.properties,定义转存日志文件位置及名称
    log4j.rootLogger=INFO, druid, logfile
    log4j.appender.druid.Threshold=INFO
    log4j.appender.druid=org.apache.log4j.ConsoleAppender
    log4j.appender.druid.layout=org.apache.log4j.PatternLayout
    log4j.appender.druid.layout.ConversionPattern=%d %p [%c]:%L - %m%n log4j.appender.logfile.Threshold=INFO
    log4j.appender.logfile=org.apache.log4j.DailyRollingFileAppender
    log4j.appender.logfile.DatePattern='.'yyyy-MM-dd
    log4j.appender.logfile.File=../logs/druid/druid.log
    log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
    log4j.appender.logfile.layout.ConversionPattern=[%d] - %m%n

保存Druid的监控记录的更多相关文章

  1. Spring Boot开启Druid数据库监控功能

    Druid是一个关系型数据库连接池,它是阿里巴巴的一个开源项目.Druid支持所有JDBC兼容的数据库,包括Oracle.MySQL.Derby.PostgreSQL.SQL Server.H2等.D ...

  2. Druid Monitor监控Java Web和Java SE项目

    Druid Monitor 对于数据源,大家已经接触了不少了.比如c3p0.dhcp.proxool等,之后又发现使用tomcat-jdbc可以大大的提高性能.但是针对于我们的高并发的系统来说,总希望 ...

  3. 云服务器 ECS Linux 保存用户登录操作命令记录

    转载自 : https://help.aliyun.com/knowledge_detail/41210.html 云服务器 ECS Linux 如果要保存用户登录操作记录,则可以通过在 /etc/p ...

  4. python之小木马(文件上传,下载,调用命令行,按键监控记录)

    window版 服务端: 开启两个线程,一个用来接收客户端的输入,一个用来监控服务端键盘的记录 客户端: get 文件(下载)put 文件(上传) window下cmd命令执行结果会直接打印出来,ke ...

  5. (15)Spring Boot使用Druid和监控配置【从零开始学Spring Boot】

    Spring Boot 系列博客] 更多查看博客:http://412887952-qq-com.iteye.com/blog Spring Boot默认的数据源是:org.apache.tomcat ...

  6. Spring Boot使用Druid和监控配置

    Spring Boot默认的数据源是:org.apache.tomcat.jdbc.pool.DataSource 整体步骤: (1)    --   Druid简单介绍,具体看官网: (2)     ...

  7. springboot中使用druid和监控配置

    如果想要监控自己的项目的访问情况及查看配置信息,druid是一个很好的选择,可能你会问druid是什么?有什么用?优点是什么? Druid简介 Druid是阿里巴巴开源的数据库连接池,号称是Java语 ...

  8. druid之监控设置及问题小记

    druid是什么注不再赘述了.想了解直接参见 https://github.com/alibaba/druid/wiki/%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98 本文 ...

  9. 【转】spring boot使用Druid和监控配置

    版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/u012100371/article/details/76602612 Druid是Java语言中最好 ...

随机推荐

  1. MM们,你们为什么要找一个程序猿男票?

    前言 免责声明:这篇文章关于什么?六一儿童节马上就要到了,作为一个前端攻城师,自我感觉效率还可以,老早已把任务搞完,页面布局和前端编码高效按时交付,呵呵.趁有时间,写写文章娱乐一下.MM们,请不要拿起 ...

  2. c# 内存的具体表现- 通用类型系统 深拷贝 浅拷贝 函数传参

    c# 通用类型系统 及变量在 深拷贝 浅拷贝 函数传参 中的深层次的表现 在编程中遇到了一些想不到的异常,跟踪发现,自己对于c#变量在内存上的表现理解有偏差,系统的学习并通过代码实验梳理了各种情况下, ...

  3. [刷题]算法竞赛入门经典(第2版) 6-4/UVa439 6-5/UVa1600

    比较忙比较累,只贴代码了. 题目:6-4 UVa439 - Knight Moves //UVa439 - Knight Moves //Accepted 0.000s //#define _XIEN ...

  4. JWebFileTrans(JDownload): 一款可以从网络上下载文件的小程序(三),多线程断点下载

    一 前言 本篇博客是<JWebFileTrans(JDownload):一款可以从网络上下载文件的小程序>系列博客的第三篇,本篇博客的内容主要是在前两篇的基础上增加多线程的功能.简言之,本 ...

  5. TCP三次握手(建立连接)/四次挥手(关闭连接)

    TCP数据包格式 顺序号(32位):用来标识从TCP源端向TCP目的端发送的数据字节流,它表示在这个报文段中的第一个数据字节的顺序号.如果将字节流看作在两个应用程序间的单向流动,则TCP用顺序号对每个 ...

  6. 让人恼火的经历——手机H5网页被注入广告

    你的网站是否在尾部出现了让人恼火的广告? 这次我算是遇到了这些流氓的广告.那么就让我们一步步攻克这些恼火的广告吧. 问题描述 某一天下午开始,我们制作的网站就开始被各种广告注入,类似上图这种. 还有在 ...

  7. Vue中comoputed中的数据绑定

    Vue中的数据实现响应式绑定是在初始化的时候利用definePrototype的定义set和get过滤器,在进行组件模板编译时实现water的监听搜集依赖项,当数据发生变化时在set中通过调用dep. ...

  8. Ubuntu安装Cassandra

    Uninstall Cassandra $ sudo su remove cassandra $ apt-get remove cassandra cleaned the cassandra fold ...

  9. CF219C hoosing Capital for Treeland

    D. Choosing Capital for Treeland time limit per test 3 seconds memory limit per test 256 megabytes i ...

  10. STM32的RFID射频读写控制装置

    ,大二上学期做的,过了很久,先上一下图: 这并不是做个最后一版:主体是RC552+STM32+1062:蜂鸣器,继电器,LED等:反正最后的效果就是,刷一下卡,1602显示一下持卡人(需要提前注册,注 ...