3.5. 日志

Hibernate utilizes Simple Logging Facade for Java (SLF4J) in order to log various system events. SLF4J can direct your logging output to several logging frameworks (NOP, Simple, log4j version 1.2, JDK 1.4 logging, JCL or logback) depending on your chosen binding. In order to setup logging properly you will need slf4j-api.jar in your classpath together with the jar file for your preferred binding - slf4j-log4j12.jar in the case of Log4J. See the SLF4J documentation for more detail. To use Log4j you will also need to place a log4j.properties file in your classpath, an example properties file is distributed with Hibernate in the src/ directory.

我们强烈建议你熟悉一下Hibernate的日志消息. 在不失可读性的前提下, 我们做了很多工作,使Hibernate的日志可能地详细. 这是必要的查错利器. 最令人感兴趣的日志分类有如下这些:

表 3.9. Hibernate日志类别

类别 功能
org.hibernate.SQL 在所有SQL DML语句被执行时为它们记录日志
org.hibernate.type 为所有JDBC参数记录日志
org.hibernate.tool.hbm2ddl 在所有SQL DDL语句执行时为它们记录日志
org.hibernate.pretty 在session清洗(flush)时,为所有与其关联的实体(最多20个)的状态记录日志
org.hibernate.cache 为所有二级缓存的活动记录日志
org.hibernate.transaction 为事务相关的活动记录日志
org.hibernate.jdbc 为所有JDBC资源的获取记录日志
org.hibernate.hql.AST 在解析查询的时候,记录HQL和SQL的AST分析日志
org.hibernate.secure 为JAAS认证请求做日志
org.hibernate 为任何Hibernate相关信息做日志 (信息量较大, 但对查错非常有帮助)

在使用Hibernate开发应用程序时, 你应当总是为org.hibernate.SQL 开启debug级别的日志记录,或者开启hibernate.show_sql属性。