How do I initialize Log4J in a web application?
Author: Deron Eriksson
Description: This Java tutorial how to initialize Log4J with a servlet in a web application.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 1.5.1 || Tomcat 5.5.20

Page:    1 2 >

In other tutorials, we saw that log4j needs to be initialized in order to be used, and we saw how log4j can be initialized with a BasicConfigurator and initialized with a PropertyConfigurator. This typically occurs when an application starts up. In a web application, we'd also like log4j to start up when the application starts up. One straightforward way of doing this is to put this log4j initialization in a servletW, and specify for the servlet to start up when the application starts up.

Here is a web application project to illustrate this. It contains the log4j jarW file in its build path, a file, a web.xmlW file, a log4j initialization servlet, and a test servlet to try out our log4j initialization.

'log4j-webapp-demo' project

Let's start by examining our web.xml file. It contains references to our two servletsW, Log4JTestServlet and Log4JInitServlet. Log4JTestServlet gets mapped to /test so that it can be hit via a browser. The Log4JInitServlet starts up when the web application starts up because of the <load-on-startup> tag. Notice that it has an init-param and an init-value. This value gets passed to the servlet and specifies the location of our file.


<?xml version="1.0" encoding="UTF-8"?>
<web-app id="log4j-webapp-demo" version="2.4"

Let's look at the Log4JInitServlet. In its init() method, it reads in the 'log4j-properties-location' init param value. If the init param doesn't exist, the application gets initialized via the BasicConfigurator. If is does exist, it gets the application's web directory location and appends the init param value to that. If the file exists at that location, it initializes log4j via the PropertyConfigurator using the file. If the file doesn't exist, the application gets initialized via the BasicConfigurator.

package test;


import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.PropertyConfigurator;

public class Log4JInitServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

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

		ServletContext sc = config.getServletContext();

		if (log4jLocation == null) {
			System.err.println("*** No log4j-properties-location init param, so initializing log4j with BasicConfigurator");
		} else {
			String webAppPath = sc.getRealPath("/");
			String log4jProp = webAppPath + log4jLocation;
			File yoMamaYesThisSaysYoMama = new File(log4jProp);
			if (yoMamaYesThisSaysYoMama.exists()) {
				System.out.println("Initializing log4j with: " + log4jProp);
			} else {
				System.err.println("*** " + log4jProp + " file not found, so initializing log4j with BasicConfigurator");

Here is the file. I described properties files in another tutorial so I won't describe them here.

# This sets the global logging level and specifies the appenders
log4j.rootLogger=INFO, myConsoleAppender

# settings for the console appender
log4j.appender.myConsoleAppender.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

Our test servlet is shown below. It contains a logger called log. Within its doGet() method, it displays the message 'Howdy' in response to a browser request, and it contains calls to log.debug(),, log.warn(), log.error(), and log.fatal().

package test;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

public class Log4JTestServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {

	private static final long serialVersionUID = 1L;
	static Logger log = Logger.getLogger(Log4JTestServlet.class);

	public Log4JTestServlet() {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		log.debug("debug message");"info message");
		log.warn("warn message");
		log.error("error message");
		log.fatal("fatal message");


(Continued on page 2)

Page:    1 2 >