Answers:
您需要为以下类别启用日志记录:
org.hibernate.SQL
-设置debug
为在执行所有SQL DML语句时记录它们org.hibernate.type
-设置为trace
记录所有JDBC参数因此,log4j配置如下所示:
# logs the SQL statements
log4j.logger.org.hibernate.SQL=debug
# Logs the JDBC parameters passed to a query
log4j.logger.org.hibernate.type=trace
第一个等效于hibernate.show_sql=true
legacy 属性,第二个则打印绑定参数。
另一个解决方案(基于非休眠)是使用JDBC代理驱动程序,如P6Spy。
org.hibernate.type.descriptor.sql.BasicBinder
记录器。org.hibernate.type
对我来说启用了打印过多的无用信息登录
org.hibernate.type
并org.hibernate.loader.hql
没有为我工作,以显示参数
为了方便起见,这是Logback(SLF4J)的相同配置示例
<appender name="SQLROLLINGFILE">
<File>/tmp/sql.log</File>
<rollingPolicy>
<FileNamePattern>logFile.%d{yyyy-MM-dd}.log</FileNamePattern>
</rollingPolicy>
<layout>
<Pattern>%-4date | %msg %n</Pattern>
</layout>
</appender>
<logger name="org.hibernate.SQL" additivity="false" >
<level value="DEBUG" />
<appender-ref ref="SQLROLLINGFILE" />
</logger>
<logger name="org.hibernate.type" additivity="false" >
<level value="TRACE" />
<appender-ref ref="SQLROLLINGFILE" />
</logger>
sql.log(示例)中的输出如下所示:
2013-08-30 18:01:15,083 | update stepprovider set created_at=?, lastupdated_at=?, version=?, bundlelocation=?, category_id=?, customer_id=?, description=?, icon_file_id=?, name=?, shareStatus=?, spversion=?, status=?, title=?, type=?, num_used=? where id=?
2013-08-30 18:01:15,084 | binding parameter [1] as [TIMESTAMP] - 2012-07-11 09:57:32.0
2013-08-30 18:01:15,085 | binding parameter [2] as [TIMESTAMP] - Fri Aug 30 18:01:15 CEST 2013
2013-08-30 18:01:15,086 | binding parameter [3] as [INTEGER] -
2013-08-30 18:01:15,086 | binding parameter [4] as [VARCHAR] - com.mypackage.foo
2013-08-30 18:01:15,087 | binding parameter [5] as [VARCHAR] -
2013-08-30 18:01:15,087 | binding parameter [6] as [VARCHAR] -
2013-08-30 18:01:15,087 | binding parameter [7] as [VARCHAR] - TODO
2013-08-30 18:01:15,087 | binding parameter [8] as [VARCHAR] -
2013-08-30 18:01:15,088 | binding parameter [9] as [VARCHAR] - MatchingStep@com.mypackage.foo
2013-08-30 18:01:15,088 | binding parameter [10] as [VARCHAR] - PRIVATE
2013-08-30 18:01:15,088 | binding parameter [11] as [VARCHAR] - 1.0
2013-08-30 18:01:15,088 | binding parameter [12] as [VARCHAR] - 32
2013-08-30 18:01:15,088 | binding parameter [13] as [VARCHAR] - MatchingStep
2013-08-30 18:01:15,089 | binding parameter [14] as [VARCHAR] -
2013-08-30 18:01:15,089 | binding parameter [15] as [INTEGER] - 0
2013-08-30 18:01:15,089 | binding parameter [16] as [VARCHAR] - 053c2e65-5d51-4c09-85f3-2281a1024f64
更改hibernate.cfg.xml
为:
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="use_sql_comments">true</property>
在“ log4j.properties”中包括log4j及以下条目:
log4j.logger.org.hibernate=INFO, hb
log4j.logger.org.hibernate.SQL=DEBUG
log4j.logger.org.hibernate.type=TRACE
log4j.appender.hb=org.apache.log4j.ConsoleAppender
log4j.appender.hb.layout=org.apache.log4j.PatternLayout
binding parameter [1] as [VARCHAR] - [1]
。
Log4JDBC是一个很好的解决方案,它使用参数将打印到数据库的确切 SQL 打印出来,而不是在此处不这样做的最流行的答案。一个主要的便利是您可以将SQL直接复制到数据库前端并按原样执行。
http://log4jdbc.sourceforge.net/
https://code.google.com/p/log4jdbc-remix/
后者还输出查询结果的表格表示形式。
示例输出显示了生成的带有参数的SQL以及来自查询的结果集表:
5. insert into ENQUIRY_APPLICANT_DETAILS (ID, INCLUDED_IN_QUOTE, APPLICANT_ID, TERRITORY_ID, ENQUIRY_ID, ELIGIBLE_FOR_COVER) values (7, 1, 11, 1, 2, 0)
10 Oct 2013 16:21:22 4953 [main] INFO jdbc.resultsettable - |---|--------|--------|-----------|----------|---------|-------|
10 Oct 2013 16:21:22 4953 [main] INFO jdbc.resultsettable - |ID |CREATED |DELETED |CODESET_ID |NAME |POSITION |PREFIX |
10 Oct 2013 16:21:22 4953 [main] INFO jdbc.resultsettable - |---|--------|--------|-----------|----------|---------|-------|
10 Oct 2013 16:21:22 4953 [main] INFO jdbc.resultsettable - |2 |null |null |1 |Country 2 |1 |60 |
10 Oct 2013 16:21:22 4953 [main] INFO jdbc.resultsettable - |---|--------|--------|-----------|----------|---------|-------|
最近,我现在一直在使用带有SLF4j和logback的log4jdbc-log4j2(https://code.google.com/archive/p/log4jdbc-log4j2/)。我的设置所需的Maven依赖关系如下:
<dependency>
<groupId>org.bgee.log4jdbc-log4j2</groupId>
<artifactId>log4jdbc-log4j2-jdbc4.1</artifactId>
<version>1.16</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>$logback.version}</version>
</dependency>
驱动程序和数据库Urls如下所示:
database.driver.class=net.sf.log4jdbc.sql.jdbcapi.DriverSpy
database.url=jdbc:log4jdbc:hsqldb:mem:db_name #Hsql
#database.url=jdbc:log4jdbc:mysql://localhost:3306/db_name
我的logback.xml配置文件如下所示:这将输出所有带参数的SQL语句以及所有查询的结果集表。
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<logger name="jdbc.audit" level="ERROR" />
<logger name="jdbc.connection" level="ERROR" />
<logger name="jdbc.sqltiming" level="ERROR" />
<logger name="jdbc.resultset" level="ERROR" />
<!-- UNCOMMENT THE BELOW TO HIDE THE RESULT SET TABLE OUTPUT -->
<!--<logger name="jdbc.resultsettable" level="ERROR" /> -->
<root level="debug">
<appender-ref ref="STDOUT" />
</root>
</configuration>
最后,我必须在类路径的根目录下创建一个名为log4jdbc.log4j2.properties的文件,例如在Mevn项目中的src / test / resources或src / main / resources。该文件有以下一行:
log4jdbc.spylogdelegator.name=net.sf.log4jdbc.log.slf4j.Slf4jSpyLogDelegator
以上内容取决于您的日志记录库。请参阅https://code.google.com/archive/p/log4jdbc-log4j2上的文档更多信息,
样本输出:
10:44:29.400 [main] DEBUG jdbc.sqlonly - org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:70)
5. select memberrole0_.member_id as member_i2_12_0_, memberrole0_.id as id1_12_0_, memberrole0_.id
as id1_12_1_, memberrole0_.member_id as member_i2_12_1_, memberrole0_.role_id as role_id3_12_1_,
role1_.id as id1_17_2_, role1_.name as name2_17_2_ from member_roles memberrole0_ left outer
join roles role1_ on memberrole0_.role_id=role1_.id where memberrole0_.member_id=104
10:44:29.402 [main] INFO jdbc.resultsettable -
|----------|---|---|----------|--------|---|-----|
|member_id |id |id |member_id |role_id |id |name |
|----------|---|---|----------|--------|---|-----|
|----------|---|---|----------|--------|---|-----|
您可以将类别行添加到log4j.xml:
<category name="org.hibernate.type">
<priority value="TRACE"/>
</category>
并添加休眠属性:
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="use_sql_comments">true</property>
将以下属性和值添加到log4j或logback配置中:
org.hibernate.sql=DEBUG
org.hibernate.type.descriptor.sql.BasicBinder=TRACE
org.hibernate.type.descriptor.sql.BasicBinder
类别不包括所有的参数,如枚举类型。因此,如果您想要所有东西,那么您确实需要TRACE
整个org.hibernate.type
团队。
您可以使用datasource-proxy来做到这一点,正如我在本文中所描述的。
假设您的应用程序需要一个dataSource
bean(例如通过@Resource
),这就是您可以配置的方式datasource-proxy
:
<bean id="actualDataSource" class="bitronix.tm.resource.jdbc.PoolingDataSource" init-method="init"
destroy-method="close">
<property name="className" value="bitronix.tm.resource.jdbc.lrc.LrcXADataSource"/>
<property name="uniqueName" value="actualDataSource"/>
<property name="minPoolSize" value="0"/>
<property name="maxPoolSize" value="5"/>
<property name="allowLocalTransactions" value="false" />
<property name="driverProperties">
<props>
<prop key="user">${jdbc.username}</prop>
<prop key="password">${jdbc.password}</prop>
<prop key="url">${jdbc.url}</prop>
<prop key="driverClassName">${jdbc.driverClassName}</prop>
</props>
</property>
</bean>
<bean id="proxyDataSource" class="net.ttddyy.dsproxy.support.ProxyDataSource">
<property name="dataSource" ref="testDataSource"/>
<property name="listener">
<bean class="net.ttddyy.dsproxy.listener.ChainListener">
<property name="listeners">
<list>
<bean class="net.ttddyy.dsproxy.listener.CommonsQueryLoggingListener">
<property name="logLevel" value="INFO"/>
</bean>
<bean class="net.ttddyy.dsproxy.listener.DataSourceQueryCountListener"/>
</list>
</property>
</bean>
</property>
</bean>
<alias name="proxyDataSource" alias="dataSource"/>
现在,Hibernate输出与数据源代理:
INFO [main]: n.t.d.l.CommonsQueryLoggingListener - Name:, Time:1, Num:1, Query:{[select company0_.id as id1_6_, company0_.name as name2_6_ from Company company0_][]}
INFO [main]: n.t.d.l.CommonsQueryLoggingListener - Name:, Time:0, Num:1, Query:{[insert into WarehouseProductInfo (id, quantity) values (default, ?)][19]}
INFO [main]: n.t.d.l.CommonsQueryLoggingListener - Name:, Time:0, Num:1, Query:{[insert into Product (id, code, company_id, importer_id, name, version) values (default, ?, ?, ?, ?, ?)][phoneCode,1,-5,Phone,0]}
这些datasource-proxy
查询包含参数值,您甚至可以添加自定义JDBC语句拦截器,以便可以从集成测试中捕获N + 1个查询问题。
<!-- A time/date based rolling appender -->
<appender name="FILE" class="org.apache.log4j.RollingFileAppender">
<param name="File" value="logs/system.log" />
<param name="Append" value="true" />
<param name="ImmediateFlush" value="true" />
<param name="MaxFileSize" value="200MB" />
<param name="MaxBackupIndex" value="100" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %d{Z} [%t] %-5p (%F:%L) - %m%n" />
</layout>
</appender>
<appender name="journaldev-hibernate" class="org.apache.log4j.RollingFileAppender">
<param name="File" value="logs/project.log" />
<param name="Append" value="true" />
<param name="ImmediateFlush" value="true" />
<param name="MaxFileSize" value="200MB" />
<param name="MaxBackupIndex" value="50" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %d{Z} [%t] %-5p (%F:%L) - %m%n" />
</layout>
</appender>
<logger name="com.journaldev.hibernate" additivity="false">
<level value="DEBUG" />
<appender-ref ref="journaldev-hibernate" />
</logger>
<logger name="org.hibernate" additivity="false">
<level value="INFO" />
<appender-ref ref="FILE" />
</logger>
<logger name="org.hibernate.type" additivity="false">
<level value="TRACE" />
<appender-ref ref="FILE" />
</logger>
<root>
<priority value="INFO"></priority>
<appender-ref ref="FILE" />
</root>
该解决方案是正确的,但也记录了结果对象的所有绑定。为了防止这种情况,可以创建一个单独的附加程序并启用过滤,例如:
<!-- A time/date based rolling appender -->
<appender name="FILE_HIBERNATE" class="org.jboss.logging.appender.DailyRollingFileAppender">
<errorHandler class="org.jboss.logging.util.OnlyOnceErrorHandler"/>
<param name="File" value="${jboss.server.log.dir}/hiber.log"/>
<param name="Append" value="false"/>
<param name="Threshold" value="TRACE"/>
<!-- Rollover at midnight each day -->
<param name="DatePattern" value="'.'yyyy-MM-dd"/>
<layout class="org.apache.log4j.PatternLayout">
<!-- The default pattern: Date Priority [Category] Message\n -->
<param name="ConversionPattern" value="%d %-5p [%c] %m%n"/>
</layout>
<filter class="org.apache.log4j.varia.StringMatchFilter">
<param name="StringToMatch" value="bind" />
<param name="AcceptOnMatch" value="true" />
</filter>
<filter class="org.apache.log4j.varia.StringMatchFilter">
<param name="StringToMatch" value="select" />
<param name="AcceptOnMatch" value="true" />
</filter>
<filter class="org.apache.log4j.varia.DenyAllFilter"/>
</appender>
<category name="org.hibernate.type">
<priority value="TRACE"/>
</category>
<logger name="org.hibernate.type">
<level value="TRACE"/>
<appender-ref ref="FILE_HIBERNATE"/>
</logger>
<logger name="org.hibernate.SQL">
<level value="TRACE"/>
<appender-ref ref="FILE_HIBERNATE"/>
</logger>
**If you want hibernate to print generated sql queries with real values instead of question marks.**
**add following entry in hibernate.cfg.xml/hibernate.properties:**
show_sql=true
format_sql=true
use_sql_comments=true
**And add following entry in log4j.properties :**
log4j.logger.org.hibernate=INFO, hb
log4j.logger.org.hibernate.SQL=DEBUG
log4j.logger.org.hibernate.type=TRACE
log4j.appender.hb=org.apache.log4j.ConsoleAppender
log4j.appender.hb.layout=org.apache.log4j.PatternLayout
这个问题的答案有些许差异。有时,我们仅需要sql即可在运行时进行调试。在这种情况下,有一种更简单的方法,即在编辑器上使用调试功能。
这是用于休眠3的。我不确定在其他版本上是否可以使用此功能。
mysql jdbc驱动程序已经提供了满足此要求的便捷方式,至少必须具有jar版本> = mysql-connect-jar-5.1.6.jar
步骤1:[配置jdbc.url以添加记录器和自定义记录]
jdbc.url=jdbc:mysql://host:port/your_db?logger=com.mysql.jdbc.log.Slf4JLogger&profileSQL=true&profilerEventHandler=com.xxx.CustomLoggingProfilerEventHandler
现在,它正在使用slf4j日志记录,如果您的默认日志记录是log4j,则必须添加slf4j-api,slf4j-log4j12依赖项才能使用slf4j日志记录
步骤2:[编写您的自定义日志记录]
package com.xxx;
import java.sql.SQLException;
import java.util.Properties;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.log.Log;
public class CustomLoggingProfilerEventHandler implements ProfilerEventHandler {
private Log log;
public LoggingProfilerEventHandler() {
}
public void consumeEvent(ProfilerEvent evt) {
/**
* you can only print the sql as this.log.logInfo(evt.getMessage())
* you can adjust your sql print log level with: DEBUG,INFO
* you can also handle the message to meet your requirement
*/
this.log.logInfo(evt);
}
public void destroy() {
this.log = null;
}
public void init(Connection conn, Properties props) throws SQLException {
this.log = conn.getLog();
}
}
我喜欢log4j:
log4j.logger.org.hibernate.SQL=trace
log4j.logger.org.hibernate.engine.query=trace
log4j.logger.org.hibernate.type=trace
log4j.logger.org.hibernate.jdbc=trace
log4j.logger.org.hibernate.type.descriptor.sql.BasicExtractor=error
log4j.logger.org.hibernate.type.CollectionType=error
记录的作品,但不正是你想要或者我想前一段时间,但P6SPY没有工作完美,
对我来说,它就像魅力。
提取p6spy-install.jar
文件,查找p6spy.jar
并spy.properties
添加p6spy.jar
到您的项目库依赖项
修改数据库配置文件。您需要将现有的JDBC驱动程序替换为P6Spy JDBC驱动程序–com.p6spy.engine.spy.P6SpyDriver
最初是MySQL JDBC驱动程序– com.mysql.jdbc.Driver
<session-factory>
<property name="hibernate.bytecode.use_reflection_optimizer">false</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mkyong</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
</session-factory>
将其更改为P6Spy JDBC驱动程序– com.p6spy.engine.spy.P6SpyDriver
<session-factory>
<property name="hibernate.bytecode.use_reflection_optimizer">false</property>
<property name="hibernate.connection.driver_class">com.p6spy.engine.spy.P6SpyDriver
</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mkyong</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
</session-factory>
spy.properties
real driver
用您现有的MySQL JDBC驱动程序替换
realdriver=com.mysql.jdbc.Driver
#specifies another driver to use
realdriver2=
#specifies a third driver to use
realdriver3=
更改日志文件位置更改logfile属性中的日志文件位置,所有SQL语句都将登录到该文件。
视窗
logfile = c:/spy.log
*尼克斯
logfile = /srv/log/spy.log
“spy.properties”
到项目类路径复制“spy.properties”
到项目的根文件夹,确保您的项目可以找到“ spy.properties”,否则将提示“spy.properties”
找不到文件异常。
<appender name="console" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" />
</layout>
</appender>
<logger name="org.hibernate" additivity="false">
<level value="INFO" />
<appender-ref ref="console" />
</logger>
<logger name="org.hibernate.type" additivity="false">
<level value="TRACE" />
<appender-ref ref="console" />
</logger>
使用Hibernate 4和slf4j / log4j2,我尝试在log4j2.xml配置中添加以下内容:
<Logger name="org.hibernate.type.descriptor.sql.BasicBinder" level="trace" additivity="false">
<AppenderRef ref="Console"/>
</Logger>
<Logger name="org.hibernate.type.EnumType" level="trace" additivity="false">
<AppenderRef ref="Console"/>
</Logger>
但是没有成功。
我通过该线程发现,需要配置hibernate使用的jboss-logging框架才能登录slf4j。我在应用程序的VM参数中添加了以下参数:
-Dorg.jboss.logging.provider=slf4j
它就像一个魅力。
这是对我有用的东西,在log4j.file中设置以下属性:
log4j.logger.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
休眠属性设置:
hibernate.show_sql=true
您可以记录以下内容:
net.sf.hibernate.hql.QueryTranslator
输出示例:
2013-10-31 14:56:19,029 DEBUG [net.sf.hibernate.hql.QueryTranslator] HQL: select noti.id, noti.idmicrosite, noti.fcaducidad, noti.fpublicacion, noti.tipo, noti.imagen, noti.visible, trad.titulo, trad.subtitulo, trad.laurl, trad.urlnom, trad.fuente, trad.texto from org.ibit.rol.sac.micromodel.Noticia noti join noti.traducciones trad where index(trad)='ca' and noti.visible='S' and noti.idmicrosite=985 and noti.tipo=3446
2013-10-31 14:56:19,029 DEBUG [net.sf.hibernate.hql.QueryTranslator] SQL: select noticia0_.NOT_CODI as x0_0_, noticia0_.NOT_MICCOD as x1_0_, noticia0_.NOT_CADUCA as x2_0_, noticia0_.NOT_PUBLIC as x3_0_, noticia0_.NOT_TIPO as x4_0_, noticia0_.NOT_IMAGEN as x5_0_, noticia0_.NOT_VISIB as x6_0_, traduccion1_.NID_TITULO as x7_0_, traduccion1_.NID_SUBTIT as x8_0_, traduccion1_.NID_URL as x9_0_, traduccion1_.NID_URLNOM as x10_0_, traduccion1_.NID_FUENTE as x11_0_, traduccion1_.NID_TEXTO as x12_0_ from GUS_NOTICS noticia0_ inner join GUS_NOTIDI traduccion1_ on noticia0_.NOT_CODI=traduccion1_.NID_NOTCOD where (traduccion1_.NID_CODIDI='ca' )and(noticia0_.NOT_VISIB='S' )and(noticia0_.NOT_MICCOD=985 )and(noticia0_.NOT_TIPO=3446 )
Log4Jdbc插件最适合您的需求。它显示以下内容-
1. Complete SQL query being hit to the db
2. Parameter values being passed to the query
3. Execution time taken by each query
请参考下面的链接来配置Log4Jdbc-
https://code.google.com/p/log4jdbc/
这里的所有答案都是有帮助的,但是如果您使用Spring应用程序上下文XML来设置会话工厂,则设置log4j SQL级别变量只会使您陷入困境,还必须设置hibernate.show_sql变量在应用程序上下文本身中,以使Hibernate开始实际显示值。
ApplicationContext.xml具有:
<property name="hibernateProperties">
<value>
hibernate.jdbc.batch_size=25
... <!-- Other parameter values here -->
hibernate.show_sql=true
</value>
</property>
而您的log4j文件需要
log4j.logger.org.hibernate.SQL=DEBUG
在Java中:
如果是CriteriaQuery(javax.persistence),请在TypedQuery中转换查询。
然后:
query.unwrap(org.hibernate.Query.class).getQueryString();
Hibernate在不同的行中显示查询及其参数值。
如果您在Spring Boot中使用application.properties,则可以在application.properties中使用以下突出显示的参数。
org.hibernate.SQL将显示查询
org.hibernate.type将显示所有参数值,这些参数值将与select,insert和update查询映射。logging.level.org.hibernate.type = TRACE
org.hibernate.type.EnumType将显示枚举类型参数值
例子::
2018-06-14 11:06:28,217 TRACE [main] [EnumType.java : 321] Binding [active] to parameter: [1]
sql.BasicBinder将显示整数,varchar,布尔型参数值
例子::
对我而言,最简单的解决方案是实现常规的stringReplace,以用参数值替换参数输入(为简单起见,将所有参数都视为字符串):
String debugedSql = sql;
//then, for each named parameter
debugedSql = debugedSql.replaceAll(":"+key, "'"+value.toString()+"'");
//and finnaly
println(debugedSql);
或类似的位置参数(?)。
如果要记录运行就绪的sql,请注意空值和特定值类型(如date)。