Configuring Log4j2 in web application using log4j-web.jar

13,074

Ok, after a little bit of more research and re-reading of the links I refered to earlier I finally managed to configure log4j2 in my web application and now I am getting logs as expected. Now would like to mention what I was doing wrong.

As stated in the link https://logging.apache.org/log4j/2.x/manual/webapp.html

I need not register Log4jServletContextListener class in my deployment descriptor if I am using servlet 3.0 or above, it needs to be registered only in servlet 2.5 and below. Also I need not provide the file location if I am adhering to the naming convention of log4j2.

Another change instead of log4j2.properties now I am using log4j2.xml as the format for properties file in log4j2 is different then that used in log4j1. Thanks to the answers given in the link below which helped me figure this out. Log4j 2 doesn't support log4j.properties file anymore?

For the current format supported refer link https://logging.apache.org/log4j/2.0/manual/configuration.html#Properties

Below is how my deployment descriptor and log4j configuartion file looks now :

web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
   <display-name>College Administration</display-name>
  <servlet>
      <servlet-name>loginServlet</servlet-name>
      <servlet-class>kumar.suraj.college.administration.login.LoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
      <servlet-name>loginServlet</servlet-name>
      <url-pattern>/login</url-pattern>
  </servlet-mapping>

  </web-app>

log4j2.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE xml>
    <Configuration status="WARN">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
           <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </Console>
        <File name="File" fileName="E:\\DEVELOPMENT\\JAVA\\web-logs\\web-college-administration\\applicationLogs.log">
           <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>    
        </File>
     </Appenders>
     <Loggers>
     <Root level="debug">
         <AppenderRef ref="Console"/>
         <AppenderRef ref="File"/>
     </Root>
     </Loggers>
     </Configuration>
Share:
13,074
Suraj Kumar
Author by

Suraj Kumar

Updated on June 26, 2022

Comments

  • Suraj Kumar
    Suraj Kumar almost 2 years

    I am trying to configure log4j2 in my webapplication by following some tutorials. I am working with glassfish 4.1.1 server and servlet version 3.1. I am able to configure the logging feature with the below configuration:

    log4j.properties

         # Root logger option
         log4j.rootLogger=INFO, consoleAppender, fileAppender
    
         # debug level logger
         log4j.logger.kumar.suraj.college.administration.login=DEBUG
    
         # Redirect log messages to console
         log4j.appender.consoleAppender=org.apache.log4j.ConsoleAppender
         log4j.appender.consoleAppender.Target=System.out
         log4j.appender.consoleAppender.layout=org.apache.log4j.PatternLayout
         log4j.appender.consoleAppender.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
    
         # Redirect log messages to a log file, support file rolling.
         log4j.appender.fileAppender=org.apache.log4j.DailyRollingFileAppender
         log4j.appender.fileAppender.File=E:\\DEVELOPMENT\\JAVA\\web-logs\\web-college-administration\\applicationLogs.log
         log4j.appender.fileAppender.layout=org.apache.log4j.PatternLayout
         log4j.appender.fileAppender.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
    

    the properties file is placed in src/main/resources folder

    web.xml

            <?xml version="1.0" encoding="UTF-8"?>
            <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee"  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee   http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID"   version="3.1">
           <display-name>College Administration</display-name>
           <!--     <context-param>
                        <param-name>log4jConfiguration</param-name>
                        <param-value>/log4j.properties</param-value>
                    </context-param>is it required
             -->
           <!--from where is this class referenced in dependency without web -->
           <listener>
                <listener-class>org.apache.logging.log4j.web.Log4jServletContextListener</listener-class>
           </listener>
          <servlet>
              <servlet-name>loginServlet</servlet-name>
              <servlet-class>kumar.suraj.college.administration.login.LoginServlet</servlet-class>
          </servlet>
          <servlet-mapping>
              <servlet-name>loginServlet</servlet-name>
              <url-pattern>/login</url-pattern>
          </servlet-mapping>
    
          </web-app>
    

    the context param that defines file location is commented out. probably log4j looks by default for a file with name log4j.properties. However just wanted to know if its the right way to specify the file location.

    Also I am not sure from which jar is org.apache.logging.log4j.web.Log4jServletContextListener being referenced. I searched all jar files but could not locate this class.

    LoginServlet.java

       package kumar.suraj.college.administration.login;
    
       import java.io.IOException;
       import javax.servlet.ServletException;
       import javax.servlet.http.HttpServlet;
       import javax.servlet.http.HttpServletRequest;
       import javax.servlet.http.HttpServletResponse;
       import org.apache.log4j.Logger;
    
       import kumar.suraj.college.administration.adduser.AddUserServlet;
    
       public class LoginServlet extends HttpServlet {
            private static final long serialVersionUID = 1L;
    
            // final static Logger logger = LogManager.getLogger(LoginServlet.class);
            final static Logger logger = Logger.getLogger(LoginServlet.class);
    
            public LoginServlet() {
               super();
            }
    
            @Override
            protected void doGet(final HttpServletRequest request, final     HttpServletResponse response)
            throws ServletException, IOException {
               LoginServlet.logger.debug("debug level logging supported");              response.getWriter().append("Servedat:").append(request.getContextPath());
        response.getWriter().append("Hello Suraj");
    }
    
           @Override
           protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
                   LoginServlet.logger.debug("debug level logging supported");
                   this.doGet(request, response);
           }
      }
    

    pom.xml dependency for log4j

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    

    All this works fine and I get logs in both console as well as file. But when I try to change the configuration as per the following links :

    https://logging.apache.org/log4j/2.x/manual/webapp.html#Servlet-3.0 https://logging.apache.org/log4j/2.x/maven-artifacts.html

    Like instead of dependency specified earlier I switch to

            <dependency>
               <groupId>org.apache.logging.log4j</groupId>
               <artifactId>log4j-web</artifactId>
               <version>2.6.2</version>
            </dependency>
    

    log4j-api and log4j-core are added as transitive dependencies with log4j-web.jar

    other changes I made in LoginServlet.java is because of the compile time error I was getting after switching to log4j-web.jar which is as below :

         import org.apache.logging.log4j.LogManager;
         import org.apache.logging.log4j.Logger;
    
    
         public class LoginServlet extends HttpServlet {
             private static final long serialVersionUID = 1L;
             final static Logger logger = LogManager.getLogger(LoginServlet.class);
             // final static Logger logger = Logger.getLogger(LoginServlet.class);
    

    the main changes are in the initialization of logger variable and the two imports. rest all configuration remained as it is. Also i was able to locate the listener class specified in web.xml in log4j-web.jar in this case. Still logging is not working with this configuartion.

    Could some one please help me with it or tell me what I am doing wrong here ?