How can I log SQL statements in Spring Boot?
Asked Answered
E

25

532

I want to log SQL statements to a file.

I have the following properties in application.properties:

spring.datasource.url=...
spring.datasource.username=user
spring.datasource.password=1234
spring.datasource.driver-class-name=net.sourceforge.jtds.jdbc.Driver

spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

security.ignored=true
security.basic.enabled=false

logging.level.org.springframework.web=INFO
logging.level.org.hibernate=INFO
logging.file=c:/temp/my-log/app.log

When I run my application,

cmd> mvn spring-boot:run

I can see SQL statements in the console, but they don't appear in app.log. The file contains only basic logs from Spring.

What should I do to see SQL statements in the log file?

Effeminate answered 8/5, 2015 at 7:55 Comment(1)
Follow instructions on baeldung.com/sql-logging-spring-bootTova
V
662

Try using this in your properties file:

logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
Vibrator answered 6/7, 2015 at 15:39 Comment(5)
If you want to log values too: logging.level.org.hibernate.type=TRACEShake
But this logs only few bind values. How can I log values from the criteria-API? If I use Specifications, I get no output for bound parameters created with the CriteriaBuilder.Woolsack
What about people that use EclipseLink instead of Hibernate ?Sibling
@Sibling post a separate questionIntroduction
In my project using spring-boot-starter-data-jpa:3.1.4 and hibernate 6.2.9, the "logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE" did not work to show the values. I had to change it to "logging.level.org.hibernate.orm.jdbc.bind=TRACE"Trifid
L
313

This works for standard output too:

spring.jpa.properties.hibernate.show_sql=true
spring.jpa.properties.hibernate.use_sql_comments=true
spring.jpa.properties.hibernate.format_sql=true

To log values:

logging.level.org.hibernate.type=trace

Just add this to application.properties.

Lam answered 26/5, 2016 at 15:20 Comment(11)
If you want to log values too: spring.jpa.properties.hibernate.type=traceShake
This doesn't write to log file, this writes to STDOUTCopyist
I still see only ? instead of the parameters. Was that solution supposed to show them to me?Kesselring
@Kesselring Sorry I can't help you. I just added it according elysch's words.Lam
@v.ladynev: But does it shows the parameters' value to you or does it shows question marks?Kesselring
spring.jpa.properties.hibernate.type=trace doesn't affect my log file ;(Quinacrine
The "type=trace" is not a spring property, so it does not work. The solution given out below https://mcmap.net/q/73642/-how-can-i-log-sql-statements-in-spring-boot is the right one for that.Barbarize
@Barbarize Thank you very much. I have updated the answer.Lam
What about people that use EclipseLink instead of Hibernate ?Sibling
This works for me, I'm using spring boot 2.5.9Hispanic
We can even have syntax highlighting via ANSI escape codes: spring.jpa.properties.hibernate.highlight_sql=trueAlgometer
A
160

This works for me (YAML):

spring:
  jpa:
    properties:
      hibernate:
        show_sql: true
        format_sql: true
logging:
  level:
    org:
      hibernate:
        type: trace
Anarch answered 11/1, 2017 at 15:37 Comment(2)
I always thought that show_sql: true belongs to jpaRepay
You are right, it should be in jpa sectionEthelyn
R
151

Settings to avoid

You should not use this setting:

spring.jpa.show-sql=true

The problem with show-sql is that the SQL statements are printed in the console, so there is no way to filter them, as you'd normally do with a Logging framework.

Using Hibernate logging

In your log configuration file, if you add the following logger:

<logger name="org.hibernate.SQL" level="debug"/>

Then, Hibernate will print the SQL statements when the JDBC PreparedStatement is created. That's why the statement will be logged using parameter placeholders:

INSERT INTO post (title, version, id) VALUES (?, ?, ?)

If you want to log the bind parameter values, just add the following logger as well:

<logger name="org.hibernate.type.descriptor.sql.BasicBinder" level="trace"/>

