因為Servlet常用的版本有兩個,即2.5與3.0。要在web application中使用Log4j2,還需要加入log4j-web的jar包。log4j通過web.xml中的context參數log4jConfiguration來查找配置文件。如果沒有的話,那么會在WEB-INF目錄下查找以“log4j2”開頭命名的xml文件。如果不止一個log4j2開頭的文件,那么會優先使用log4j2-name命名的文件,name為項目名稱。否則會使用第一個文件。
log4j2能夠在Servlet3.0下正常使用且不用配置。因為在Servlet3.0的API中加入了ServletContainerInitializer,它自動啟動了Filter和ServletContextListener(這兩個類在Servlet2.5中需要配置)。官方文檔有一個注意事項:
Important Note! For performance reasons, containers often ignore certain JARs known not to
contain TLDs or ServletContainerInitializers and do not scan them for web-fragments and
initializers. Importantly, Tomcat 7 <7.0.43 ignores all JAR files named log4j*.jar, which prevents this
feature from working. This has been fixed in Tomcat 7.0.43, Tomcat 8, and later. In Tomcat 7 <7.0.43
you will need to change catalina.properties and remove "log4j*.jar" from the jarsToSkip property. You may need to do something similar on other containers if they skip scanning Log4j JAR files.
在tomcat版本小於7.0.43的時候,需要修改catalina.properties文件的 jarToSkip配置,把“log4j*.jar”去掉。
如果你不想讓log4j2自動啟動,那么可以配置isLog4jAutoInitializationDisabled參數。
1 <context-param> 2 <param-name>isLog4jAutoInitializationDisabled</param-name> 3 <param-value>true</param-value> 4 </context-param>
在Servlet2.5中,需要我們自己配置filter和Listener。配置規則如下:
1 <listener> 2 <listener-class>org.apache.logging.log4j.web.Log4jServletContextListener 3 </listener-class> 4 </listener> 5 <filter> 6 <filter-name>log4jServletFilter</filter-name> 7 <filter-class>org.apache.logging.log4j.web.Log4jServletFilter</filter-class> 8 </filter> 9 <filter-mapping> 10 <filter-name>log4jServletFilter</filter-name> 11 <url-pattern>/*</url-pattern> 12 <dispatcher>REQUEST</dispatcher> 13 <dispatcher>FORWARD</dispatcher> 14 <dispatcher>INCLUDE</dispatcher> 15 <dispatcher>ERROR</dispatcher> 16 <dispatcher>ASYNC</dispatcher><!-- Servlet 3.0 w/ disabled auto-initialization only; not supported in 17 </filter-mapping>
以上兩種情況都允許自定義context parameters。有3個參數可供配置:
isLog4jContextSelectorNamed:布爾類型配置,由它選擇是否使用JndiContextSelector。如果它設為true的話,那么log4jContextName一定要配置或者在web.xml中指定display-name。並且log4jConfiguration也要配置一個URL,這個URL是log4j2的配置文件地址,但這個不是必須要配置的。
log4jContextName:配置display-name。
log4jConfiguration:log4j配置文件的路徑。
示例如下:
1 <context-param> 2 <param-name>isLog4jContextSelectorNamed</param-name> 3 <param-value>true</param-value> 4 </context-param>
1 <context-param> 2 <param-name>log4jContextName</param-name> 3 <param-value>myApplication</param-value> 4 </context-param>
1 <context-param> 2 <param-name>log4jConfiguration</param-name> 3 <param-value>file:///etc/myApp/myLogging.xml</param-value> 4 </context-param>
這里的log4jConfiguration可以寫絕對地址,也可以寫相對地址。