O'Reilly logo

Java Servlet & JSP Cookbook by Bruce W. Perry

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

14.3. Using a Logger Without a Configuration File

Problem

You want to use a logger in a servlet without setting up your own configuration file.

Solution

Create the logger in the servlet and use the org.apache.log4j.BasicConfigurator class to configure the logger.

Discussion

log4j allows the configuration of a logger without a provided configuration or properties file. Example 14-3 is a servlet that instantiates a logger in its init( ) method, which the servlet container calls when the servlet instance is created. The static BasicConfigurator.configure( ) method creates a ConsoleAppender ; in other words, the logger will log its messages to the console using a default format.

Example 14-3. A servlet uses BasicConfigurator to configure a logger

package com.jspservletcookbook;import org.apache.log4j.Logger;
import org.apache.log4j.BasicConfigurator;

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

public class LoggerNconfig extends HttpServlet {

private Logger log = null;

  public void init( ){
  
      //use the root logger
      log = Logger.getRootLogger( );
      
      //this logger will log to the console with a default message format
      BasicConfigurator.configure( );

  
  }

  public void doGet(HttpServletRequest request, 
    HttpServletResponse response)
      throws ServletException, java.io.IOException {
    
        //display a DEBUG level message
        log.debug("Sending a DEBUG message");

        // display an INFO level message
        log.info("Sending an INFO message"); //better display some HTML response.setContentType("text/html"); java.io.PrintWriter ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required