Once you set the BasicBinder logger, you will see that the bind parameter values are logged as well:

DEBUG [main]: o.h.SQL - insert into post (title, version, id) values (?, ?, ?)
TRACE [main]: o.h.t.d.s.BasicBinder - binding parameter [1] as [VARCHAR] - [High-Performance Java Persistence, part 1]
TRACE [main]: o.h.t.d.s.BasicBinder - binding parameter [2] as [INTEGER] - [0]
TRACE [main]: o.h.t.d.s.BasicBinder - binding parameter [3] as [BIGINT] - [1]

Using datasource-proxy

The datasource-proxy OSS framework allows you to proxy the actual JDBC DataSource, as illustrated by the following diagram:

DataSource-Proxy

You can define the dataSource bean that will be used by Hibernate as follows:

@Bean
public DataSource dataSource(DataSource actualDataSource) {
    SLF4JQueryLoggingListener loggingListener = new SLF4JQueryLoggingListener();
    loggingListener.setQueryLogEntryCreator(new InlineQueryLogEntryCreator());
    return ProxyDataSourceBuilder
        .create(actualDataSource)
        .name(DATA_SOURCE_PROXY_NAME)
        .listener(loggingListener)
        .build();
}

Notice that the actualDataSource must be the DataSource defined by the connection pool you are using in your application.

Next, you need to set the net.ttddyy.dsproxy.listener log level to debug in your logging framework configuration file. For instance, if you're using Logback, you can add the following logger:

<logger name="net.ttddyy.dsproxy.listener" level="debug"/>

Once you enable datasource-proxy, the SQL statement are going to be logged as follows:

Name:DATA_SOURCE_PROXY, Time:6, Success:True,
Type:Prepared, Batch:True, QuerySize:1, BatchSize:3,
Query:["insert into post (title, version, id) values (?, ?, ?)"],
Params:[(Post no. 0, 0, 0), (Post no. 1, 0, 1), (Post no. 2, 0, 2)]
Rede answered 18/2, 2020 at 20:33 Comment(3)
What exactly does to enable the datasource-proxy means here? Is it another configuration? Is there something extra that needs configuration apart from creating the bean with the proper datasource? Do we also need to configure something in the log4j.properties at this point?Wrath
I updated the answer to answer your questions.Rede
It do not work,how does Hibernate know to use this bean?Bojorquez
F
29

Please use:

logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type=TRACE
spring.jpa.show-sql=true
Frowsty answered 21/12, 2017 at 8:50 Comment(0)
T
26

If you have a logback-spring.xml file or something like that, add the following code to it:

<logger name="org.hibernate.SQL" level="trace" additivity="false">
    <appender-ref ref="file" />
</logger>

That works for me.

To get bind variables as well:

<logger name="org.hibernate.type.descriptor.sql" level="trace">
    <appender-ref ref="file" />
</logger>
Trona answered 17/7, 2017 at 6:41 Comment(2)
With Spring Boot you have to use <appender-ref ref="FILE" />Pice
appender ref is the name of the appender that you have defined in the logback xml. It is only a variableWoll
P
15

For the SQL Server driver (Microsoft SQL Server JDBC Driver), try using:

logging.level.com.microsoft.sqlserver.jdbc=debug

in your application.properties file.

My personal preference is to set:

logging.level.com.microsoft.sqlserver.jdbc=info
logging.level.com.microsoft.sqlserver.jdbc.internals=debug

You can look at these links for reference:

Poet answered 21/3, 2016 at 19:29 Comment(0)
U
14

For hibernate 6: it is:

spring.jpa.properties.hibernate.show_sql=true
logging.level.org.hibernate.orm.jdbc.bind = trace
Urtication answered 11/11, 2022 at 14:5 Comment(1)
I verified this for Spring Boot 3.0.0, which uses hibernate 6.1.5. Though, for me, I used logging.level.org.hibernate.SQL=DEBUG and logging.level.org.hibernate.orm.jdbc.bind=TRACE.Gaggle
L
13

