在运行时初始化 Log4j

[来源] 达内    [编辑] 达内   [时间]2012-09-14

我们可在程序运行时来通过配置文件初始化

[代码] log4j.xml
01
<?xml version="1.0" encoding="UTF-8"?>
02
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
03
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="true">
04
<appender name="consoleAppender"
05
class="org.apache.log4j.ConsoleAppender">
06
<param name="Threshold" value="DEBUG" />
07
<layout class="org.apache.log4j.PatternLayout">
08
<param name="ConversionPattern" value="%d %-5p [%c]-[%L] %m%n" />
09
</layout>
10
</appender>
11
<appender name="fileAppender"
12
class="org.apache.log4j.RollingFileAppender">
13
<param name="Threshold" value="DEBUG" />
14
<param name="File" value="C:/log4jFiles/myapp.log"/>
15
<layout class="org.apache.log4j.PatternLayout">
16
<param name="ConversionPattern" value="%d %-5p [%c]-[%L] %m%n" />
17
</layout>
18
</appender>
19
<root>
20
<priority value ="debug" />
21
<appender-ref ref="fileAppender" />
22
<appender-ref ref="consoleAppender" />
23
</root>
24
</log4j:configuration>
[代码] 初始化方法
view sourceprint?
1
import org.apache.log4j.BasicConfigurator;
2
import org.apache.log4j.xml.DOMConfigurator;
3

4
String configPath = "C:/log4jFiles/log4j.xml";
5

6
BasicConfigurator.resetConfiguration();
7
DOMConfigurator.configure(configPath);
8
DOMConfigurator.configureAndWatch(configPath);
 

资源下载