标签:
因为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可以写绝对地址,也可以写相对地址。
标签:
原文地址:http://www.cnblogs.com/bigbang92/p/log4j2_servlet.html