日志系列之WEB应用中使用Log4j2

  当在Web应用中使用Log4j2或者其它日志框架时,需要确保:web应用启动时,日志组件能够被启动;web应用关闭时,日志组件能够被关闭。对于Log4j2,需要在应用中添加log4j-web包。

log4j2.xml的加载

  1. 首先寻找web.xml中指定的log4j2.xml文件,如下图所示:
   <context-param>
     <param-name>log4jConfigLocation</param-name>
     <param-value>/WEB-INF/conf/log4j2.xml</param-value>
   </context-param>
  1. 其次寻找WEB-INF目录下文件名以log4j2开头的文件,当找到多个文件时,如果存在”log4j2-应用名”的文件,则进行加载;否则,加载第一个文件;
  2. 在classpath中寻找log4j2.xml文件;

log4j启动和初始化

Servlet 3.0

  web应用启动时会自动初始化log4j,关闭时会自动清理log4j。

Log4j 2 “just works” in Servlet 3.0 and newer web applications. It is capable of automatically starting when the application deploys and shutting down when the application undeploys. Thanks to the ServletContainerInitializer API added to Servlet 3.0, the relevant Filter and ServletContextListener classes can be registered dynamically on web application startup.

Servlet 2.5

  需要手动配置Log4jServletContextListener 和Log4jServletFilter,且Listener和Filter都必须放在第一个位置,如下图所示:

If you are using Log4j in a Servlet 2.5 web application, or if you have disabled auto-initialization with the isLog4jAutoInitializationDisabled context parameter, you must configure the Log4jServletContextListener and Log4jServletFilter in the deployment descriptor or programmatically. The filter should match all requests of any type. The listener should be the very first listener defined in your application, and the filter should be the very first filter defined and mapped in your application.

<listener>
        <listener-class>org.apache.logging.log4j.web.Log4jServletContextListener</listener-class>
    </listener>

    <filter>
        <filter-name>log4jServletFilter</filter-name>
        <filter-class>org.apache.logging.log4j.web.Log4jServletFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>log4jServletFilter</filter-name>
        <url-pattern>/*</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
        <dispatcher>INCLUDE</dispatcher>
        <dispatcher>ERROR</dispatcher>
        <dispatcher>ASYNC</dispatcher><!-- Servlet 3.0 w/ disabled auto-initialization only; not supported in 2.5 -->
    </filter-mapping>

依赖的jar包

  1. log4j-api-2.4.1.jar
  2. log4j-core-2.4.1.jar
  3. log4j-web-2.4.1.jar

Servlet版本查看

查看web.xml的的version属性即可:

<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
    http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值