Include the necessary dependencies in your project's build file. For Log4j 2, use the log4j-core artifact. For Log4j 1, include the older log4j library. Ensure only one version is active on the classpath to avoid conflicts.
<!-- Log4j 2 -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.12.1</version>
</dependency>
<!-- Log4j 1 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
Inside the MyBatis configuration file (mybatis.cfg.xml), explicitly declare which logging implementation to use via the logImpl setting. While MyBatis can auto-detect Log4j, explicitly defining the implementation prevents the framework from picking up another available logger. For Log4j 1, set the value to LOG4J. For Log4j 2, use LOG4J2.
Log4j 1 Setup
Place a log4j.properties file at the root of your classpath (often under src/main/resources). To suppress excessive debug noise while still viewing SQL statement output, keep the root logger at a higher level and enable lower levels for mapper namespaces. During development, directing output to the console is practical.
# Root logger set to debug; output goes to the console
log4j.rootLogger=info, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %l %F %p %m%n
# File appender for persistent logs
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=d:/msb.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %p %m%n
# Show SQL statements from mappers
log4j.logger.com.mybatis.mappers=debug
Log4j 2 Setup
Add a log4j2.xml configuration file to your resources directory. The status attribute controls internal Log4j 2 logging. Output can be configured for console and rolling file appenders.
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
</Console>
<RollingFile name="RollingFile" fileName="logs/app.log"
filePattern="logs/app-%d{MM-dd-yyyy}-%i.log.gz">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" />
<Policies>
<SizeBasedTriggeringPolicy size="10 MB" />
</Policies>
<DefaultRolloverStrategy max="20" />
</RollingFile>
</Appenders>
<Loggers>
<Root level="info">
<AppenderRef ref="Console" />
<AppenderRef ref="RollingFile" />
</Root>
<Logger name="org.mybatis.example" level="debug" additivity="false">
<AppenderRef ref="Console" />
</Logger>
</Loggers>
</Configuration>
Within the MyBatis configuration file, the settings element alows you to select the logging strategy explicitly. This guarantees that the intended infrastructure handles log output.