I'm building a SpringBoot application with spring-data-jpa. I know how to log all sqls from this question. How to print a query string with parameter values when using Hibernate
But what if I only want to log failed sqls?
I'm building a SpringBoot application with spring-data-jpa. I know how to log all sqls from this question. How to print a query string with parameter values when using Hibernate
But what if I only want to log failed sqls?
There are two options:
First, let's analyze the problem and split the query types into SELECT and INSERT/UPDATE queries.
A solution to your problem needs to do essentially two things: 1. It should log the queries with their parameter values. This can be done the following way:
# logs the SQL statements
log4j.logger.org.hibernate.SQL=debug
# Logs the JDBC parameters passed to a query
log4j.logger.org.hibernate.type=trace
2. The solution needs to disable the batching of queries, otherwise, you will get a bunch of SQLs but you will not know which SQL exactly is the problematic one.
hibernate.jdbc.batch_size=1
Not sure if this will be enough to entirely disable the batching, but you need to find out.
Alternatively, you can use a jdbc driver designed for DEBUG. This would be p6spy driver which has the option to flush every single SQL statement which is exactly what you want.
Here you need to set the autoflush=true
configuration parameter to ensure every single sql statement is immediately flushed to the database.
https://p6spy.readthedocs.io/en/latest/configandusage.html
This gives you multiple log entries. In my case this was not welcome.
Here is my solution for it:
@Bean
public DataSource dataSource() {
return ProxyDataSourceBuilder.create(originalDatasource())
.logQueryBySlf4j(FLF4JLogLevel.DEBUG).build();
}
public class SQLAppender extends AppenderBase
[...]
@Override
protected void append(ILoggingEvent eventObject) {
[...]
}
<appender name="mySQLAppender" class="com.my.SQLAppender" >
</appender>
<logger name="net.ttddyy.dsproxy.listener.logging.SLF4JQueryLoggingListener" level="DEBUG"\>
<appender-ref ref="mySQLAppender"/>
</logger>