简体   繁体   English

Mybatis log4j如何配置log4j将sql日志打印到文件

[英]Mybatis log4j how to confiure log4j to print sql log to file

i use Spring 4 and MyBatis 3, want to confiure log4j to print sql log such as connection,select, insert, update, delete, statement, preparedStatement, resultSet to log file. 我使用Spring 4和MyBatis 3,想确认log4j打印sql日志,例如连接,选择,插入,更新,删除,声明,preparedStatement,resultSet到日志文件。

My log4j.properties is as below: 我的log4j.properties如下:

### set log levels ###
log4j.rootLogger=debug, stdout, log, index, D, I, W, E
#log4j.rootLogger = debug,error, log, index, D, I, W, E
log4j.FilePath=${catalina.home}/app_log
###  print log to console ###
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 %p [%c] - <%m>%n

###  print log to console ###
log4j.appender.error = org.apache.log4j.ConsoleAppender
log4j.appender.error.Target = System.out
log4j.appender.error.layout = org.apache.log4j.PatternLayout
log4j.appender.error.layout.ConversionPattern = %d %p [%c] - <%m>%n

### create log to file ###
log4j.appender.log = org.apache.log4j.DailyRollingFileAppender
log4j.appender.log.File = ${log4j.FilePath}/all.log
#log4j.appender.log.MaxFileSize = 1024KB
log4j.appender.log.Encoding = UTF-8
log4j.appender.log.Append = true
log4j.appender.log.layout = org.apache.log4j.PatternLayout
log4j.appender.log.layout.ConversionPattern= %d %p [%c] - <%m>%n
log4j.additivity.com.packagename = true 


###  create log on lever debug ###
log4j.appender.D = org.apache.log4j.RollingFileAppender
log4j.appender.D.File = ${log4j.FilePath}/debug.log
log4j.appender.D.MaxFileSize = 1024KB
log4j.appender.D.Encoding = UTF-8
log4j.appender.D.Threshold = DEBUG
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern= %d %p [%c] - <%m>%n
log4j.appender.D.MaxBackupIndex = 10


###  create log on lever error ###
log4j.appender.E = org.apache.log4j.RollingFileAppender
log4j.appender.E.File = ${log4j.FilePath}/error.log
log4j.appender.E.MaxFileSize = 1024KB
log4j.appender.E.Encoding = UTF-8
log4j.appender.E.Threshold = ERROR
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern= %d %p [%c] - <%m>%n
log4j.appender.E.MaxBackupIndex = 10


# If programmed properly the most messages would be at DEBUG 
# and the least at FATAL.

# Control logging for other open source packages
log4j.logger.net.sf.navigator=ERROR
log4j.logger.net.sf.acegisecurity=WARN
log4j.logger.net.sf.acegisecurity.intercept.event.LoggerListener=WARN
log4j.logger.org.apache.commons=ERROR
log4j.logger.org.apache.struts=WARN
log4j.logger.org.displaytag=ERROR
log4j.logger.org.springframework=WARN
log4j.logger.org.apache.velocity=WARN
log4j.logger.org.springframework.ws.server.MessageTracing=DEBUG


# SqlMap logging configuration...
log4j.logger.com.ibatis=debug,stdout,log
log4j.logger.com.ibatis.db=debug,stdout,log
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=debug,stdout,log
log4j.logger.com.ibatis.sqlmap.engine.cache.CacheModel=debug,stdout,log
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientImpl=debug,stdout,log
log4j.logger.com.ibatis.sqlmap.engine.builder.xml.SqlMapParser=debug,stdout,log
log4j.logger.com.ibatis.common.util.StopWatch=debug,stdout,log
log4j.logger.org.apache.ibatis=debug,stdout,log
log4j.logger.org.mybatis.spring=debug,stdout,log
log4j.logger.org.mybatis.spring.SqlSessionUtils=WARN
log4j.logger.org.springframework.jdbc.datasource.DataSourceTransactionManager=debug,stdout,log

log4j.logger.org.mybatis.example=TRACE



log4j.logger.java.sql.Connection=debug
log4j.logger.java.sql.Statement=debug
log4j.logger.java.sql.PreparedStatement=debug
log4j.logger.java.sql.ResultSet=debug

it prints sql log in the console, but doesn't print sql log to the log file(such as all.log). 它在控制台中打印sql日志,但不将sql日志打印到日志文件(例如all.log)。 can anyone help me? 谁能帮我? thank you very much! 非常感谢你!

you can refer to mybatis logging 您可以参考mybatis日志记录

MyBatis provides logging information through the use of an internal log factory. MyBatis通过使用内部日志工厂来提供日志信息。 The internal log factory will delegate logging information to one of the following log implementations: 内部日志工厂会将日志记录信息委派给以下日志实现之一:

