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

查看:395
本文介绍了Mybatis log4j如何配置log4j将sql日志打印到文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Spring 4和MyBatis 3,要配置log4j来打印sql日志,例如连接,选择,插入,更新,删除,声明,preparedStatement,resultSet到日志文件.

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.

我的log4j.properties如下:

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

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

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!

推荐答案

,您可以参考 mybatis记录

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

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日志记录 Log4j 2 Log4j JDK日志记录 选择的日志记录解决方案基于内部MyBatis日志工厂的运行时自省. MyBatis日志工厂将使用它找到的第一个日志记录实现(以上述顺序搜索实现).如果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.

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

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>

有效值为SLF4J,LOG4J,LOG4J2,JDK_LOGGING,COMMONS_LOGGING,STDOUT_LOGGING,NO_LOGGING或实现org.apache.ibatis.logging.Log并获取字符串作为构造函数参数的完整合格类名称.

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

如果选择调用这些方法之一,则应在调用任何其他MyBatis方法之前执行此操作.同样,只有在运行时类路径上可用该实现时,这些方法才会切换到所请求的日志实现.例如,如果您尝试选择Log4J日志记录而Log4J在运行时不可用,则MyBatis将忽略使用Log4J的请求,并将使用它的常规算法来发现日志记录实现.

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.

SLF4J,Apache Commons Logging,Apache Log4J和JDK Logging API的详细信息不在本文档的讨论范围之内.但是,下面的示例配置应该可以帮助您入门.如果您想进一步了解这些框架,可以从以下位置获得更多信息:

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日志记录 Apache Log4j 1.x和2.x JDK记录API 记录配置 要查看MyBatis日志记录语句,您可以启用包登录,映射器完全限定的类名,名称空间或完全限定的语句名.

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.

同样,您如何执行此操作取决于所使用的日志记录实现.我们将展示如何使用Log4J做到这一点.配置日志记录服务仅需包括一个或多个其他配置文件(例如log4j.properties),有时还包括一个新的JAR文件(例如log4j.jar).以下示例配置将使用Log4J作为提供程序来配置完整的日志记录服务.有两个步骤.

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.

第1步:添加Log4J JAR文件

Step 1: Add the Log4J JAR file

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

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.

对于Web或企业应用程序,您可以将log4j.jar添加到WEB-INF/lib目录中,或者对于独立应用程序,您只需将其添加到JVM -classpath启动参数中即可.

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.

第2步:配置Log4J

Step 2: Configure Log4J

配置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);
}

创建一个名为log4j.properties的文件,如下所示,并将其放在您的类路径中:

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

上面的文件将使log4J报告org.mybatis.example.BlogMapper的详细日志记录,并报告应用程序其余类的错误.

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.

如果您想更精细地调整日志记录,则可以打开特定语句的日志记录,而不是整个映射器文件的日志记录.以下行将仅针对selectBlog语句启用日志记录:

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

有些查询可以返回巨大的结果集.在这种情况下,您可能只想查看SQL语句,而不要查看结果.为此,SQL语句在DEBUG级别(JDK日志记录中为FINE)记录,结果在TRACE级别(JDK日志记录中为FINER)记录,因此,如果要查看该语句而不是结果,请将级别设置为DEBUG.

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

但是,如果您不使用映射器接口,而是使用像这样的映射器XML文件呢?

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>

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

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

或针对特定声明:

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

是的,正如您可能已经注意到的,为映射器接口或XML映射器文件配置日志记录没有区别.

Yes, as you may have noticed, there is no difference in configuring logging for mapper interfaces or for XML mapper files.

注意如果您使用的是SLF4J或Log4j 2,MyBatis将使用标记MYBATIS对其进行调用.

NOTE If you are using SLF4J or Log4j 2 MyBatis will call it using the marker MYBATIS.

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

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.

这篇关于Mybatis log4j如何配置log4j将sql日志打印到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