Wednesday, May 1, 2024
HomeJavaThe best way to log all SQL statements executed by R2DBC

The best way to log all SQL statements executed by R2DBC


jOOQ already has a LoggingConnection (see additionally the handbook), which acts as a JDBC proxy Connection to log all SQL statements which are executed by any JDBC shopper (together with Hibernate, MyBatis, JdbcTemplate, native JDBC, and many others.).

Ranging from jOOQ 3.18.0, 3.17.7, and three.16.13, a LoggingConnection is now additionally obtainable for R2DBC purchasers to log all reactive queries. Whereas some R2DBC drivers already do their very own DEBUG logging, a few of them don’t, so this utility will likely be very helpful to jOOQ customers or anybody else working with R2DBC.

In the event you don’t need to add the jOOQ dependency, you possibly can merely use the LoggingConnection code obtainable from github. To provide you an concept of what it does:

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

    // Use your individual logger, alternatively
    non-public static closing JooqLogger log = 
        JooqLogger.getLogger(LoggingConnection.class);

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

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

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

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

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

    // [...]
}

And the identical factor is finished with a wrapper for Assertion or Batch:

// The jOOQ DefaultStatement simply delegates all calls 
// to a delegate Assertion
public class LoggingStatement extends DefaultStatement {

    // Use your individual logger, alternatively
    non-public static closing JooqLogger log = 
        JooqLogger.getLogger(LoggingStatement.class);

    public LoggingStatement(Assertion delegate) {
        tremendous(delegate);
    }

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

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

    @Override
    public Writer<? extends End result> execute() {
        return s -> {
            if (log.isDebugEnabled())
                log.debug("Assertion::execute");

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

That’s it!

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments