实践Log4jdbc-log4j2

Log4jdbc-log4j2是一个jdbc日志工具,代码托管于github

logger description
jdbc.sqlonly Logs only SQL. SQL executed within a prepared statement is automatically shown with it’s bind arguments replaced with the data bound at that position, for greatly increased readability.
jdbc.sqltiming Logs the SQL, post-execution, including timing statistics on how long the SQL took to execute.
jdbc.audit Logs ALL JDBC calls except for ResultSets. This is a very voluminous output, and is not normally needed unless tracking down a specific JDBC problem.
jdbc.resultset Even more voluminous, because all calls to ResultSet objects are logged.
jdbc.resultsettable Log the jdbc results as a table. Level debug will fill in unread values in the result set.
jdbc.connection Logs connection open and close events as well as dumping all open connection numbers. This is very useful for hunting down connection leak problems.

1、添加maven依赖

1
2
3
4
5
<dependency>
  <groupId>org.bgee.log4jdbc-log4j2</groupId>
  <artifactId>log4jdbc-log4j2-jdbcXX</artifactId>
  <version>1.16</version>
</dependency>

2、如果使用slf4j作为日志框架,则新增配置文件log4jdbc.log4j2.properties,内容如下:

1
log4jdbc.spylogdelegator.name=net.sf.log4jdbc.log.slf4j.Slf4jSpyLogDelegator

3、新增包装数据源定义,参考如下:

1
2
3
4
5
6
7
8
9
10
  <bean id="dataSourceSpied" class="...">
    <property name="driverClass" value="${datasource.driverClassName}"/>
    <property name="jdbcUrl" value="${datasource.url}"/>
    <property name="user" value="${datasource.username}"/>
    <property name="password" value="${datasource.password}"/>
  </bean>

  <bean id="dataSource" class="net.sf.log4jdbc.sql.jdbcapi.DataSourceSpy">
    <constructor-arg ref="dataSourceSpied" />
  </bean>