A simple example of log4j for Servlet

This Example shows you how to create a log in a Servlet.

A simple example of log4j for Servlet

A simple example of log4j for Servlet

     

This Example shows you how to create a log in a Servlet.

Description of the code:

Logger.getLogger(): Logger class is used for handling the majority of log operations and getLogger method is used for return a logger according to the value of the parameter. If the logger already exists, then the existing instance will be returned. If the logger is not already exist, then create a new instance.

log.info(): This method is used to check that the specified category is INFO enabled or not, if yes then it converts the massage passed as a string argument to a string by using appropriate object renderer of class ObjectRenderer.

 

LoggingServlet :


import java.io.IOException;
import java.io.PrintWriter;

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 LoggingServlet extends HttpServlet {

  private static Logger logger = Logger.getLogger(LoggingServlet.class);

  protected void processRequest(HttpServletRequest request, 
   HttpServletResponse response)

  throws ServletException, IOException {
  response.setContentType("text/html;charset=UTF-8");
  PrintWriter writer = response.getWriter();
  try {
  logger.info("invoked the LoggingServlet...");
  writer.println("Check your web server console...");
  writer.flush();
  writer.close();
  finally {
  writer.close();
  }
  }

  protected void doGet(HttpServletRequest request, 
  HttpServletResponse response)

  throws ServletException, IOException {
  processRequest(request, response);
  }

  protected void doPost(HttpServletRequest request, 
  HttpServletResponse response)

  throws ServletException, IOException {
  processRequest(request, response);
  }
}


Output:



Download code