使用java进行数据库操作时最痛苦的莫过于拼接SQL语句。在实际运行时往往需要查看实际生成的SQL语句和实际传入的参数,或许还会有查看SQL执行时间等的需求。
无论原生JDBC、dbutils、mybatis还是hibernate,使用log4j等日志框架可以看到生成的SQL,但是占位符和参数总是分开打印的。实在是不太友好。显示如下的效果:
select * from t_user where age>? and (sex=? or dept_id=?)
- 1
log4jdbc能很好的解决上述问题。使用log4jdbc之后的效果如下:
select * from t_user where age>1 and (sex=0 or dept_id='007')
- 1
没有什么比官网对它的介绍更加贴切了:
log4jdbc is a Java JDBC driver that can log SQL and/or JDBC calls (and optionally SQL timing information) for other JDBC drivers using the Simple Logging Facade For Java (SLF4J) logging system.
但是,众所周知googlecode在国内的访问问题……
官网的News一栏有如下消息:2015-03-30: Due to Google Code shutting down soon, log4jdbc has moved to github at 2015-03-30: Due to Google Code shutting down soon, log4jdbc has moved to github at https://github.com/arthurblake/log4jdbc
以下多数信息来自于官网
JDK Version | jar file |
---|---|
JDK 1.4 or 1.5 | JDBC 3 version of log4jdbc |
JDK 1.6 or 1.7 | JDBC 4 version of log4jdbc |
不了解 JDBC3 JDBC4?
log4jdbc 使用Simple Logging Facade for Java (SLF4j) 作为日志系统,(SLF4J)是一个简单灵活的日志抽象层,可以方便的在以下日志系统之间切换:
- Log4j
- java.util logging in JDK 1.4
- logback
- Jakarta Commons Logging
下载 SLF4j,你将需要slf4j-api-1.5.0.jar和你实际所用的日志系统的jar包,或许还会有一个适配的中间插件jar包(取决于你使用的实际日志系统)。
log4jdbc “spy” driver 将会尝试着加载以下驱动:
Driver Class | Database Type |
---|---|
oracle.jdbc.driver.OracleDriver | Older Oracle Driver |
oracle.jdbc.OracleDriver | Newer Oracle Driver |
com.sybase.jdbc2.jdbc.SybDriver | Sybase |
net.sourceforge.jtds.jdbc.Driver | jTDS SQL Server & Sybase driver |
com.microsoft.jdbc.sqlserver.SQLServerDriver | Microsoft SQL Server 2000 driver |
com.microsoft.sqlserver.jdbc.SQLServerDriver | Microsoft SQL Server 2005 driver |
weblogic.jdbc.sqlserver.SQLServerDriver | Weblogic SQL Server driver |
com.informix.jdbc.IfxDriver | Informix |
org.apache.derby.jdbc.ClientDriver | Apache Derby client/server driver, aka the Java DB |
org.apache.derby.jdbc.EmbeddedDriver | Apache Derby embedded driver, aka the Java DB |
com.mysql.jdbc.Driver | MySQL |
org.postgresql.Driver | PostgresSQL |
org.hsqldb.jdbcDriver | HSQLDB pure Java database |
org.h2.Driver | H2 pure Java database |
注意: 如果你要使用一个不在上表中的Driver,请提供log4jdbc.drivers配置,多个之间用逗号分隔,不带空格。
例如:
你的url为: url= jdbc:mysql://localhost:3306/mvn
应该改为: url= jdbc:log4jdbc:mysql://localhost:3306/mvn
log4jdbc使用5种logger:
logger | 描述 | since |
---|---|---|
jdbc.sqlonly | 仅仅记录 SQL 语句,会将占位符替换为实际的参数 | 1.0 |
jdbc.sqltiming | 包含 SQL 语句实际的执行时间 | 1.0 |
jdbc.audit | 除了 ResultSet 之外的所有JDBC调用信息,篇幅较长 | 1.0 |
jdbc.resultset | 包含 ResultSet 的信息,输出篇幅较长 | 1.0 |
jdbc.connection | 输出了 Connection 的 open、close 等信息 | 1.2alpha1 |
此外还有个叫 log4jdbc.debug 的 logger,用于log4jdbc的内部调试,会输出 log4jdbc spy 加载驱动的时的信息,如driver found 或 not found 等信息。
可以在类路径下提供一个名为 log4jdbc.properties 的配置文件,用以修改一些默认的debug属性。
其常用属性如下(来自于 官网 文档):
property | default | description | since |
---|---|---|---|
log4jdbc.drivers | log4jdbc 加载的一个或多个驱动的全类名。如果有多个,每个之间用逗号分隔(不带空格).对应常见的 JDBC drivers 此选项不是必须的。但是如果需要多个 driver ,需要配置该选项。 | 1.0 | |
log4jdbc.auto.load.popular.drivers | true | 自动加载常用的jdbc driver,如果设置为false,则必须提供 log4jdbc.drivers 属性。 | 1.2beta2 |
log4jdbc.debug.stack.prefix | The partial (or full) package prefix for the package name of your application. The call stack will be searched down to the first occurrence of a class that has the matching prefix. If this is not set, the actual class that called into log4jdbc is used in the debug output (in many cases this will be a connection pool class.) For example, setting a system property such as this: -Dlog4jdbc.debug.stack.prefix=com.mycompany.myapp Would cause the call stack to be searched for the first call that came from code in the com.mycompany.myapp package or below, thus if all of your sql generating code was in code located in the com.mycompany.myapp package or any subpackages, this would be printed in the debug information, rather than the package name for a connection pool, object relational system, etc. | 1.0 | |
log4jdbc.sqltiming.warn.threshold | 毫秒值.执行时间超过该值的SQL语句将被记录为warn级别. | 1.1beta1 | |
log4jdbc.sqltiming.error.threshold | 毫秒值.执行时间超过该值的SQL语句将被记录为error级别. | 1.1beta1 | |
log4jdbc.dump.booleanastruefalse | false | 当该值为 false 时,boolean 值显示为 0 和 1 ,为 true 时 boolean 值显示为 true 和 false | 1.2alpha1 |
log4jdbc.dump.sql.maxlinelength | 90 | SQL 分行的最大值 | 1.2alpha1 |
log4jdbc.dump.fulldebugstacktrace | false | 设置为 true 将会输出大篇幅的 debug信息 | 1.2alpha1 |
log4jdbc.dump.sql.select | true | 是否输出 select 语句 | 1.2alpha1 |
log4jdbc.dump.sql.insert | true | 是否输出 insert 语句 | 1.2alpha1 |
log4jdbc.dump.sql.delete | true | 是否输出 delete 语句 | 1.2alpha1 |
log4jdbc.dump.sql.update | true | 是否输出 update 语句 | 1.2alpha1 |
log4jdbc.dump.sql.create | true | 是否输出 create 语句 | 1.2alpha1 |
log4jdbc.dump.sql.addsemicolon | false | 是否在 SQL 的行末添加一个分号 | 1.2alpha1 |
log4jdbc.statement.warn | false | Set this to true to display warnings (Why would you care?) in the log when Statements are used in the log. NOTE, this was always true in releases previous to 1.2alpha2. It is false by default starting with release 1.2 alpha 2. | 1.2alpha2 |
log4jdbc.trim.sql | true | Set this to false to not trim the logged SQL. (Previous versions always trimmed the SQL.) | 1.2beta2 |
log4jdbc.trim.sql.extrablanklines | true | Set this to false to not trim extra blank lines in the logged SQL (by default, when more than one blank line in a row occurs, the contiguous lines are collapsed to just one blank line.) (Previous versions didn’t trim extra blank lines at all.) | 1.2 |
log4jdbc.suppress.generated.keys.exception | false | Set to true to ignore any exception produced by the method, Statement.getGeneratedKeys() (Useful for using log4jdbc with Coldfusion.) | 1.2beta2 |
maven 依赖
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.4version>
<scope>testscope>
dependency>
<dependency>
<groupId>com.googlecode.log4jdbcgroupId>
<artifactId>log4jdbcartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.35version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.16version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-log4j12artifactId>
<version>1.6.0version>
dependency>
dependencies>
log4j.properties
log4j.logger.jdbc.sqlonly=OFF
log4j.logger.jdbc.sqltiming=INFO
log4j.logger.jdbc.audit=OFF
log4j.logger.jdbc.resultset=OFF
log4j.logger.jdbc.connection=OFF
log4j.logger.jdbc.sqlonly=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
#log4j.logger.jdbc.sqltiming=INFO,console
#log4j.logger.jdbc.connection=INFO,console
log4j.rootLogger=DEBUG, console
java
url:jdbc:log4jdbc:mysql://localhost:3306/mvn
driverClassName:net.sf.log4jdbc.DriverSpy
username:root
password:root
log4jdbc.properties
log4jdbc.debug.stack.prefix=software_test.log4jdbc
log4jdbc.drivers=com.mysql.jdbc.Driver
log4jdbc.auto.load.popular.drivers=true
log4jdbc.statement.warn=true
log4jdbc.sqltiming.warn.threshold=1000
log4jdbc.sqltiming.error.threshold=3000
log4jdbc.dump.booleanastruefalse=true
log4jdbc.dump.sql.maxlinelength=90
log4jdbc.dump.fulldebugstacktrace=false
log4jdbc.dump.sql.select=true
log4jdbc.dump.sql.insert=true
log4jdbc.dump.sql.delete=true
log4jdbc.dump.sql.update=true
log4jdbc.dump.sql.create=true
log4jdbc.dump.sql.addsemicolon=false
log4jdbc.trim.sql=true
log4jdbc.trim.sql.extrablanklines=true
log4jdbc.suppress.generated.keys.exception=false
```java
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;
import org.junit.Test;
public class SimpleTest {
@Test
public void test1() {
String sql = "select * " + "from t_user where id=?";
Connection conn = null;
PreparedStatement ps = null;
try {
conn = getConnection();
ps = conn.prepareStatement(sql);
ps.setInt(1, 2);
ps.executeQuery();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public Connection getConnection() throws IOException, SQLException,
ClassNotFoundException {
String driverClassName = null;
String jdbcUrl = null;
String user = null;
String password = null;
// 读取类路径下的配置文件
InputStream in = getClass().getClassLoader().getResourceAsStream(
"dbconfig.properties");
Properties properties = new Properties();
properties.load(in);
driverClassName = properties.getProperty("driverClassName");
jdbcUrl = properties.getProperty("url");
user = properties.getProperty("username");
password = properties.getProperty("password");
Class.forName(driverClassName);
// 连接信息
Properties info = new Properties();
info.put("user", user);
info.put("password", password);
// 获取连接
Connection connection = DriverManager.getConnection(jdbcUrl, user,
password);
return connection;
}
}
```
截至目前为止,官网 对于log4jdbc和数据源的使用还没有一个很好地例子,以下是官网的截图:
本人尝试了一下C3P0数据源,不到之处请指正。
maven 依赖
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.4version>
<scope>testscope>
dependency>
<dependency>
<groupId>com.googlecode.log4jdbcgroupId>
<artifactId>log4jdbcartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.35version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.16version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-log4j12artifactId>
<version>1.6.0version>
dependency>
<dependency>
<groupId>c3p0groupId>
<artifactId>c3p0artifactId>
<version>0.9.1.2version>
dependency>
dependencies>
此处只需要 log4j.properties 和log4jdbc.properties 两个配置文件即可,配置同4.0中的配置文件。
package software_test.log4jdbc;
import java.sql.Connection;
import java.sql.PreparedStatement;
import org.junit.Test;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class DataSourceTest {
@Test
public void testC3P0() {
try {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setUser("root");
dataSource.setPassword("1234");
dataSource.setDriverClass("net.sf.log4jdbc.DriverSpy");
dataSource.setJdbcUrl("jdbc:log4jdbc:mysql://localhost:3306/mvn");
dataSource.setMaxPoolSize(50);
Connection conn = dataSource.getConnection();
String sql = "select * " + "from t_user where id=?";
PreparedStatement ps = null;
ps = conn.prepareStatement(sql);
ps.setInt(1, 2);
ps.executeQuery();
ps.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
在此将log4jdbc的使用结合官网的帮助文档中主要的一部分罗列出来。部分不太常用或理解不到位的没有翻译,怕误人子弟,有翻译不周的地方或理解不到位的地方欢迎指正。
实战部分,以后会抽时间加入其它的使用方式。
转载请保留出处。