Translated accepted answer to YAML works for me

logging:
  level:
    org:
      hibernate:
        SQL:
          TRACE
        type:
          descriptor:
            sql:
              BasicBinder:
                TRACE
Lawsuit answered 12/3, 2019 at 21:39 Comment(1)
You can also use flat properties in YAML if you don't want to nest for single use props, like: logging.level.org.hibernate.SQL: TRACE logging.level.org.hibernate.type.descriptor.sql.BasicBinder: TRACETetrapterous
T
11

According to documentation it is:

spring.jpa.show-sql=true # Enable logging of SQL statements.
Townswoman answered 21/11, 2017 at 20:54 Comment(1)
I have reverse problem, setting this to false, and org.hibernate to level ERROR and its still printing drop/create/insert/selectCorelli
A
11

Log in to standard output

Add to application.properties

### To enable
spring.jpa.show-sql=true

### To make the printing SQL beautify
spring.jpa.properties.hibernate.format_sql=true

This is the simplest way to print the SQL queries, though it doesn't log the parameters of prepared statements.

And it’s not recommended since it’s not such as optimized logging framework.

Using a logging framework

Add to application.properties

### Logs the SQL queries
logging.level.org.hibernate.SQL=DEBUG
### Logs the prepared statement parameters
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE

### To make the printing SQL beautify
spring.jpa.properties.hibernate.format_sql=true

By specifying the above properties, log entries will be sent to the configured log appender, such as log-back or Log4j.

Amritsar answered 23/10, 2019 at 6:28 Comment(0)
T
9

We can log SQL statements using two approaches in Spring boot: 1: using logger 2: standard approach


For logger You should add this line to application.properties file:

logging.level.org.hibernate.SQL=DEBUG

Standard Approach You should add these lines in application.properties file:

spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
Tarpon answered 29/6, 2022 at 7:27 Comment(1)
This standard approach only works for console log.Clot
P
9

I was able to solve that problem by adding these variables lines in application.properties file:

logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.orm.jdbc.bind=TRACE
spring.jpa.properties.hibernate.format_sql=true

That made me able to see debugging SQL queries (in formatted shape) and the passed variables (parameters) values.

And my log output was like this:

17:21:45.965 [http-nio-7001-exec-5] DEBUG org.hibernate.SQL - 
    select
        a1_0.action_id,
        a1_0.action_nr,
        a1_0.app_version
    from
        action a1_0 
    where
        a1_0.guid=? limit ?
17:21:45.965 [http-nio-7001-exec-5] TRACE org.hibernate.orm.jdbc.bind - binding parameter [1] as [VARCHAR] - [60154cd5-3f51-4c45-9c65-2af724c5c693]
17:21:45.965 [http-nio-7001-exec-5] TRACE org.hibernate.orm.jdbc.bind - binding parameter [2] as [INTEGER] - [1]
Pathos answered 23/3, 2023 at 14:27 Comment(1)
I can confirm it works with SpringBoot 3!Jaquelynjaquenetta
T
8

If you want to view the actual parameters used to query you can use

logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql=TRACE

Then notice that actual parameter value is shown as binding parameter...:

    2018-08-07 14:14:36.079 DEBUG 44804 --- [           main] org.hibernate.SQL                        : select employee0_.id as id1_0_, employee0_.department as departme2_0_, employee0_.joining_date as joining_3_0_, employee0_.name as name4_0_ from employee employee0_ where employee0_.joining_date=?
     2018-08-07 14:14:36.079 TRACE 44804 --- [           main] o.h.type.descriptor.sql.BasicBinder      : binding parameter [1] as [TIMESTAMP] - [Tue Aug 07 00:00:00 SGT 2018]
Tonjatonjes answered 7/8, 2018 at 6:17 Comment(0)
K
7

We can use any one of these in the application.properties file:

spring.jpa.show-sql=true

Example:

//Hibernate: select country0_.id as id1_0_, country0_.name as name2_0_ from country country0_

or

logging.level.org.hibernate.SQL=debug

Example:

2018-11-23 12:28:02.990 DEBUG 12972 --- [nio-8086-exec-2] org.hibernate.SQL   : select country0_.id as id1_0_, country0_.name as name2_0_ from country country0_
Know answered 23/11, 2018 at 6:58 Comment(0)
S
4

Use this code in the file application.properties:

# Enable logging for configuration troubleshooting
logging.level.org.hibernate.SQL=DEBUG
logging.level.com.zaxxer.hikari.HikariConfig=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
Sword answered 3/8, 2020 at 12:57 Comment(0)
T
4

You can simply add the below lines in application.properties for stdout SQL queries:

spring.jpa.properties.hibernate.show_sql=true
Tarpon answered 9/12, 2021 at 5:29 Comment(2)
What are "stdout SQL queries"? "standard out SQL queries"? Can you elaborate? Or do you mean "standard SQL queries"?Furring
By stdout queries, I mean to say that the queries which are further generated by JPA that are going to run over our DB can be logged over console or log files.Tarpon
R
3

Putting spring.jpa.properties.hibernate.show_sql=true in application.properties didn't help always.

You can try to add properties.put("hibernate.show_sql", "true"); to the properties of the database configuration.

public class DbConfig {

    @Primary
    @Bean(name = "entityManagerFactory")
    public LocalContainerEntityManagerFactoryBean
    entityManagerFactory(
            EntityManagerFactoryBuilder builder,
            @Qualifier("dataSource") DataSource dataSource
    ) {
        Map<String, Object> properties = new HashMap();
        properties.put("hibernate.hbm2ddl.auto", "validate");
        properties.put("hibernate.show_sql", "true");

        return builder
                .dataSource(dataSource)
                .packages("com.test.dbsource.domain")
                .persistenceUnit("dbsource").properties(properties)
                .build();
    }
Retired answered 16/9, 2019 at 14:0 Comment(0)
F
3

You just need to set spring.jpa.show-sql=true in application.properties.

For example, you may refer to ConfigServerRepo/application.yaml.

Footed answered 15/6, 2020 at 12:17 Comment(0)
H
3

In my YAML file:

logging:
  level:
    org.hibernate.SQL: DEBUG
    org.hibernate.type.descriptor.sql: TRACE

Spring Boot version: 2.3.5.RELEASE

Hartung answered 31/8, 2021 at 5:40 Comment(0)
P
2

If you're having trouble with this setting and it seems to work sometimes and not other times - consider if the times where it doesn't work are during unit tests.

Many people declare custom test-time properties via the @TestPropertySources annotation declared somewhere in your test inheritance hierarchy. This will override whatever you put in your application.properties or other production properties settings so those values you're setting are effectively being ignored at test-time.

Possing answered 9/9, 2019 at 2:39 Comment(0)
A
2

The basic way is to add the following lines in your application.properties. This will enable Spring Boot to log all your SQL queries that get executed:

spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

The second line is used to beautify the SQL statements.

If you want to use loggers, you can use the following lines:

logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE

The second line is used to print all the parameters that get bound with your queries.

Adjure answered 8/10, 2021 at 7:26 Comment(0)
C
1
logging.level.org.hibernate.type.descriptor.sql.BasicBinder

has been renamed to:

logging.level.org.hibernate.orm.jdbc.bind
Cultism answered 17/1 at 17:16 Comment(0)
M
0

Add these in the properties. Quoting Hibernate Show SQL:

# Show SQL statement
logging.level.org.hibernate.SQL=debug

# Show SQL values
logging.level.org.hibernate.type.descriptor.sql=trace
Manifesto answered 18/11, 2021 at 18:13 Comment(0)
A
0

If you are using JdbcTemplate, add the below in application.properties file to log SQL and parameter values.

logging.level.org.springframework.jdbc.core.JdbcTemplate=DEBUG
logging.level.org.springframework.jdbc.core.StatementCreatorUtils=TRACE
Almita answered 28/1, 2022 at 18:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.