log4j简介(二)

来源:互联网 发布:设计网页的软件 编辑:程序博客网 时间:2024/05/29 01:54

继续介绍appender和layout。

 

appender

Log4j allows logging requests to print to multiple destinations. In log4j speak, an output destination is called an appender. Currently, appenders exist for the console, files, GUI components, remote socket servers, JMS, NT Event Loggers, and remote UNIX Syslog daemons. It is also possible to log asynchronously.

//所以,appender的种类也有多个。感叹一下,连jms,daemon都有!太强大了!!!

常用的当然是console和files了。另外,一个logger可以有多个appender,即我在上文提到的,比如同时将log输出到两个文件。

考察这个包:org.apache.log4j.AppenderSkeleton 
里面包含了上面提到的所有种类的appender。其中包含file and console appender的
org.apache.log4j.WriterAppender最常用。

自定义appender的时候,就可以继承这些类:

public class ArchiveRollingFileAppender extends RollingFileAppender{}

//这里写file时可以使用能实现file write rotate 的类,这样可以实现日志归档。

 

Each enabled logging request for a given logger will be forwarded to all the appenders in that logger as well as the appenders higher in the hierarchy. In other words, appenders are inherited additively from the logger hierarchy.

但是这一默认行为可以修改。

 

However, if an ancestor of logger C, say P, has the additivity flag set to false, then C's output will be directed to all the appenders in C and its ancestors upto and including P but not the appenders in any of the ancestors of P.

 

layout

PatternLayout 是log4j的一个标准类。

For example, the PatternLayout with the conversion pattern "%r [%t] %-5p %c - %m%n" will output something akin to:

176 [main] INFO org.foo.Bar - Located nearest gas station.

The first field is the number of milliseconds elapsed since the start of the program. The second field is the thread making the log request. The third field is the level of the log statement. The fourth field is the name of the logger associated with the log request. The text after the '-' (即%m%n)is the message of the statement.

 

实际应用的例子:

<layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="(%-22d{MMM dd, yyyy, HH:mm:ss}), %p, [%t] %C, %m%n"/>
</layout>

 

输出:
(Mar 02, 2011, 11:27:50), INFO, [PROJECT] com.***.common.project.Project, Start project [initial]...

原创粉丝点击