看來還是用1.2版的比較好,現在的版本是1.2.15,和1.2.8比有很大的變化。從配置文件裏反映出來,大的結構都變了。現把要點摘錄如下:
Log4j有3個主要部件,loggers, appenders and layouts.
- logger有如下幾個級別,排列如下:
DEBUG < INFO < WARN < ERROR < FATAL
另外Logger x = Logger.getLogger("wombat"); 和 Logger y = Logger.getLogger("wombat");是指向同一個對象,這樣的話不需要到處傳遞對象的引用。
- appender的意思是“輸出的目的地”, 它可以是console,file,gui component,JMS,remote socket server,NT Event Log
- layout顧名思義是管輸出的格式的,PatternLayout是Log4j的標準輸出格式,具體內容請參照javadoc
Format modifier | left justify | minimum width | maximum width | comment |
---|---|---|---|---|
%20c | false | 20 | none | Left pad with spaces if the category name is less than 20 characters long. |
%-20c | true | 20 | none | Right pad with spaces if the category name is less than 20 characters long. |
%.30c | NA | none | 30 | Truncate from the beginning if the category name is longer than 30 characters. |
%20.30c | false | 20 | 30 | Left pad with spaces if the category name is shorter than 20 characters. However, if category name is longer than 30 characters, then truncate from the beginning. |
%-20.30c | true | 20 | 30 | Right pad with spaces if the category name is shorter than 20 characters. However, if category name is longer than 30 characters, then truncate from the beginning. |
- 最後貼個例子:
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=example.log
log4j.appender.R.MaxFileSize=100KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
- 補充一點,配置文件要麼放在classpath裏,不用特殊聲明。要麼指明路徑,如下初始化,一次即可。
String resource =
;
URL configFileResource =
InitUsingPropertiesFile..getResource(resource);
PropertyConfigurator.configure(configFileResource);