Mybatis log4j 如何确认log4j将sql日志打印到文件上[英] Mybatis log4j how to confiure log4j to print sql log to file

本文是小编为大家收集整理的关于Mybatis log4j 如何确认log4j将sql日志打印到文件上的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我使用Spring 4和Mybatis 3,想将Log4j混淆以打印SQL日志,例如连接,选择,插入,更新,删除,删除,语句,准备statement,Resultset,结果集与日志文件.

我的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

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

推荐答案

您可以参考 mybatis logging

Mybatis通过使用内部日志工厂提供记录信息.内部日志工厂将将记录信息委托给以下日志实现之一:

SLF4J Apache Commons记录 log4j 2 log4j JDK记录 所选的记录解决方案基于内部Mybatis日志工厂的运行时内省. Mybatis日志工厂将使用它所找到的第一个日志记录实现(以上顺序搜索实现).如果Mybatis找不到上述实现,则将禁用日志记录.

许多环境将记录作为应用程序服务器类Path的一部分(包括Tomcat和WebSphere)的一部分.重要的是要知道,在这种环境中,MyBatis将使用Commons Loggging作为日志记录实现.在像WebSphere这样的环境中,这将意味着您的Log4J配置将被忽略,因为WebSphere提供了自己的专有实施Commons Loggging.这可能会非常令人沮丧,因为Mybatis似乎忽略了您的Log4J配置(实际上,Mybatis忽略了您的Log4J配置,因为Mybatis会在此类环境中使用Commons Lognging).如果您的应用程序正在集体记录中包含在ClassPath中的环境中运行,但是您宁愿使用其他日志记录实现之一,您可以通过在mybatis-config.xml文件中添加设置来选择其他日志记录实现,如下所示:

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

有效值是slf4j,log4j,log4j2,jdk_logging,commons_logging,stdout_logging,no_logging或一个实现org.apache.ibatis.logging.Log的完整合格类名称,并将字符串作为构造函数参数.

您还可以通过调用以下方法之一来选择实现:

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();

如果您选择调用其中一种方法,则应在调用任何其他Mybatis方法之前这样做.另外,如果该实现在运行时类Pather上可用时,这些方法将仅切换到所请求的日志实现.例如,如果您尝试在运行时选择Log4J记录和Log4J,则Mybatis会忽略使用Log4J的请求,并且将使用其正常算法来发现记录实现.

>

SLF4J,Apache Commons记录,Apache Log4J和JDK记录API的细节超出了本文档的范围.但是,下面的示例配置应使您入门.如果您想了解有关这些框架的更多信息,则可以从以下位置获得更多信息:

SLF4J Apache Commons记录 apache log4j 1.x和2.x JDK记录API 记录配置 要查看Mybatis记录语句,您可以在包装上登录,映射器完全合格的类名称,名称空间o完全合格的语句名称.

再次,您如何执行此操作取决于使用的日志记录实现.我们将展示如何使用log4j进行操作.配置日志记录服务只是包括一个或多个额外的配置文件(例如log4j.properties),有时还有一个新的JAR文件(例如Log4j.jar).以下示例配置将使用log4j作为提供商配置完整的日志服务.有2个步骤.

步骤1:添加log4j jar文件

因为我们使用的是log4j,因此我们需要确保其JAR文件可用于我们的应用程序.要使用Log4J,您需要将JAR文件添加到应用程序类Path.您可以从上面的URL下载log4j.

对于Web或Enterprise应用程序,您可以将log4j.jar添加到您的Web -Inf/lib目录,或者对于独立应用程序,您只需将其添加到JVM -ClassPath启动参数中.

.

步骤2:配置log4j

配置log4j很简单.假设您想启用此映射器的日志:

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

创建一个称为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

上面的文件将导致log4j报告org.mybatis.example.blogmapper的详细日志,并且仅为您的应用程序的其余类中的错误.

如果要以更细的级别调整登录,则可以打开登录以获取特定语句而不是整个映射器文件.以下行将仅适用于SelectBlog语句的记录:

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

相反,您可能希望为一组映射器启用记录.在这种情况下,您应该将其添加为logger root软件包所在的root软件包:

log4j.logger.org.mybatis.example=TRACE

有一些查询可以返回巨大的结果集.在这种情况下,您可能需要查看SQL语句,但没有结果.为此,SQL语句已记录在调试级别(JDK记录中的罚款),并在跟踪级别(在JDK日志记录中更好)的结果,因此,如果您想查看该语句,但没有结果,请设置调试级别.

log4j.logger.org.mybatis.example=DEBUG

但是,如果您不使用映射器接口,而是这样的映射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>

在这种情况下,您可以通过添加名称空间的记录器来启用对整个XML文件的记录:

:

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

或特定语句:

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

是的,正如您可能已经注意到的那样,配置映射器接口或XML映射文件的记录没有差异.

注意,如果您使用的是SLF4J或Log4J 2 Mybatis将使用Marker Mybatis调用它.

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

其他推荐答案

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

本文地址:https://www.itbaoku.cn/post/1574913.html

问题描述

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.

My log4j.properties is as below:

### 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!

推荐答案

you can refer to 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:

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.

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.xml file as follows:

<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.

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.

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 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.

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.

Step 1: Add the Log4J JAR file

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.

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.

Step 2: Configure Log4J

Configuring Log4J is simple. 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:

# 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.

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:

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.

log4j.logger.org.mybatis.example=DEBUG

But what about if you are not using mapper interfaces but mapper XML files like this one?

<?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:

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.

NOTE If you are using SLF4J or Log4j 2 MyBatis will call it using the marker 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.

其他推荐答案

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