Druid开启日志
最近总是会有线上机器的com.alibaba.druid.pool.DruidDataSource.CreateConnectionThread
会无故的退出,导致池中连接处小于minIdle
甚至变成0, 所以就想打印这个线程或者DruidDataSource
的日志来帮忙定位一下问题。
那么就让我们来看一下druid
的日志体系吧。
Logger name如何生效的
首先先引入Loggername
配置的是如何生效的吧。
- logger的name具有父子关系,比如
org
就是org.springframework
的父级。org
的配置也会对org.springframework
生效。 - 我们配置的logger的name是怎么来的? 不论是使用
@Slf4j
还是LoggerFactory
,我们最常见的传参就是class的name,这也就是为什么我们经常会以包名
的方式配置。
Druid的日志体系
Druid的Log实现
在com.alibaba.druid.support.logging.LogFactory
中会按照以下顺序尝试找到一个合适的实现。
tryImplementation("org.slf4j.Logger", "com.alibaba.druid.support.logging.SLF4JImpl");
tryImplementation("org.apache.log4j.Logger", "com.alibaba.druid.support.logging.Log4jImpl");
tryImplementation("org.apache.logging.log4j.Logger", "com.alibaba.druid.support.logging.Log4j2Impl");
tryImplementation("org.apache.commons.logging.LogFactory",
"com.alibaba.druid.support.logging.JakartaCommonsLoggingImpl");
tryImplementation("java.util.logging.Logger", "com.alibaba.druid.support.logging.Jdk14LoggingImpl");
而com.alibaba.druid.support.logging.SLF4JImpl
中可以看到还是使用的Slf4j的api进行获取。
public SLF4JImpl(String loggerName){
this.log = (LocationAwareLogger) LoggerFactory.getLogger(loggerName);
}
Druid的LogFilter
从配置LogFilter官网可以看到LogFilter的介绍,那么这种又是什么呢?
从名字上可以看出来,是Filter。从源码上看其中的一部分,就会明白这种是关于druid内置了一些filter的日志打印店,从而可以灵活控制打印相关的日志。
public void connection_close(FilterChain chain, ConnectionProxy connection) throws SQLException {
super.connection_close(chain, connection);
if (connectionCloseAfterLogEnable && isConnectionLogEnabled()) {
connectionLog("{conn-" + connection.getId() + "} closed");
}
}
然后结合代码就会看到这四种Logger的名称,所以在log的配置文件可以使用druid.sql
或者druid.sql.Connection
进行配置Logger的打印日志。
protected String dataSourceLoggerName = "druid.sql.DataSource";
protected String connectionLoggerName = "druid.sql.Connection";
protected String statementLoggerName = "druid.sql.Statement";
protected String resultSetLoggerName = "druid.sql.ResultSet";
那么如何打印我们想要的日志呢?
从DruidDataSource
中可以看到Log名称是以classname,所以可以使用com.alibaba.druid.pool
进行配置。