mybatis用log4j打印sql日志

时间:2021-06-23 04:38:18

一、打印sql到控制台

1、配置log4j.properties

log4j.rootLogger=DEBUG, Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender 
log4j.appender.Console.layout=org.apache.log4j.PatternLayout 
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n

log4j.logger.com.ibatis=DEBUG

log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

2、在mybatis-config.xml中添加如下语句

<settings>
        <!-- 打印查询语句 -->
        <setting name="logImpl" value="LOG4J"/>
</settings>

注意以上语句必须要放到typeAliases之前

3、如果根据如上配置还不能打印sql,且报“logImpl is unknown”,则将mybatis的jar包更换成mybatis-3.2.3.jar

4、相关jar包如下

mybatis用log4j打印sql日志

mybatis用log4j打印sql日志

二、打印sql到日志文件

1、配置log4j.properties

log4j.rootLogger=DEBUG
log4j.logger.com.ibatis=DEBUG
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

2、配置log4j.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="appender" class="org.apache.log4j.DailyRollingFileAppender">
<param name="File" value="E:/logs/log4j.log" />
<param name="Append" value="true" />
<param name="threshold" value="DEBUG" />
<param name="DatePattern" value="'.'yyyy-MM-dd'.txt'" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p [%c] - %m%n" />
</layout>
</appender>

<logger name="com.ibatis" additivity="true">
<level value="debug" />
</logger>

<logger name="java.sql.Connection" additivity="true">
<level value="debug" />
</logger>

<logger name="java.sql.Statement" additivity="true">
<level value="debug" />
</logger>

<logger name="java.sql.PreparedStatement" additivity="true">
<level value="debug" />
</logger>

<logger name="java.sql.ResultSet" additivity="true">
<level value="debug" />
</logger>


<root>
<priority value="debug" />
<appender-ref ref="appender" />
</root>
</log4j:configuration>
3、其他配置见一中的2、3、4