PROGRAMMING LANGUAGES

How to log all SQL statements executed by R2DBC

jOOQ already has a LoggingConnection (see also the manual), which acts as a JDBC proxy Connection to log all SQL statements that are executed by any JDBC client (including Hibernate, MyBatis, JdbcTemplate, native JDBC, etc.).

Starting from jOOQ 3.18.0, 3.17.7, and 3.16.13, a LoggingConnection is now also available for R2DBC clients to log all reactive queries. While some R2DBC drivers already do their own DEBUG logging, some of them don’t, so this utility will be very useful to jOOQ users or anyone else working with R2DBC.

If you don’t want to add the jOOQ dependency, you can simply use the LoggingConnection code available from github. To give you an idea of what it does:

// The jOOQ DefaultConnection just delegates all calls 
// to a delegate Connection
public class LoggingConnection extends DefaultConnection {

    // Use your own logger, alternatively
    private static final JooqLogger log = 
        JooqLogger.getLogger(LoggingConnection.class);

    public LoggingConnection(Connection delegate) {
        super(delegate);
    }

    @Override
    public Publisher<Void> close() {
        return s -> {
            if (log.isDebugEnabled())
                log.debug("Connection::close");

            getDelegate().close().subscribe(s);
        };
    }

    @Override
    public Statement createStatement(String sql) {
        if (log.isDebugEnabled())
            log.debug("Connection::createStatement", sql);

        return new LoggingStatement(getDelegate().createStatement(sql));
    }

    // [...]
}

And the same thing is done with a wrapper for Statement or Batch:

// The jOOQ DefaultStatement just delegates all calls 
// to a delegate Statement
public class LoggingStatement extends DefaultStatement {

    // Use your own logger, alternatively
    private static final JooqLogger log = 
        JooqLogger.getLogger(LoggingStatement.class);

    public LoggingStatement(Statement delegate) {
        super(delegate);
    }

    @Override
    public Statement add() {
        if (log.isDebugEnabled())
            log.debug("Statement::add");

        getDelegate().add();
        return this;
    }

    @Override
    public Publisher<? extends Result> execute() {
        return s -> {
            if (log.isDebugEnabled())
                log.debug("Statement::execute");

            getDelegate().execute().subscribe(s);
        };
    }
}

That’s it!

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button