Java Web Programming with Eclipse contents
Last modified January 14, 2011 10:56 am

back next

Web Application Logging





Software developers usually spend a lot of time debugging code. There are several techniques that you can use to find bugs. One technique is to use a debugger, which is a service normally provided by an IDE. With a debugger the developer can step through code one statement at a time as the program executes and inspect that state of variables. For this process to work, the IDE needs to control the execution of the program. When developing a desktop application, you can launch its execution inside Eclipse, set breakpoints, step through the code and inspect the state of variables. However, this procedure is not available to us because Eclipse does not control execution of our code; tomcat controls execution of the code. In order to have these capabilities, we would need to have Eclipse control the execution of Tomcat. One way to do this is to extend Eclipse functionality by installing the Eclipse Web Tools feature. However, we will not cover this option in this book.

Another technique that is useful for debugging is trace statements. In this case, we insert statements at various points in the code to print out useful information. When this output goes into a file, it is called a log file. One of the benefits of using logging is that logging statements can be left in production code, so that log files are generated in the production environment. This enables the developer to diagnose bugs that surface in the production environment.

Rather than simply using the basic print facilities, a logging framework provides a developer with the ability to set different logging levels, so that logging can be more or less verbose depending on the situation. For example, when the code is running in the production environment, you will most likely record error events rather than the fine details that would be useful to debug a known bug.

There are two main choices of logging frameworks when working in Java: log4j and Java logging API. Log4j is the older of the two and is more widely used than the Java logging API. However, the Java logging API provides the same basic functionality as log4j. We will illustrate the use of the log4j logging framework in this chapter.

In this chapter, you will add logging to the website application you started in the chapter on servlet basics.

Add the Log4j Library to the Project

We need to add the log4j library to the project build path and the classpath of the deployed application. Go to the Log4j Website and locate and download the most recent release of the log4j library, which is a Java Archive (jar) containing the classes that comprise the log4j library. At the time of this writing, version 1.3 of log4j is a discontinued branch of development, version 1.4 is in beta release, and version 1.2 is in final release. For our purposes, we use version 1.2, because it is the most recent final release. Place the jar file on the classpath of the deployed application by creating the folder lib under web\WEB-INF, and then copy the jar file into the lib folder. If you create the folder and copy the file inside Eclipse, then you are done. This is the approach that will give you the fewest problems. However, if you do either operation outside Eclipse, then you need to synchronize Eclipse with the file system by selecting File ... Refresh.

To place the jar file on the classpath used for building, right click on the log4j jar file in the package explorer view of Eclipse and select Build Path ... Add to Build Path. In the Project Explorer view of Eclipse, the jar file will no longer be visible under the WEB-INF/lib folder; it now appears under the referenced libraries folder. Note that the Project Explorer view presents a logical view of your project rather than a physical view (file system view).

The following screen shot shows the result of the above procedure.

Add the Log4j library to Build Path

Add the Log4j library to Build Path

Create the Log4j Configuration File

We will configure log4j to write logging messages from our application to a log file that we create in ${TOMCAT_HOME}/logs. Log4j requires configuration in the application that uses it. The easiest way to do this is to put a configuration file in the classpath. Create the file directly under the src directory and insert the contents of the following listing into it. Make sure that you replace ${TOMCAT_HOME} with the actual path to your tomcat installation. Note that under Windows, forward slashes work as directory delimiters in the log4j properties file. If you use back slashes as directory delimiters, each back slash should be escaped with an additional back slash.

Contents of file

log4j.appender.R.layout.ConversionPattern=%d [%t] %-5p %c - %m%n
log4j.rootLogger=WARN, R

If you are on Windows, you can also use backslashes in the pathname for the log file. So in the example above, you could also have used the following.


Observe the Eclipse Build Process

Because we configured src to be a source directory, Eclipse will copy any files that do not end with .java into the default output folder web/WEB-INF/classes. You cannot see this in the Java perspective; to verify this, switch to the Resource perspective using the following steps.

Select Window ... Open Perspective ... Other ... Resource.

Switch back to Java perspective in a similar manner. Also, there are icons in the upper right hand corner of the screen that can be used to speed up perspective switching.

Modify HomeServlet

Add the following line of code to HomeServlet to define a private member variable called logger as shown in the following figure.

private Logger logger = Logger.getLogger(this.getClass());

Add the logger variable to HomeServlet

Add the logger variable to HomeServlet

Notice the error icons indicating that the identifier Logger can not be resolved to a type. Hold down the control and shift keys, and press the O key to organize imports. Because there are two packages in the classpath that contain classes called Logger, Eclipse presents them to you as choices as shown in the following screen shot. The one you should select is org.apache.log4j.Logger.

Organize Imports window

Organize Imports window

Add the following line of code to the doGet method of HomeServlet, which prints a logging message every time the doGet method runs.


The following program listing shows the modified file.

Modified for logging

package website.web;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
public class HomeServlet extends HttpServlet {
   private Logger logger = Logger.getLogger(this.getClass());
   protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
   throws ServletException, IOException {
       PrintWriter writer=resp.getWriter();
       writer.println("<h1>Hello, World!</h1>");

After making changes to the home servlet, you need to reload the website application in the manager application so that Tomcat reloads the class definition of the servlet.

In order for the website log file to get created, we need to write something into it. Do this by sending a request to HomeServlet by following the link http://localhost:8080/website/home. Observe that the file ${TOMCAT_HOME}/logs/website.log gets created. Open the log file in whatever log file viewer you are using and then reload the webpage in the browser window to see the logging message generated with each reload. The following screen shot shows the results in the LogWatcher window.

Observe the logging output in LogWatcher window

Logging output of the LogWatcher window

If you don't see the logging statement appear in the watch window, then try reloading the website application in the manager application.


(1) Attach Source Code

Attach the source code for the log4j library. Refer to instructions given earier for attaching the source code for servlet-api.jar.

back next

Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved.