Mybatis3中用log4j跟踪SQL语句

来源:互联网 发布:linux php zend 加密 编辑:程序博客网 时间:2024/05/19 01:10

在开发过程中,打印SQL语句应该是一个非常有用的功能。

下面介绍如何在Mybatis3中开启打印SQL语句的功能。

Mybatis内置的日志工厂提供日志功能,具体的日志实现有以下几种方式:

  • SLF4J
  • Apache Commons Logging
  • Log4j 2
  • Log4j
  • JDK logging
具体选择哪个日志实现由MyBatis的内置日志工厂确定。它会使用最先找到的(按上文列举的顺序查找)。 如果一个都未找到,日志功能就会被禁用

另外Mybatis官网上说Many environments ship Commons Logging as a part of the application server classpath (good examples include Tomcat and WebSphere).

但是其实tomcat的classpath下并没有commons-logging包,其实就算项目中用了到,它也可以结合log4J良好的工作。

那么,开始吧!

1、导入log4j包,这里用的是log4j-1.2.17

2、配置log4j.properties(文件放在classpath下)

下面这段配置就可以输出所有的SQL语句

log4j.rootLogger=error, Consolelog4j.logger.com.zhuchao.test.dao=debug#Consolelog4j.appender.Console=org.apache.log4j.ConsoleAppenderlog4j.appender.Console.layout=org.apache.log4j.PatternLayoutlog4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n

其中com.zhuchao.test.dao则是Mapper类所在的包名,若是想指定某个Mapper输出SQL语句

还可以实现更细粒度的配置,比如log4j.logger.com.zhuchao.test.dao.PersonMapper=debug

再细一点,还可以指定到具体的一条sql语句,比如log4j.logger.com.zhuchao.test.dao.PersonMapper.selectById=debug

若想对Mapper.xml文件进行日志记录,只需要根据namespace来就可以了。

一般项目中mapper.xml和mapper类都是一一对应的,所以两者配置都一样~

值得注意的是,debug的日志级别,只会打印SQL语句,参数,以及影响的记录条数

2014-09-14 00:49:10,078 [http-8080-3] DEBUG [com.zhuchao.test.BasecodeMapper.selectByExample] - ==>  Preparing: select * from basecode WHERE ( cls = ? ) 2014-09-14 00:49:10,078 [http-8080-3] DEBUG [com.zhuchao.test.BasecodeMapper.selectByExample] - ==> Parameters: level(String)2014-09-14 00:49:10,079 [http-8080-3] DEBUG [com.zhuchao.test.BasecodeMapper.selectByExample] - <==      Total: 2

若还想看到所有的执行结果,可以将日志级别设置为trace:

2014-09-14 00:49:10,078 [http-8080-3] DEBUG [com.zhuchao.test.BasecodeMapper.selectByExample] - ==>  Preparing: select * from basecode WHERE ( cls = ? ) 2014-09-14 00:49:10,078 [http-8080-3] DEBUG [com.zhuchao.test.BasecodeMapper.selectByExample] - ==> Parameters: level(String)2014-09-14 00:49:10,079 [http-8080-3] TRACE [com.zhuchao.test.BasecodeMapper.selectByExample] - <==    Columns: cls, id, code, name, description, seq2014-09-14 00:49:10,079 [http-8080-3] TRACE [com.zhuchao.test.BasecodeMapper.selectByExample] - <==        Row: level, 1, level2, 等级2, 等级2, 02014-09-14 00:49:10,079 [http-8080-3] TRACE [com.zhuchao.test.BasecodeMapper.selectByExample] - <==        Row: level, 2, level1, 等级1, 等级1, 02014-09-14 00:49:10,079 [http-8080-3] DEBUG [com.zhuchao.test.BasecodeMapper.selectByExample] - <==      Total: 2

34 0
原创粉丝点击