首先到http://logging.apache.org/log4j/2.x/download.html 上下載下傳最新的log4j2的jar包,然後再eclipse中加入log4j-api-2.4.1.jar和log4j-core-2.4.1.jar,需要注意的是不要将所有jar都導入工程造成不必要的混亂。

左邊豎欄是Event的Level,右邊橫欄是LoggerConfig(即filter)的Level。Yes的意思就是這個event可以通過filter,no的意思就是不能通過filter。
可以看到,INFO級别的Event是無法被ERROR級别的LoggerConfig的filter接受的。是以,INFO資訊不會被輸出。
log4j2與以往的log4j有一個明顯的不同,其配置檔案隻能采用.xml, .json或者 .jsn,而不是.properties檔案。其格式如下:
使用Log4j2的一般都約定俗成的寫一個log4j2.xml放在src目錄下使用。
在系統工程裡面,将log4j2的配置檔案放到src目錄底下很不友善。如果能把工程中用到的所有配置檔案都放在一個檔案夾裡面,當然就更整齊更好管理了。但是想要實作這一點,前提就是Log4j2的配置檔案能重新定位到别處去,而不是放在classpath底下。
看看文檔裡怎麼說吧:
1.Log4j will inspect the "log4j.configurationFile" system property and, if set,will attempt to load the configuration using the ConfigurationFactory that matches the file extension.
2.If no system property is set the JSON ConfigurationFactory will look for log4j2-test.json or log4j2-test.jsn in the classpath.
3.If no such file is found the XML ConfigurationFactory will look for log4j2-test.xml in the classpath.
4.If a test file cannot be located the JSON ConfigurationFactory will look for log4j2.json or log4j2.jsn on the classpath.
5.If a JSON file cannot be located the XML ConfigurationFactory will try to locate log4j2.xml on the classpath.
6.If no configuration file could be located the DefaultConfiguration will be used. This will cause logging output to go to the console.
可見,如果沒有設定"log4j.configurationFile" system property的話,application将在classpath中按照如下查找順序來找配置檔案:
log4j2-test.json 或log4j2-test.jsn檔案
log4j2-test.xml檔案
log4j2.json 或log4j2.jsn檔案
log4j2.xml檔案
如果想将配置檔案重命名并放到别處,就需要設定系統屬性log4j.configurationFile。
設定的方式是在VM arguments中寫入該屬性的key和value:
在myeclipse中,就是 右鍵-》run as -》run configuration-》右邊視窗的“(x)=argument”=》VM arguments
然後寫入上述key和value即可。
-D是參數,不能缺少。
測試
在“D:\learning\blog\20130115\config\”路徑下編寫檔案:
root LoggerConfig的Level設為INFO。
在myeclipse中寫入log4j.configurationFile系統屬性:
測試的java程式如上文,在此不再重複。運作,console輸出如下: