How to configure mybatis logging in log4j?

To configure log4j to record MyBatis logs, you need to follow these steps:

  1. Add the log4j dependency to your project. You can add the following code to the pom.xml file.
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>
  1. Create a log4j.properties file. Create a file named log4j.properties in the src/main/resources directory of your project and add the following configuration:
# 设置日志输出级别
log4j.rootLogger=DEBUG, 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} %-5p %c{1}:%L - %m%n

# MyBatis日志输出
log4j.logger.org.mybatis=DEBUG, mybatis
log4j.additivity.org.mybatis=false
log4j.appender.mybatis=org.apache.log4j.DailyRollingFileAppender
log4j.appender.mybatis.File=/path/to/mybatis.log
log4j.appender.mybatis.DatePattern='.'yyyyMMdd
log4j.appender.mybatis.layout=org.apache.log4j.PatternLayout
log4j.appender.mybatis.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

Please make sure to modify the value of log4j.appender.mybatis.File property by replacing /path/to/mybatis.log with the desired path and file name where you want to store the log file.

  1. Enable logging in your MyBatis configuration file. Add the following configuration in your MyBatis configuration file (typically mybatis-config.xml):
<configuration>
    <!-- 其他配置 -->
    <settings>
        <!-- 启用日志 -->
        <setting name="logImpl" value="LOG4J"/>
    </settings>
    <!-- 其他配置 -->
</configuration>

After completing the above steps, your application will utilize log4j to record MyBatis logs. The logs will be outputted to both the console and the specified log file.

bannerAds