一 、Basic Knoledge:java
1.Common conceptionweb
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.spring
Gülcü has since started the SLF4J and Logback[1] projects, with the intention of offering a successor to log4j.sql
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.apache
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.api
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.mybatis
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.app
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.less
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")
.jvm
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.
Explain on <root>
Near the bottom of the log4j.xml file, look for the following entry:
<root>
<priority value="INFO" />
<appender-ref ref="CONSOLE" />
<appender-ref ref="FILE" />
</root>
Assigning a value to root ensures that any log appenders that do not have a level explicitly assigned inherit the root level (in this case, INFO). For example, by default, the FILE appender does not have a threshold level assigned and so it assumes the root’s.
The possible log levels used by log4j are DEBUG, INFO, WARN, ERROR, and FATAL, as defined in the org.apache.log4j.Level class. Inattention to the proper use of these settings can be costly in terms of performance.
A good rule of thumb is to use INFO or DEBUG only when debugging a particular problem.
Any appender included in the root that does have a level threshold set, should set that threshold to ERROR, WARN, or FATAL unless you are debugging something.
The performance hit with high log levels has less to do with verbosity of messages than with the simple fact that console and file logging, in log4j, involve synchronous writes. An AsyncAppender class is available, but its use does not guarantee better performance. The issues are well-known and are Apache log4j issues, not Identity Manager issues.
The default of INFO in the User Application’s log config file (above) is satisfactory for many environments, but where performance is critical, you should consider changing the above jboss-log4j.xml entry to:
<root>
<priority value="ERROR"/>
<appender-ref ref="FILE"/>
</root>
In other words, remove CONSOLE and set the log level to ERROR. For a fully tested/debugged production setup, there is no need to log at the INFO level, nor any need to leave CONSOLE logging enabled. The performance payoff of turning these off can be significant.
For more information on log4j, consult the documentation available at http://logging.apache.org/log4j/docs.
For more information on the use of Novell Identity Audit with Identity Manager, consult the Novell Identity Manager: Administration Guide.
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()
2、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>