A simple example of log4j for Servlet

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


 
Ads

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

     

Advertisements

Share on Google+Share on Google+

A simple example of log4j for Servlet

Posted on: September 10, 2008 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Advertisements

Ads
 

Discuss: A simple example of log4j for Servlet   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:4
Chubby
November 1, 2011
HlpTrjimCw

Mighty useful. Make no misakte, I appreciate it.
Nishanth Thomas
February 29, 2012
Log4j using servlet log4j.xml

// Program by Nishanth Thomas â?? Insolutions Global Bangalore // example class file package com.logs; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.FileAppender; import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout; import org.apache.log4j.PropertyConfigurator; import org.apache.log4j.xml.DOMConfigurator; public class Logscollected { static Logger log = Logger.getLogger(Logscollected.class); public static void logscollection(Exception e, HttpServletRequest request) throws IOException{ HttpSession session = request.getSession(); String exceptiondetail = â??â?? ; //create a folder in your application config and place log4j.xml file there and // get path by the following; String strPath = request.getRealPath("config"); DOMConfigurator.configure(strPath+"/"+"log4jexp.xml"); //create log4j.xml file as give name like shown above log4jexp; try{ //// /* Get the Stack Trace messages ////// e = ((e==null)?((Exception)request.getAttribute("Exception")):e); StackTraceElement stem[]=e.getStackTrace(); for(int i=0;i<stem.length;i++){ if (!exceptiondetail.equals("")) exceptiondetail += "\n"; exceptiondetail += "\t"; exceptiondetail=exceptiondetail+stem[i].toString(); } log.debug(exceptiondetail); //log.info(e); // log.warn("Here is some WARN"); // log.info(object); log.error(e); // log.fatal("Here is some FATAL"); }catch(Exception e1){ e1.printStackTrace(); } } } In the catch of any servlet call that function like this try{ // Some codeâ?¦â?¦â?¦â?¦ } catch(Exception e) { // Logs collection log 4j------------------------ Logscollected.logscollection(e,request); //--------------------------- } Finally Lo4j.xml here we renamed to log4jexp.xml to avoid conflicts with server log4j.xml file palce log4jexp.xml in config folder ( here I used) <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" > <--configure path according to your requrmts to save log file --> <log4j:configuration> <!--code between <log4j:configuration> </log4j:configuration> --> <appender name="daoAppender" class="org.apache.log4j.RollingFileAppender"> <param name="maxFileSize" value="100KB" /> <param name="maxBackupIndex" value="2" /> <param name="File" value="${jboss.server.home.dir}/deploy/myexampleprj.war/serverlogs/serverlogs.txt" /> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d{dd-MMM-yyyy HH:mm};%5p %c %m%n" /> </layout> </appender> <--configure path according for diff packge to your requrmts to save log file --> <!--appender name="appAppender" class="org.apache.log4j.RollingFileAppender"> <param name="maxFileSize" value="100KB" /> <param name="maxBackupIndex" value="2" /> <param name="File" value="${jboss.server.home.dir}/deploy/myexampleprj.war/serverlogs/serverlogs.txt" /> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d{ABSOLUTE} %5p %c{1}: %m%n " /> </layout> </appender--> <!â??package name given in category here com is the package give package name --> <!--category name="com.ex.actions"> <priority value="DEBUG"/> <appender-ref ref="appAppender"/> </category--> <!--package name given in category here com is the package --> <category name="com"> <priority value="DEBUG"/> <appender-ref ref="daoAppender"/> </category> <root> <!-- <appender-ref ref="appAppender" /> <appender-ref ref="daoAppender" /> --> </root> </log4j:configuration>
Nishanth Thomas
February 29, 2012
Log4j - servlet web applications

// Program by Nishanth Thomas â?? Insolutions Global Bangalore // example class file package com.logs; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.FileAppender; import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout; import org.apache.log4j.PropertyConfigurator; import org.apache.log4j.xml.DOMConfigurator; public class Logscollected { static Logger log = Logger.getLogger(Logscollected.class); public static void logscollection(Exception e, HttpServletRequest request) throws IOException{ HttpSession session = request.getSession(); String exceptiondetail = â??â?? ; //create a folder in your application config and place log4j.xml file there and // get path by the following; String strPath = request.getRealPath("config"); DOMConfigurator.configure(strPath+"/"+"log4jexp.xml"); //create log4j.xml file as give name like shown above log4jexp; try{ //// /* Get the Stack Trace messages ////// e = ((e==null)?((Exception)request.getAttribute("Exception")):e); StackTraceElement stem[]=e.getStackTrace(); for(int i=0;i<stem.length;i++){ if (!exceptiondetail.equals("")) exceptiondetail += "\n"; exceptiondetail += "\t"; exceptiondetail=exceptiondetail+stem[i].toString(); } log.debug(exceptiondetail); //log.info(e); // log.warn("Here is some WARN"); // log.info(object); log.error(e); // log.fatal("Here is some FATAL"); }catch(Exception e1){ e1.printStackTrace(); } } } In the catch of any servlet call that function like this try{ // Some codeâ?¦â?¦â?¦â?¦ } catch(Exception e) { // Logs collection log 4j------------------------ Logscollected.logscollection(e,request); //--------------------------- } Finally Lo4j.xml here we renamed to log4jexp.xml to avoid conflicts with server log4j.xml file palce log4jexp.xml in config folder ( here I used) <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" > <--configure path according to your requrmts to save log file --> <log4j:configuration> <!--code between <log4j:configuration> </log4j:configuration> --> <appender name="daoAppender" class="org.apache.log4j.RollingFileAppender"> <param name="maxFileSize" value="100KB" /> <param name="maxBackupIndex" value="2" /> <param name="File" value="${jboss.server.home.dir}/deploy/myexampleprj.war/serverlogs/serverlogs.txt" /> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d{dd-MMM-yyyy HH:mm};%5p %c %m%n" /> </layout> </appender> <--configure path according for diff packge to your requrmts to save log file --> <!--appender name="appAppender" class="org.apache.log4j.RollingFileAppender"> <param name="maxFileSize" value="100KB" /> <param name="maxBackupIndex" value="2" /> <param name="File" value="${jboss.server.home.dir}/deploy/myexampleprj.war/serverlogs/serverlogs.txt" /> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d{ABSOLUTE} %5p %c{1}: %m%n " /> </layout> </appender--> <!â??package name given in category here com is the package give package name --> <!--category name="com.ex.actions"> <priority value="DEBUG"/> <appender-ref ref="appAppender"/> </category--> <!--package name given in category here com is the package --> <category name="com"> <priority value="DEBUG"/> <appender-ref ref="daoAppender"/> </category> <root> <!-- <appender-ref ref="appAppender" /> <appender-ref ref="daoAppender" /> --> </root> </log4j:configuration>
I'm what I'm
May 7, 2012
log file location

Where can i find those log files...in wich path it will be stored??? anyone help me out...

Ads

 

Ads