Log4j Configuration in XML

一 、Basic Knoledge
 1.Common conception
Apache log4j is a Java-based logging utility. It was originally written by Ceki Gülcü and is now a project of the Apache Software Foundation. log4j is one of several Java logging frameworks.
Gülcü has since started the SLF4J and Logback[1] projects, with the intention of offering a successor to log4j.
The log4j team has created a successor to log4j with version number 2.0, which is currently in beta release. log4j 2.0 was developed with a focus on the problems of log4j 1.2, 1.3, java.util.logging and logback, and addresses issues which appeared in those frameworks. In addition, log4j 2.0 offers a plugin architecture which makes it more extensible than its predecessor. log4j 2.0 is not backwards compatible with 1.x versions,[2] although an "adapter" is available.
There are three ways to configure log4j: with a properties file, with an XML file and through Java code. Within either you can define three main components: Loggers, Appenders and Layouts. Configuring logging via a file has the advantage of turning logging on or off without modifying the application that uses log4j. The application can be allowed to run with logging off until there's a problem, for example, and then logging can be turned back on simply by modifying the configuration file.
Loggers are logical log file names. They are the names that are known to the Java application. Each logger is independently configurable as to what level of logging (FATAL, ERROR, etc.) it currently logs. In early versions of log4j, these were called category and priority, but now they're called logger and level, respectively.
The actual outputs are done by Appenders. There are numerous Appenders available, with descriptive names, such as FileAppender, ConsoleAppender, SocketAppender, SyslogAppender, NTEventLogAppender and even SMTPAppender. Multiple Appenders can be attached to any Logger, so it's possible to log the same information to multiple outputs; for example to a file locally and to a socket listener on another computer.
Appenders use Layouts to format log entries. A popular way to format one-line-at-a-time log files is PatternLayout, which uses a pattern string, much like the C / C++ function printf. There are also HTMLLayout and XMLLayout formatters for use when HTML or XML formats are more convenient, respectively.
To debug a misbehaving configuration use the Java VM property -Dlog4j.debug which will output to standard out. To find out where a log4j.properties was loaded from inspect getClass().getResource("/log4j.properties") or getClass().getResource("/log4j.xml").
There is also an implicit "unconfigured" configuration of log4j, that of a log4j-instrumented Java application which lacks any log4j configuration. This prints to stdout a warning that the program is unconfigured, and the URL to the log4j web site where details on the warning and configuration may be found. As well as printing this warning, an unconfigured log4j application does not print messages at INFO, DEBUG or TRACE levels -and possibly not higher level messages.
 2. log4j有三种主要组件:logger、appender and layout
 3.Log4j提供的appender有以下几种:
  org.apache.log4j.ConsoleAppender(控制台)
  org.apache.log4j.FileAppender(文件)
  org.apache.log4j.DailyRollingFileAppender(每天产生一个日志 文件)
  org.apache.log4j.RollingFileAppender(文件大小到达指定尺寸的时候产生一个新的文件)
  org.apache.log4j.WriterAppender(将日志信息以流格式发送到任意指定的地方)
 4.Log4j提供的layout有以下几种:
  org.apache.log4j.HTMLLayout(以HTML表格形式布局)
  org.apache.log4j.PatternLayout(可以灵活地指定布局模式)
  org.apache.log4j.SimpleLayout(包含日志信息的级别和信息字符串)
  org.apache.log4j.TTCCLayout(包含日志产生的时间、线程、类别等等信息)
 5.Log4j提供的几种输出格式:
  %M:Used to output the method name where the logging request was issued.
  %m:Used to output the application supplied message associated with the logging event.
  %l:Used to output location information of the caller which generated the logging event
  %L:Used to output the line number from where the logging request was issued.
  %p:Used to output the priority of the logging event.
  %n:Outputs the platform dependent line separator character or characters.
   %r:Used to output the number of milliseconds elapsed since the start of the application until the creation of the logging event.
  %F:Used to output the file name where the logging request was issued.
  %d:Used to output the date of the logging event.
  %c:Used to output the category of the logging event
  %C:Used to output the fully qualified class name of the caller issuing the logging request
 6.如果是对于效率要求比较高的话,要在log.debug()之前加上log.isDebugEnabled()进行判断,这样能够大大减少执行时间
  7.对于各个appenders,共有的属性是layout(一般设置为org.apache.log4j.PatternLayout),Threshold(Log的级别)
  (1)ConsoleAppender:Target(System.out和System.err)
  (2)FileAppender:File(定义输出的文件名),Append(定义是否为追加)
  (3)DailyRollingFileAppender(除FileAppender属性外):MaxFileSize(最大文件大小),MaxBackupIndex()

二、Configuration Example
Step 1: add jars of log4j, for example in pom.xml:

<!-- Logging part -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>apache-log4j-extras</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.1</version>
</dependency>

 

Step 2: specify the location of log4j configuration, for example in web.xml:

……
  <context-param> 
  <param-name>log4jConfigLocation</param-name> 
    <param-value>classpath:log4j.xml</param-value> 
  </context-param> 
  <context-param> 
    <param-name>log4jRefreshInterval</param-name> 
    <param-value>60000</param-value> 
  </context-param> 
  <listener> 
  <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> 
  </listener>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
