Log4j in Servlets

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Kedar Kachare
    New Member
    • Feb 2008
    • 3

    Log4j in Servlets

    How to use Log4j to create log files using file appender in a Servlet? Also, how to make that Servlet read the log4j.propertie s file?


    I have tried following:

    My web.xml( I use Eclipse europa)
    Code:
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
    
            <display-name>ClientSkill_Log4j</display-name>
    
            <welcome-file-list>
    
              <welcome-file>index.html</welcome-file>
    
              <welcome-file>index.htm</welcome-file>
    
              <welcome-file>index.jsp</welcome-file>
    
              <welcome-file>default.html</welcome-file>
    
              <welcome-file>default.htm</welcome-file>
    
              <welcome-file>default.jsp</welcome-file>
    
            </welcome-file-list>
    
           
    
            <servlet>
    
              <description>Description</description>
    
              <display-name>Display name</display-name>
             
    
              <servlet-name>ClientSkillServlet</servlet-name>
    
              <servlet-class>HTML_Generator</servlet-class>
    
             
    
              <init-param>
    
                  <param-name>log4j.properties</param-name>
    
                  <param-value>WEB-INF/log4j.properties</param-value>
    
              </init-param>
    
            </servlet>
    
           
    
            <servlet-mapping>
    
              <servlet-name>ClientSkillServlet</servlet-name>
    
              <url-pattern>/</url-pattern>
    
            </servlet-mapping>
    </web-app>


    My log4j.propertie s file:-
    Code:
          # Configures Log4j as the Tomcat system logger
          #
          #
          # Configure the logger to output info level messages into a log file.
          #
          log4j.rootLogger=INFO, R
          #
          # To continue using the "catalina.out" file (which grows forever),
          # comment out the above line and uncomment the next.
          #
          log4j.rootLogger=ERROR, A1
          #
          # Configuration for standard output ("catalina.out").
          #
          log4j.appender.A1=org.apache.log4j.ConsoleAppender 
          log4j.appender.A1.layout=org.apache.log4j.PatternL  ayout
          #
          # Print the date in ISO 8601 format
          #
          log4j.appender.A1.layout.ConversionPattern=%d [%t] %-5p %c - %m%n
          #
          # Configuration for a rolling log file ("tomcat.log").
          #
          log4j.appender.R=org.apache.log4j.FileAppender
          # Edit the next line to point to your logs directory.
          # The last part of the name is the log file name.
          #
          log4j.appender.R.File=D:\DATA\tomcat.log
          log4j.appender.R.layout=org.apache.log4j.PatternLa  yout
          #
          # Print the date in ISO 8601 format
          #
          log4j.appender.R.layout.ConversionPattern=%d [%t] %-5p %c - %m%n
          # Application logging options
          #
          #log4j.logger.org.apache=DEBUG
          #log4j.logger.org.apache=INFO
          #log4j.logger.org.apache.struts=DEBUG
          #log4j.logger.org.apache.struts=INFO

    and My servlet code is:
    Code:
          import java.sql.*;
          import java.io.*;
          import javax.servlet.*;
          import javax.servlet.http.*;
          import org.apache.log4j.*;
    
          public class HTML_Generator extends HttpServlet
    
          {
              private static Logger logger =Logger.getLogger(HTML_Generator.class);
              public void init() throws ServletException
    
              {
    
                  // Put your code here
    
                  String prefix = getServletContext().getRealPath("/");
    
                  String file = getInitParameter("log4j.properties");
    
                  if(file != null)
    
                  {
    
                      PropertyConfigurator.configure(prefix+file);
                  }
    
              }
    
              public void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException
    
              {
    
                      PrintWriter pw = resp.getWriter();
    
                      Connection conn = null;
    
                      ResultSet rs = null;
    
                      Statement stmt = null;
    
                      pw.println("Check your web server console...");
    
                      System.out.println("Insde doPost()");
    
                      pw.flush();
    
                      pw.close();
    
                      try
    
                      {
    
                          Class.forName("<driver name>");
    
                          conn = DriverManager.getConnection("<url>","<username>","<password>");
    
                          stmt = conn.createStatement();
    
                          rs = stmt.executeQuery("<my query>" );
    
                          int numColumns = rs.getMetaData().getColumnCount();
    
                          int i=0;
    
                          pw.println("<form name=\"Form2\" method=\"POST\" action=\"http://localhost/servlet/<target-servlet(running fine)>\">");
    
                          while (rs.next())
    
                          {
    
                              for (i = 1 ; i < numColumns ; i++ )
    
                                  {
    
                                      <my action>
    
                                  }
    
                          }
    
                         
    
                      }
    
                      catch(SQLException sqle)
    
                      {
    
                          sqle.printStackTrace();
    
                      }
    
                      catch(Exception exc)
    
                      {
    
                          exc.printStackTrace();
    
                      }
    
                      try
    
                      {
    
                          rs.close();
    
                          stmt.close();
    
                          conn.close();
    
                      }catch(SQLException sqle){
    
                          sqle.printStackTrace();
    
                      }catch(Exception exc){
    
                          exc.printStackTrace();
    
                      }
    
              }
    
          }

    Thanks in advance,
    Kedar
  • Dököll
    Recognized Expert Top Contributor
    • Nov 2006
    • 2379

    #2
    Greetings!

    I fetched below and thought it could be of use:

    Using the Log4J



    Let us know if it worked:-)
    Last edited by Dököll; Dec 8 '08, 05:26 AM. Reason: modified link

    Comment

    Working...