Implementing log4j in a Java Servlet

Previously I’ve used Log4Net which is a derivative from the original log4j. I can remember it being a bit fiddly to set-up for the 1st time, and then essentially being more or less a copy and paste from then on. I’ve just had a very similar experience with log4j, so I’m documenting my steps for my own review, and possibly to help others out there.

Everything presented here is already available on the Internet, I just found I had to consult 3 or 4 resources to get it working for me. Full credit will be given to those resources at the end.

1. Download the latest log4j release.
2. Add the log4j-1.2.xx.jar (or the appropriate version number for your release) to your web application.
3. Create a log4j.properties file in your WEB-INF folder. And enter the following:

log4j.rootCategory=DEBUG, dest1
log4j.appender.dest1=org.apache.log4j.RollingFileAppender
log4j.appender.dest1.file=/<give full path>/monitoringfailedinserts.log
log4j.appender.dest1.MaxFileSize=1000KB
log4j.appender.dest1.layout=org.apache.log4j.PatternLayout
log4j.appender.dest1.layout.ConversionPattern=%d{dd MMM yyyy HH:mm:ss,SSS} %-5p: %c - %m%n

Other resources will detail the previous parameters in much greater detail, but to give a very brief overview – here I’ve said that the logging should be at DEBUG level, and should use the appender ‘dest1’. Dest1 is a rolling file appender so a new file will be created once the size fills to 1000Kb. I’m also specifiying the message pattern to output the date/time, the logger priority, the category of the output, and then the message followed by a new line.

4. Implement an init() override method in the servlet to be logged from.

@Override
public void init(ServletConfig config) throws ServletException {
   System.out.println("Initialising log4j");
   String log4jLocation = config.getInitParameter("log4j-properties-location");

   ServletContext sc = config.getServletContext();

   if (log4jLocation == null) {
      System.out.println("No log4j properites...");
      BasicConfigurator.configure();
   } else {
      String webAppPath = sc.getRealPath("/");
      String log4jProp = webAppPath + log4jLocation;
      File output = new File(log4jProp);

      if (output.exists()) {
         System.out.println("Initialising log4j with: " + log4jProp);
         PropertyConfigurator.configure(log4jProp);
      } else {
         System.out.println("Find not found (" + log4jProp + ").");
         BasicConfigurator.configure();
      }
   }

   super.init(config);
}

5. In the web.xml add the following init-params within the servlet tags.


<servlet>
   <servlet-name>MyServlet</servlet-name>
   <servlet-class>servlets.MyServlet</servlet-class>
   <init-param>
      <param-name>log4j-properties-location</param-name>
      <param-value>WEB-INF/log4j.properties</param-value>
   </init-param>
   <load-on-startup>1</load-on-startup>
</servlet>

6. Finally (and I’m doing this in a class in my web application rather than directly from the servlet, but hopefully the principal is the same), my class code looks similar to this:


public class MyClass {
   private static Logger logger = Logger.getLogger(BaseAccessData.class.getName());

   private void myMethod() {
      logger.error("Error encountered");
   }
}

To give some credit, the error logging to the standard log file when trying to get this working was absolutely fantastic. A massive thumbs up from me to the Apache Logging for this. The error message described exactly what was wrong, and even provided a link at one stage to an article to resolve the issue.

References

1. Don’t Use System.out.println!
2. Apache Logging FAQ
3. How do I initialize log4j in a Web Application
4. Log4j question to Experts Exchange

Advertisements

One thought on “Implementing log4j in a Java Servlet

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s