……

 
Step 3: under java/resources, add log4j.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<!--  an appender is an output destination, such as the console or a file;
        names of appenders are arbitrarily chosen  -->
<!-- 1.  输出到控制台中  -->
<appender name="console" class="org.apache.log4j.ConsoleAppender">
<param name="Target" value="System.out"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p -%c{1} - %m%n"/>
</layout>
</appender>
<!-- 2  输出到日志文件 每天一个日志  -->
<appender name="fileAppenderDefault" class="org.apache.log4j.DailyRollingFileAppender">
<param name="File"
value="/data/Logs/Dev/sso/${jvm.process.name}/sso.log" />
<param name="Append" value="true" />
<param name="encoding" value="UTF-8" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p -%c{1} - %m%n" />
</layout>
</appender>
<!--  3 输出到日志文件,2和3根据需要选择一种  -->   
•    <appender name="filelog_appender"   
•         class="org.apache.log4j.RollingFileAppender">   
•         <!-- 设置File参数:日志输出文件名 -->   
•         <param name="File" value="log/testlog4jxml_all.log" />   
•         <!-- 设置是否在重新启动服务时,在原有日志的基础添加新日志 -->   
•         <param name="Append" value="true" />   
•         <!-- 设置文件大小 -->   
•         <param name="MaxFileSize" value="1MB" />   
•         <!-- 设置文件备份 -->   
•         <param name="MaxBackupIndex" value="10000" />   
•         <!-- 设置输出文件项目和格式 -->   
•        <layout class="org.apache.log4j.PatternLayout">   
•        <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p (%c:%L)- %m%n"/>             </layout>   
•      </appender>
<!--  4 配置mybatis的log  -->   
<appender name="mybatis_sql" class="org.apache.log4j.DailyRollingFileAppender">
<param name="File"
value="/data/Logs/Dev/sso/${jvm.process.name}/mybatis_sql.log" />
<param name="Append" value="true" />
<param name="encoding" value="UTF-8" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p -%c{1} - %m%n" />
</layout>
</appender>
<appender name="fileAppenderApiMcnRunningWater" class="org.apache.log4j.rolling.RollingFileAppender"> 
          <rollingPolicy 
             class="org.apache.log4j.rolling.TimeBasedRollingPolicy"> 
             <param name="FileNamePattern" 
             value="/data/Logs/Dev/sso/${jvm.process.name}/sso-RunningWater.log.%d{yyyy-MM-dd}" /> 
          </rollingPolicy> 
          <layout class="org.apache.log4j.PatternLayout"> 
               <param name="ConversionPattern"  value="%d{yyyy-MM-dd HH:mm:ss}\t%m%n" /> 
          </layout> 
     </appender>
<!--通过<logger></logger>的定义可以将各个包中的类日志输出到不同的日志文件中:
Category is deprecated and should be avoided, used Logger,which is a subclass of Categroty, instead-->
<!-- loggers of category 'org.springframework' will only log messages of level "info" or higher;
        if you retrieve Loggers by using the class name (e.g. Logger.getLogger(AClass.class))
        and if AClass is part of the org.springframework package, it will belong to this category   -->
    <logger name="RUNNING_WATER_LOGGER" additivity="false">
        <level value="info"/>
        <appender-ref ref="fileAppenderApiMcnRunningWater"/>
    </logger>
<logger name="com.ibatis" additivity="false">
<level value="debug" />
<appender-ref ref="mybatis_sql"/>
</logger>
<logger name="com.ibatis.common.jdbc.SimpleDataSource"
additivity="false">
<level value="debug" />
<appender-ref ref="mybatis_sql"/>
</logger>
<logger name="com.ibatis.common.jdbc.ScriptRunner" additivity="false">
<level value="debug" />
<appender-ref ref="mybatis_sql"/>
</logger>
<logger name="com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate"
additivity="false">
<level value="debug" />
<appender-ref ref="mybatis_sql"/>
</logger>
<logger name="java.sql.Connection" additivity="false">
<level value="debug" />
<appender-ref ref="mybatis_sql"/>
</logger>
<logger name="java.sql.Statement" additivity="false">
<level value="debug" />
<appender-ref ref="mybatis_sql"/>
</logger>
<logger name="java.sql.PreparedStatement" additivity="false">
<level value="debug" />
<appender-ref ref="mybatis_sql"/>
</logger>
<logger name="java.sql.ResultSet" additivity="false">
<level value="debug" />
<appender-ref ref="mybatis_sql"/>
</logger>
<logger name="org.apache">
<level value="debug" />
</logger>
<logger name="org.springframework">
<level value="debug" />
</logger>
<logger name="net.sourceforge">
<level value="error" />
</logger>
<!--
           all log messages of level "debug" or higher will be logged, unless defined otherwise
           all log messages will be logged to the appender "stdout", unless defined otherwise
       -->
<root>
<priority value="debug" />
<!--通过<configuration to be used-->
<appender-ref ref="fileAppenderDefault" />
</root>
</log4j:configuration>

猜你喜欢

转载自fushine-lee.iteye.com/blog/1973766