July 10, 2010

Dumping MyBatis SQL Statements To Console using Logback

By default the root logger in LogBack is set to the debug level.

This means if you use MyBatis, MyBatis will dump statements from the java.sql.* package to the standard console (assuming your root logger is configured in a more or less standard way with a ConsoleAppender or a default configuration).

For example:

Having a root logger configured like this in logback.xml:

<root level="debug">
   <appender-ref ref="OUT" />
</root>

and associated with a console appender like the one below for example:


<appender name="OUT" class="ch.qos.logback.core.ConsoleAppender">    
    <encoder>
   <pattern>[%c] [%d{dd MMM yyyy - hh:mm:ss}] %5p - %m %n</pattern>        
    </encoder>
</appender>

You will see a dump of MyBatis debug statements for package java.sql.* as your application runs.

If you want this, that's great.

But if not, you have some options for disabling the MyBatis SQL logging dump to the console. Choose one:

  1. Set the logging level for the java.sql.* package to WARN.

    Add the following <logger> element to logback.xml
        <logger name="java.sql" level="WARN"></logger>
    
  2. Turn off the root logger.

    <root level="OFF">
       <appender-ref ref="OUT" />
    </root>
    

    If you have another logger configured to display other information, turning the root logger off will also prevent java.sql.* statements from being logged, since calling the log.debug() method passes the message to any appenders of that logger and any appenders of its parent loggers (including in this case the root logger).

  3. Set the additivity flag to false.

    <logger name="java.sql" additivity="false"/>
    

    Setting additivity="false" on any logger, ensures that logging doesn't occur on any other appenders that belong to the logger's parents (in this case the root logger). That combined with the fact that there is no appender specified for the logger named "java.sql" will essentially prevent any log.debug() statements from dumping mybatis sql results to the console.

Displaying MyBatis SQL Statements to the Console

If your root logger however is set to another level like INFO, and you actually want to display MyBatis debug info on the console, then you can just add a simple logger element to the logback.xml configuration file:

 <logger name="java.sql" level="DEBUG">
    <appender-ref ref="OUT"/> 
    <!-- see the appender named OUT defined above -->
 </logger>