1.给项目添加log4j2的jar包
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-web</artifactId>
<version>2.0.2</version>
</dependency>
2.配置mybatis_configer.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="logImpl" value="LOG4J2"/>
</settings>
</configuration>
3.配置log4j2.xml,在网上简单找到的使用
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<!-- Author: Crunchify.com -->
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} [%t] %-5p %c{1}:%L - %msg%n" />
</Console>
<!-- 注意%i和 %d{yyyyMMdd},这样子才能将文件删除-->
<RollingFile name="RollingFile" filename="/log/Convergence.log"
filepattern="/log/%d{yyyyMMdd}-Convergence-%i.log">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} [%t] %-5p %c{1}:%L - %msg%n" />
<Policies>
<SizeBasedTriggeringPolicy size="20 MB" />
</Policies>
<DefaultRolloverStrategy max="20" >
<Delete basePath="/log/" maxDepth="1">
<IfFileName glob="*-Convergence-*.log" />
<IfLastModified age="30D" />
</Delete>
</DefaultRolloverStrategy>
</RollingFile>
</Appenders>
<Loggers>
<!-- name中的值为mybatis的DAO层接口包路径 -->
<logger name="convergence.idao" level="DEBUG" additivity="false">
<appender-ref ref="Console"/>
</logger>
<Root level="DEBUG">
<AppenderRef ref="Console" />
<AppenderRef ref="RollingFile" />
</Root>
</Loggers>
</Configuration>
4.在spring_mybatis.xml中引用
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mapperLocations" value="classpath:mapper/*.xml" />
<!--注意其他配置-->
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageInterceptor">
<property name="properties">
<!--使用下面的方式配置参数,一行配置一个 -->
<value>
rowBoundsWithCount=true
PageRowBounds=true
offsetAsPageNum=true
pageSizeZero=true
reasonable=true
</value>
</property>
</bean>
</array>
</property>
<property name="configLocation" value="classpath:mybatis_configer.xml"></property><!-- 配置mybatis的日志记录 -->
</bean>
5.测试,idea使用mybatis log打印sql非常方便
如有不解,请加java爱好群大家交流:852665736;大家一起交流,一同进步
无偿免费分享源码以及技术和面试文档,更多优秀精致的源码技术栈分享请关注微信公众号:gh_817962068649