简体   繁体   中英

Log4j2 in Web application

How to configure Log4j2 with a simple java web application? I went through the tutorial in apache website but it did not give any straight forward examples wrt web applications. I used it in stand alone applications where I had static variables for loggers. But in Servlet, I think we cannot have instance variables. Should we use as static variable inside doPost ?

Also, any pointers to a configured log4j2 web app or tutorial with all the steps will be helpful as I am unable to find a right one.

I'm running on a Tomcat 6.0 server.

Servlets 3.0 environment

It is such simple as to put log4j2.xml into WEB-INF/classes .

From documentation

The Short Story 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.

Servlets 2.5 environment

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. This is easily accomplished using the following web.xml code:

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

<filter>
    <filter-name>log4jServletFilter</filter-name>
    <filter-class>org.apache.logging.log4j.core.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>

Then write configuration options:

<context-param>
    <param-name>log4jContextName</param-name>
    <param-value>myApplication</param-value>
</context-param>

<context-param>
    <param-name>log4jConfiguration</param-name>
    <param-value>file:///etc/myApp/myLogging.xml</param-value>
</context-param>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM