MyBatis:日志


#Java Mybatis#


我们可以通过配置,让mybatis打印出执行过程中的日志。

MyBatis:对查询结果排序 中的示例 mybatis-demo-007 为例,log4j.properties 配置为:

log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

我们只需要加一行:

log4j.logger.org.mybatis.mapper=TRACE

就可以打印出 mapper 包下所有 Mapper 接口中函数的执行日志。因为log4j.rootLogger=INFO,所以只会打印出INFO级别及以上级别的日志。为了看到更多日志,可以将其改成更低级别的DEBUG。最终如下:

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

# mapper 包下的所有接口的方法都会打日志,会打印不低于 DEBUG 级别的日志
log4j.logger.org.mybatis.mapper=TRACE

执行 Main 类中的以下代码:

@Test
public void test_01() throws IOException {
    SqlSession sqlSession = getSqlSession();
    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    List<User> userList = userMapper.findByPassword("123", "id asc");
    log.info("{}", userList);
}

输出如下:

DEBUG [main] - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - Opening JDBC Connection
DEBUG [main] - Created connection 17037394.
DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@103f852]
DEBUG [main] - ==>  Preparing: select * from blog_db.user where password=? order by id asc 
DEBUG [main] - ==> Parameters: 123(String)
DEBUG [main] - <==      Total: 2
 INFO [main] - [User(id=1, name=letian, email=letian@111.com, password=123), User(id=2, name=xiaosi, email=xiaosi@111.com, password=123)]

本节示例代码在 mybatis-demo-008


( 本文完 )