Recipe 14.2 Setting Up Log4j


Problem

You want to set up log4j for use in your web application.

Solution

Download the log4j distribution from the Apache Jakarta project and place the accompanying log4j-1.2.8.jar file (the name will be different for different log4j versions) in the WEB-INF/lib directory of your web application.

Discussion

The log4j package is available for use under the Apache Software License, which is included with the distribution. Here are the steps for setting up log4j for your web application:

  1. Go to the log4j web site and download the distribution in ZIP (Windows) or gzipped (Unix-based systems) format: http://jakarta.apache.org/log4j/docs/download.html. The downloaded file will be named something like jakarta-log4j-1.2.8.zip or jakarta-log4j-1.2.8.tar.gz .

  2. Unpack the distribution, which creates a directory jakarta-log4j-1.2.8 (for Version 1.2.8 of log4j ). Inside the dist directory of this top-level directory is the log4j-1.2.8.jar file. Copy this JAR file into the WEB-INF/lib directory of your web application(s).

  3. Create a log4j properties file and place it in the web application's WEB-INF/classes directory. This is typically a text file with name/value pairs for configuring log4j elements such as loggers, appenders, and layouts. Recipe 14.4 includes an example of this file.

  4. In the servlets or beans where you will use a logger, include the proper import statements. Example 14-2 is a skeletal servlet showing the classes that you might typically use.

Example 14-2. Importing log4j- related packages
  import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator;  import javax.servlet.*; import javax.servlet.http.*; public class LoggerSkel extends HttpServlet {   private Logger log;  public void init( ){          //log4j will find the log4j.properties file       //in WEB-INF/classes       log = Logger.getLogger(LoggerSkel.class);       //Just an example of using the logger       log.debug("Instance created of: " + getClass( ).getName( ));      }  public void doGet(HttpServletRequest request,      HttpServletResponse response) throws ServletException,       java.io.IOException {          //do logging here if necessary            } //doGet     } 

As long as log4j-1.2.8.jar is located in WEB-INF/lib , your servlet can use the necessary classes from the org.apache.log4j.* packages.

See Also

Recipe 14.3-Recipe 14.8 on using log4j to design your own custom logging mechanism; the log4j download site: http://jakarta.apache.org/log4j/docs/download.html; the log4j project documentation page: http://jakarta.apache.org/log4j/docs/documentation.html.



Java Servlet & JSP Cookbook
Java Servlet & JSP Cookbook
ISBN: 0596005725
EAN: 2147483647
Year: 2004
Pages: 326

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net