Logging SQL requests in java test framework with JDBC connection

 If you use JDBC connection to run SQL scripts in your java project, then logging could be quite useful to monitor what was executed after all - request body, request parameters, execution time.

To see sql execution logs, all we need to do is to implement new logger class:

@Log4j2

public class JdbcLogger implements SqlLogger {

    @Override

    public void logAfterExecution(StatementContext context) {

        log.info("Raw SQL: {}; ", context.getRawSql());

        log.info("Bindings: {};", context.getBinding());

        log.info("Elapsed (millisecond): {}", context.getElapsedTime(MILLIS));

    }

}

And add it to our jdbi connection method:

    public JdbcConnection(JdbcConfig conf) {

        Jdbi jdbi = Jdbi.create(conf.getConnectionUrl());

        jdbi.installPlugin(new SqlObjectPlugin());

        jdbi.setSqlLogger(new JdbcLogger());

        this.handle = jdbi.open();

    } 

And that's it. Profit👍

Now while running test cases in console output we could see: 

  1. SQL request body
  2. SQL request parameters
  3. Execution time
[main] INFO c.p.t.a.t.j.JdbcLoggerV3:14 - Raw SQL: USE DataBase SELECT Id FROM User WITH (nolock) ORDER BY Date DESC;
[main] INFO c.p.t.a.t.j.JdbcLoggerV3:16 - Bindings: {positional:{}, named:{}, finder:[]};
[main] INFO c.p.t.a.t.j.JdbcLoggerV3:18 - Elapsed (millisecond): 381