SLF4J Apache Commons Logging Log4j 2 Log4j JDK logging The logging solution chosen is based on runtime introspection by the internal MyBatis log factory. SLF4J Apache Commons Logging Log4j 2 Log4j JDK日志记录所选的日志记录解决方案基于内部MyBatis日志工厂的运行时自省。 The MyBatis log factory will use the first logging implementation it finds (implementations are searched in the above order). MyBatis日志工厂将使用它找到的第一个日志记录实现(按上述顺序搜索实现)。 If MyBatis finds none of the above implementations, then logging will be disabled. 如果MyBatis未找到上述任何实现,则将禁用日志记录。

Many environments ship Commons Logging as a part of the application server classpath (good examples include Tomcat and WebSphere). 许多环境将Commons Logging作为应用程序服务器类路径的一部分提供(很好的例子包括Tomcat和WebSphere)。 It is important to know that in such environments, MyBatis will use Commons Logging as the logging implementation. 重要的是要知道,在这样的环境中,MyBatis将使用Commons Logging作为日志记录实现。 In an environment like WebSphere this will mean that your Log4J configuration will be ignored because WebSphere supplies its own proprietary implementation of Commons Logging. 在像WebSphere这样的环境中,这将意味着您的Log4J配置将被忽略,因为WebSphere提供了自己的Commons Logging专有实现。 This can be very frustrating because it will appear that MyBatis is ignoring your Log4J configuration (in fact, MyBatis is ignoring your Log4J configuration because MyBatis will use Commons Logging in such environments). 这可能非常令人沮丧,因为MyBatis似乎忽略了Log4J配置(实际上,MyBatis忽略了Log4J配置,因为MyBatis在此类环境中将使用Commons Logging)。 If your application is running in an environment where Commons Logging is included in the classpath but you would rather use one of the other logging implementations you can select a different logging implementation by adding a setting in mybatis-config.xml file as follows: 如果您的应用程序在类路径中包含Commons Logging的环境中运行,但是您宁愿使用其他日志记录实现中的一种,则可以通过在mybatis-config.xml文件中添加一个设置来选择其他日志记录实现,如下所示:

<configuration>
  <settings>
    ...
    <setting name="logImpl" value="LOG4J"/>
    ...
  </settings>
</configuration>

Valid values are SLF4J, LOG4J, LOG4J2, JDK_LOGGING, COMMONS_LOGGING, STDOUT_LOGGING, NO_LOGGING or a full qualified class name that implements org.apache.ibatis.logging.Log and gets an string as a constructor parameter. 有效值为SLF4J,LOG4J,LOG4J2,JDK_LOGGING,COMMONS_LOGGING,STDOUT_LOGGING,NO_LOGGING或实现org.apache.ibatis.logging.Log并获取字符串作为构造函数参数的完全合格的类名。

You can also select the implementation by calling one of the following methods: 您还可以通过调用以下方法之一来选择实现:

org.apache.ibatis.logging.LogFactory.useSlf4jLogging();
org.apache.ibatis.logging.LogFactory.useLog4JLogging();
org.apache.ibatis.logging.LogFactory.useLog4J2Logging();
org.apache.ibatis.logging.LogFactory.useJdkLogging();
org.apache.ibatis.logging.LogFactory.useCommonsLogging();
org.apache.ibatis.logging.LogFactory.useStdOutLogging();

If you choose to call one of these methods, you should do so before calling any other MyBatis method. 如果选择调用这些方法之一,则应在调用任何其他MyBatis方法之前进行调用。 Also, these methods will only switch to the requested log implementation if that implementation is available on the runtime classpath. 同样,只有在运行时类路径上可以使用所请求的日志实现时,这些方法才会切换到该请求。 For example, if you try to select Log4J logging and Log4J is not available at runtime, then MyBatis will ignore the request to use Log4J and will use it's normal algorithm for discovering logging implementations. 例如,如果您尝试选择Log4J日志记录,而Log4J在运行时不可用,则MyBatis将忽略使用Log4J的请求,并将使用它的常规算法来发现日志记录实现。

The specifics of SLF4J, Apache Commons Logging, Apache Log4J and the JDK Logging API are beyond the scope of this document. SLF4J,Apache Commons Logging,Apache Log4J和JDK Logging API的详细信息超出了本文档的范围。 However the example configuration below should get you started. 但是,下面的示例配置将帮助您入门。 If you would like to know more about these frameworks, you can get more information from the following locations: 如果您想进一步了解这些框架,可以从以下位置获得更多信息:

SLF4J Apache Commons Logging Apache Log4j 1.x and 2.x JDK Logging API Logging Configuration To see MyBatis logging statements you may enable logging on a package, a mapper fully qualified class name, a namespace oa fully qualified statement name. SLF4J Apache Commons日志记录Apache Log4j 1.x和2.x JDK日志记录API日志记录配置要查看MyBatis日志记录语句,可以启用包记录,映射器完全限定的类名,名称空间或完全限定的语句名。

Again, how you do this is dependent on the logging implementation in use. 同样,您如何执行此操作取决于所使用的日志记录实现。 We'll show how to do it with Log4J. 我们将展示如何使用Log4J做到这一点。 Configuring the logging services is simply a matter of including one or more extra configuration files (eg log4j.properties) and sometimes a new JAR file (eg log4j.jar). 配置日志记录服务仅是包括一个或多个其他配置文件(例如log4j.properties),有时还包括一个新的JAR文件(例如log4j.jar)的问题。 The following example configuration will configure full logging services using Log4J as a provider. 以下示例配置将使用Log4J作为提供程序来配置完整的日志记录服务。 There are 2 steps. 有2个步骤。

Step 1: Add the Log4J JAR file 步骤1:添加Log4J JAR文件

Because we are using Log4J, we will need to ensure its JAR file is available to our application. 因为我们正在使用Log4J,所以我们需要确保其JAR文件可用于我们的应用程序。 To use Log4J, you need to add the JAR file to your application classpath. 要使用Log4J,您需要将JAR文件添加到您的应用程序类路径中。 You can download Log4J from the URL above. 您可以从上面的URL下载Log4J。

For web or enterprise applications you can add the log4j.jar to your WEB-INF/lib directory, or for a standalone application you can simply add it to the JVM -classpath startup parameter. 对于Web或企业应用程序,您可以将log4j.jar添加到WEB-INF / lib目录中,或者对于独立应用程序,只需将其添加到JVM -classpath启动参数中即可。

Step 2: Configure Log4J 步骤2:配置Log4J

Configuring Log4J is simple. 配置Log4J很简单。 Suppose you want to enable the log for this mapper: 假设您要为此映射器启用日志:

package org.mybatis.example;
public interface BlogMapper {
  @Select("SELECT * FROM blog WHERE id = #{id}")
  Blog selectBlog(int id);
}

Create a file called log4j.properties as shown below and place it in your classpath: 创建一个名为log4j.properties的文件,如下所示,并将其放在您的类路径中:

# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.org.mybatis.example.BlogMapper=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

The above file will cause log4J to report detailed logging for org.mybatis.example.BlogMapper and just errors for the rest of the classes of your application. 上面的文件将使log4J报告org.mybatis.example.BlogMapper的详细日志记录,而对于应用程序的其余类仅报告错误。

If you want to tune the logging at a finer level you can turn logging on for specific statements instead of the whole mapper file. 如果要更精细地调整日志记录,可以为特定语句而不是整个映射器文件打开日志记录。 The following line will enable logging just for the selectBlog statement: 以下行将仅针对selectBlog语句启用日志记录:

log4j.logger.org.mybatis.example.BlogMapper.selectBlog=TRACE

By the contrary you may want want to enable logging for a group of mappers. 相反,您可能想要启用一组映射器的日志记录。 In that case you should add as a logger the root package where your mappers reside: 在这种情况下,您应该将映射器所在的根软件包添加为记录器:

log4j.logger.org.mybatis.example=TRACE

There are queries that can return huge result sets. 有些查询可以返回巨大的结果集。 In that cases you may want to see the SQL statement but not the results. 在这种情况下,您可能想查看SQL语句,而不是结果。 For that purpose SQL statements are logged at the DEBUG level (FINE in JDK logging) and results at the TRACE level (FINER in JDK logging), so in case you want to see the statement but not the result, set the level to DEBUG. 为此,SQL语句在DEBUG级别(JDK日志记录中为FINE)记录,结果在TRACE级别(JDK日志记录中为FINER)记录,因此,如果要查看该语句而不是结果,请将级别设置为DEBUG。

log4j.logger.org.mybatis.example=DEBUG

But what about if you are not using mapper interfaces but mapper XML files like this one? 但是,如果您不使用映射器接口,而是使用像这样的映射器XML文件呢?

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.mybatis.example.BlogMapper">
  <select id="selectBlog" resultType="Blog">
    select * from Blog where id = #{id}
  </select>
</mapper>

In that case you can enable logging for the whole XML file by adding a logger for the namespace as shown below: 在这种情况下,您可以通过添加名称空间的记录器来启用整个XML文件的记录,如下所示:

log4j.logger.org.mybatis.example.BlogMapper=TRACE

Or for an specific statement: 或针对特定声明:

log4j.logger.org.mybatis.example.BlogMapper.selectBlog=TRACE

Yes, as you may have noticed, there is no difference in configuring logging for mapper interfaces or for XML mapper files. 是的,您可能已经注意到,为映射器接口或XML映射器文件配置日志记录没有区别。

NOTE If you are using SLF4J or Log4j 2 MyBatis will call it using the marker MYBATIS. 注意如果使用的是SLF4J或Log4j,2 MyBatis将使用标记MYBATIS对其进行调用。

The remaining configuration in the log4j.properties file is used to configure the appenders, which is beyond the scope of this document. log4j.properties文件中的其余配置用于配置附加程序,这超出了本文档的范围。 However, you can find more information at the Log4J website (URL above). 但是,您可以在Log4J网站(上面的URL)上找到更多信息。 Or, you could simply experiment with it to see what effects the different configuration options have. 或者,您可以简单地尝试一下它,看看不同的配置选项有什么作用。

也许您可以查看以下详细信息: http : //www.mybatis.org/mybatis-3/logging.html希望它能起作用!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM