首先到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输出如下: