Skip to content

Logging SQL Statements

Carl Harris edited this page Apr 27, 2017 · 2 revisions

Fluent JDBC supports logging of both SQL statements and bound placeholder values. Enabling statement logging on System.out is as simple as this:

FluentJdbc jdbc = new FluentJdbc(...);
jdbc.setLogger(System.out);

If you want to log both statements and bound parameter values, specify the additional traceEnabled flag value as true:

jdbc.setLogger(System.out, true);

In addition to logging to System.out you can also configure Fluent JDBC to use any implementation of its JdbcLogger interface. This is a very simple adapter interface that can easily be implemented to work with almost any logging framework. What's more, Fluent JDBC includes support for many popular frameworks, including Slf4j, Log4j, Commons Logging, and java.util.Logging (JULI).

Especially when using a logging framework, you may wish to format SQL statements prior to logging them. Fluent JDBC includes a FormattingJdbcLogger that you can use to stack formatting on top of any JdbcLogger. Formatters implement the SQLFormatter interface. A very simple, single-line formatter that cleans up whitespace and removes SQL comments is also included (SimpleSQLFormatter).

For example, suppose we wanted to log single-line formatted SQL to a java.util.logging.Logger. The following configuration is all we need.

import java.util.logging.Logger;

import org.soulwing.jdbc.FluentJdbc;
import org.soulwing.jdbc.logger.FormattingJdbcLogger;
import org.soulwing.jdbc.logger.JuliJdbcLogger;
import org.soulwing.jdbc.source.SimpleSQLFormatter;

Logger logger = ...

FluentJdbc jdbc = new FluentJdbc(...);
jdbc.setLogger(new FormattingJdbcLogger(new JuliJbdcLogger(logger)));

See the Javadocs for complete details on logging and formatting.