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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33749846/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 22:06:00  来源:igfitidea点击:

Mybatis log4j how to confiure log4j to print sql log to file

javaspringlog4jmybatis

提问by Java Basketball

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). can anyone help me? thank you very much!

它在控制台中打印 sql 日志,但不会将 sql 日志打印到日志文件(如 all.log)。谁能帮我?非常感谢!

回答by Java Basketball

you can refer to mybatis logging

可以参考mybatis logging

MyBatis provides logging information through the use of an internal log factory. The internal log factory will delegate logging information to one of the following log implementations:

MyBatis 通过使用内部日志工厂提供日志信息。内部日志工厂会将日志信息委托给以下日志实现之一:

SLF4J Apache Commons Logging Log4j 2 Log4j JDK logging The logging solution chosen is based on runtime introspection by the internal MyBatis log factory. The MyBatis log factory will use the first logging implementation it finds (implementations are searched in the above order). If MyBatis finds none of the above implementations, then logging will be disabled.

SLF4J Apache Commons Logging Log4j 2 Log4j JDK 日志 选择的日志解决方案基于内部 MyBatis 日志工厂的运行时内省。MyBatis 日志工厂将使用它找到的第一个日志实现(按上述顺序搜索实现)。如果 MyBatis 没有发现上述实现,那么日志将被禁用。

Many environments ship Commons Logging as a part of the application server classpath (good examples include Tomcat and WebSphere). It is important to know that in such environments, MyBatis will use Commons Logging as the logging implementation. 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. 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). 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.xmlfile as follows:

许多环境将 Commons Logging 作为应用程序服务器类路径的一部分(很好的例子包括 Tomcat 和 WebSphere)。需要知道的是,在这样的环境中,MyBatis 会使用 Commons Logging 作为日志实现。在像 WebSphere 这样的环境中,这意味着您的 Log4J 配置将被忽略,因为 WebSphere 提供了它自己专有的 Commons Logging 实现。这可能会很令人沮丧,因为它会显得 MyBatis 忽略了你的 Log4J 配置(实际上,MyBatis 忽略了你的 Log4J 配置,因为 MyBatis 会在这样的环境中使用 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.Logand 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. 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.

如果你选择调用这些方法之一,你应该在调用任何其他 MyBatis 方法之前这样做。此外,如果该实现在运行时类路径上可用,这些方法只会切换到请求的日志实现。例如,如果您尝试选择 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. 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 和 JDK Logging API 的细节超出了本文档的范围。但是,下面的示例配置应该可以帮助您入门。如果您想了解有关这些框架的更多信息,可以从以下位置获取更多信息:

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 o a 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. Configuring the logging services is simply a matter of including one or more extra configuration files (e.g. log4j.properties) and sometimes a new JAR file (e.g. log4j.jar). The following example configuration will configure full logging services using Log4J as a provider. There are 2 steps.

同样,您如何执行此操作取决于正在使用的日志记录实现。我们将展示如何使用 Log4J 做到这一点。配置日志服务只是包含一个或多个额外配置文件(例如 log4j.properties)和有时一个新的 JAR 文件(例如 log4j.jar)的问题。以下示例配置将使用 Log4J 作为提供程序来配置完整的日志记录服务。有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. To use Log4J, you need to add the JAR file to your application classpath. You can download Log4J from the URL above.

因为我们使用的是 Log4J,所以我们需要确保它的 JAR 文件对我们的应用程序可用。要使用 Log4J,您需要将 JAR 文件添加到您的应用程序类路径。您可以从上面的 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

第二步:配置Log4J

Configuring Log4J is simple. Suppose you want to enable the log for this mapper:

配置 Log4J 很简单。假设您要为此映射器启用日志:

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. 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 语句而不是结果。为此,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. However, you can find more information at the Log4J website (URL above). Or, you could simply experiment with it to see what effects the different configuration options have.

log4j.properties 文件中的其余配置用于配置 appender,这超出了本文档的范围。但是,您可以在 Log4J 网站(上面的 URL)上找到更多信息。或者,您可以简单地尝试一下,看看不同的配置选项有什么影响。

回答by Java Basketball

maybe you view this details: http://www.mybatis.org/mybatis-3/logging.htmlhope it works!

也许您查看此详细信息:http: //www.mybatis.org/mybatis-3/logging.html希望它有效!