49
50

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Spring Boot で log4jdbc-log4j2 を使用してSQLを出力する

Last updated at Posted at 2014-12-14

Spring Boot で log4jdbc-log4j2 を使用してSQLを出力するための手順です。開発時に実行されているSQLを確認したい時に使えると思います。

http://code.google.com/p/log4jdbc-log4j2/ を参照しました。

pom.xml に log4jdbc-log4j2-jdbc4.1 を追加します。

pom.xml
        <dependency>
            <groupId>org.bgee.log4jdbc-log4j2</groupId>
            <artifactId>log4jdbc-log4j2-jdbc4.1</artifactId>
            <version>1.16</version>
        </dependency>

application.properties の設定を変更します。urlのjdbcの後に :log4jdbc を追加し、driverClassName を net.sf.log4jdbc.sql.jdbcapi.DriverSpy に変更します。

(変更前)application.properties
spring.datasource.url             = jdbc:mysql://localhost/world
spring.datasource.driverClassName = com.mysql.jdbc.Driver
(変更後)application.properties
spring.datasource.url             = jdbc:log4jdbc:mysql://localhost/world
spring.datasource.driverClassName = net.sf.log4jdbc.sql.jdbcapi.DriverSpy

/resources の下に log4jdbc.log4j2.properties を作成します。

log4jdbc.log4j2.properties
log4jdbc.spylogdelegator.name=net.sf.log4jdbc.log.slf4j.Slf4jSpyLogDelegator

/resources の下に logback.xml を作成します。

logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <include resource="org/springframework/boot/logging/logback/base.xml"/>

    <!-- log4jdbc-log4j2 -->
    <logger name="jdbc.sqlonly"        level="DEBUG"/>
    <logger name="jdbc.sqltiming"      level="INFO"/>
    <logger name="jdbc.audit"          level="INFO"/>
    <logger name="jdbc.resultset"      level="ERROR"/>
    <logger name="jdbc.resultsettable" level="ERROR"/>
    <logger name="jdbc.connection"     level="DEBUG"/>
</configuration>

以下の Java Configuration のクラスを作成します。

@Configuration
public class ApplicationConfig {

    @Bean
    @ConfigurationProperties("spring.datasource")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

}

Spring Data JPA でも MyBatis-Spring でもSQLが出力されます。

49
50
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
49
50

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?