[ Team LiB ] Previous Section Next Section

Recipe 14.1 Logging Without Log4j

Problem

You want to put a message in the server logs.

Solution

Call the ServletContext.log( ) method inside the servlet.

Discussion

If you just want to log a message in the servlet container's log file and do not need the power of log4j, use the ServletContext.log( ) method. Example 14-1 shows the two versions of the log( ) method. One takes the String message as a parameter, and the other has two parameters: a String message and a Throwable. The servlet log will contain the stack trace of the Throwable if you use this log( ) form.

Example 14-1. A servlet uses the ServletContext.log( ) method
package com.jspservletcookbook;           

import javax.servlet.*;
import javax.servlet.http.*;

public class ContextLog extends HttpServlet {


  public void doGet(HttpServletRequest request, 
      HttpServletResponse response) throws ServletException,
         java.io.IOException {
    
      String yourMessage = request.getParameter("mine");
      //Call the two ServletContext.log methods
      ServletContext context = getServletContext( );

      if (yourMessage == null || yourMessage.equals(""))
      //log version with Throwable parameter
      context.log("No message received:",
          new IllegalStateException("Missing parameter"));
      else
          context.log("Here is the visitor's message: " + yourMessage);
      
      response.setContentType("text/html");
      java.io.PrintWriter out = response.getWriter( );
      //logging servlets probably want to display more HTML
      out.println(
        "<html><head><title>ServletContext logging</title></head><body>");
      out.println("<h2>Messages sent</h2>");
      out.println("</body></html>");
    } //doGet
}

The ServletContext logs its text messages to the servlet container's log file. With Tomcat these logs are found in <Tomcat-installation-directory>/logs. Below is the output of Example 14-1 and the second form of ServletContext.log( ), which prints the message and the Throwable's stack trace (only the first two levels of the method stack are shown). You can see that the log includes the date and time of the logging activity, and the message text:

2003-05-08 14:42:43 No message received:
java.lang.IllegalStateException: Missing parameter
        at com.jspservletcookbook.ContextLog.doGet(Unknown Source)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
...

The single-parameter form of the log( ) method simply displays the date, time, and text of the message, as in the first line of the prior log sample. Each log( ) method call places the message on a new line in the server log file.

See Also

Recipe 14.2-Recipe 14.8 on using log4j to design your own custom logging mechanism; Chapter SRV.3 of the servlet API on the servlet context; links to the latest servlet specification: http://java.sun.com/products/servlet/index.html.

    [ Team LiB ] Previous Section Next Section