1.在maven引入:
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency> <dependency>
<groupId>com.googlecode.log4jdbc</groupId>
<artifactId>log4jdbc</artifactId>
<version>1.2</version>
</dependency> <dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.24</version>
</dependency>
2.log4j.properties配置如下:
#记录系统执行过的sql语句
log4j.logger.jdbc.sqlonly=DEBUG,console
#记录sql执行的时间,可以分析耗时的sql语句
log4j.additivity.jdbc.sqltiming=true
log4j.logger.jdbc.sqltiming=INFO,console
#记录除了ResultSet外的所有JDBC调用情况。一般不需要。
#log4j.additivity.jdbc.audidt=true
#log4j.logger.jdbc.audit=INFO,console
#记录返回结果集信息
#log4j.additivity.jdbc.resultset=true
#log4j.logger.jdbc.resultset=INFO,console
#记录数据库连接和释放信息,可记录当前的数据库连接数,便于诊断连接是否释放
#log4j.additivity.jdbc.connection=true
#log4j.logger.jdbc.connection=INFO,console
#控制台输出
log4j.appender.console=org.apache.log4j.ConsoleAppender
#控制台输出格式定义
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSS} %m%n%n
3.修改数据库连接配置如下:
#数据库驱动
mysql.driver=net.sf.log4jdbc.DriverSpy
#数据库连接URL
mysql.url=jdbc:log4jdbc:mysql://localhost/test
结果如下:
[QC] INFO [http-apr-8070-exec-7] net.sf.log4jdbc.Slf4jSpyLogDelegator.sqlTimingOccured(370) | select bookent0_.n_id as n_id1_0_, bookent0_.d_create_time as d_create2_0_, bookent0_.s_created_by
as s_create3_0_, bookent0_.d_update_time as d_update4_0_, bookent0_.s_updated_by as s_update5_0_,
bookent0_.n_chapternum as n_chapte6_0_, bookent0_.s_name as s_name7_0_, bookent0_.s_profile
as s_profil8_0_, bookent0_.s_remark as s_remark9_0_, bookent0_.n_size as n_size10_0_, bookent0_.n_sort
as n_sort11_0_, bookent0_.n_type as n_type12_0_, bookent0_.s_url as s_url13_0_ from jy_book
bookent0_ where 1=1 and bookent0_.n_type=1 order by bookent0_.n_sort desc
{executed in 9 msec}