Log4j – 如何配置多个logger?
内容简介:
本文主要介绍 在一个系统中如何通过log4j的配置文件配置出多个logger,使得该系统可以在不同路径下输出多个内容不同的log 文件。并通过该实例的实现过程进一步讲解log4j的一些特性。
具体内容:
1. 如何在项目中配置log4j使得该系统可以输出web test的日志文件(自定义格式)到工程dist目录下的junitLog/WebTestLog.log目录下,输出508 check日志(html格式)到c:/508log.html路径下?
第一步:加入log4j-1.2.8.jar到lib下。
第三步:根据需要修改log4j配置文件中的相应属性,修改之前就必须知道这些都是干什么的,在后面的部分具体讲解。
该实例中 根据需要 配好的log4j.properties如下:
Logger
nameAssigned
levelInherited
levelroot
Proot
Proot
X
Px
Px
X.Y
none
Px
X.Y.Z
Pxyz
Pxyz
在上面例子中我们可以了解到如果一个普通logger定义了Level,则其level就使用它定义的(例如:logger X),如果没有定义,就使用其父logger的(例如:logger X.Y)。
请看下面的例子(继承关系对确定logger的Appender的影响):
Logger
NameAdded
AppendersAdditivity
FlagOutput Targets
Comment
root
A1
not applicable
A1
The root logger is anonymous but can be accessed with the Logger.getRootLogger() method. There is no default appender attached to root.
x
A-x1, A-x2
true
A1, A-x1, A-x2
Appenders of "x" and root.
x.y
none
true
A1, A-x1, A-x2
Appenders of "x" and root.
x.y.z
A-xyz1
true
A1, A-x1, A-x2, A-xyz1
Appenders in "x.y.z", "x" and root.
security
A-sec
false
A-sec
No appender accumulation since the additivity flag is set to false.
security.access
none
true
A-sec
Only appenders of "security" because the additivity flag in "security" is set to false.
在上面的例子中我们可以看出:
a. 如果一个普通logger定义Appender且其AdditivityFlag是true,则该logger的Appender包括其定义的Appender及其父logger定义的Appender。例如:logger‘x’。
b. 如果一个普通logger没有定义Appender,但其AdditivityFlag是true,则该logger的Appender为其父logger定义的Appender。例如:logger‘x.y’。
c. 如果一个普通logger定义了Appender,但其AdditivityFlag是false,则该logger的Appender只为其定义的Appender。例如:logger‘security’。