Java/Servlets/Log

Материал из Java эксперт
Перейти к: навигация, поиск

Another logger servlet

 
//Log4j from Apache is required
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import javax.servlet.*;
import javax.servlet.http.*;
public class LoggerServlet2 extends HttpServlet {
  private Logger log = null;
  public void init() {
    log = Logger.getLogger(LoggerServlet2.class);
  }
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, java.io.IOException {
    //display a DEBUG level message
    log.debug("Sending a DEBUG message from logger2");
    //display an INFO level message
    log.info("Sending an INFO message from logger2");
    //better display something
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    out.println("<html><head><title>Servlet logging</title></head><body>");
    out.println("<h2>Hello from LoggerServlet</h2>");
    out.println("Your logger name is: " + log.getName() + "<br>");
    out.println("Your logger parent is: " + log.getParent().getName()
        + "<br>");
    out.println("</body></html>");
    out.close();
  } //end doGet
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, java.io.IOException {
    doGet(request, response);
  }
}





Context log

 
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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
    //the javax.servlet.GenericServlet.getServletContext method
    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; this is "lazy
    // HTML"
    out.println("<html><head><title>ServletContext logging</title></head><body>");
    out.println("<h2>Messages sent</h2>");
    out.println("</body></html>");
  } //end doGet
}





Context logger

 
//Log4j from Apache is required
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import javax.servlet.*;
import javax.servlet.http.*;
public class ContextLogger implements ServletContextListener {
  private Logger log;
  public ContextLogger() {
  }
  public void contextDestroyed(ServletContextEvent sce) {
    String name = sce.getServletContext().getServletContextName();
    //log request of the INFO level
    log.info("ServletContext shut down: " + (name == null ? "" : name));
  }
  public void contextInitialized(ServletContextEvent sce) {
    ServletContext context = sce.getServletContext();
    String realPath = context.getRealPath("/");
    String fileSep = System.getProperty("file.separator");
    if (realPath != null && (!realPath.endsWith(fileSep)))
      realPath = realPath + fileSep;
    //Initialize logger here:
    PropertyConfigurator.configure(realPath + "WEB-INF/classes/"
        + context.getInitParameter("logger-config"));
    log = Logger.getLogger(ContextLogger.class);
    String name = context.getServletContextName();
    //log request about servlet context being initialized
    log.info("ServletContext ready: " + (name == null ? "" : name));
  }
}





Log Filter

 
//Log4j from Apache is required
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class LogFilter implements Filter {
  private FilterConfig config;
  private Logger log;
  /** Creates new RequestFilter */
  public LogFilter() {
  }
  public void init(FilterConfig filterConfig) throws ServletException {
    this.config = filterConfig;
    //load the configuration for this application"s loggers using the
    // servletLog.properties file
    PropertyConfigurator.configure(config.getServletContext().getRealPath(
        "/")
        + "WEB-INF/classes/servletLog.properties");
    log = Logger.getLogger(LogFilter.class);
    log.info("Logger instantiated in " + getClass().getName());
  }
  public void doFilter(ServletRequest request, ServletResponse response,
      FilterChain chain) throws java.io.IOException, ServletException {
    HttpServletRequest req = null;
    String id = config.getInitParameter("log-id");
    if (id == null)
      id = "unknown";
    if (log != null && (request instanceof HttpServletRequest)) {
      req = (HttpServletRequest) request;
      log.info("Log id:" + id + ": Request received from: "
          + req.getRemoteHost() + " for " + req.getRequestURL());
    }
    chain.doFilter(request, response);
  }// doFilter
  public void destroy() {
    /*
     * called before the Filter instance is removed from service by the web
     * container
     */
    log = null;
  }
}





Logger new config

 
//Log4j from Apache is required
import org.apache.log4j.Logger;
import javax.servlet.*;
import javax.servlet.http.*;
public class LoggerNewConfig extends HttpServlet {
  private Logger log = null;
  public void init() {
    log = Logger.getLogger(LoggerNewConfig.class);
    log.info("LoggerNewConfig started.");
  }
  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 out = response.getWriter();
    out.println("<html><head><title>Servlet logging</title></head><body>");
    out.println
       ("<h2>Hello from a Logger with its own configuration in the log4j.properties file</h2>");
    out.println("Your logger name is: " + log.getName() + "<br>");
    out.println("Your logger parent is: " + log.getParent().getName()
        + "<br>");
    out.println("</body></html>");
    out.close();
  } //end doGet
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, java.io.IOException {
    doGet(request, response);
  }
}





Logger Servlet

 
//Log4j from Apache is required
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import javax.servlet.*;
import javax.servlet.http.*;
public class LoggerServlet extends HttpServlet {
  private Logger log = null;
  public void init() {
    String realPath = getServletContext().getRealPath("/");
    String fileSep = System.getProperty("file.separator");
    if (realPath != null && (!realPath.endsWith(fileSep)))
      realPath = realPath + fileSep;
    System.out.println(realPath);
    //load the configuration for this application"s loggers using the
    // servletLog.properties file
    PropertyConfigurator.configure(realPath
        + "WEB-INF/classes/servletLog.properties");
    //create the logger for this servlet class
    //it will use the configuration for the logger com.jexp.LoggerServlet
    //or inherit from the logger com.jexp if one exists, and so on
    log = Logger.getLogger(LoggerServlet.class);
    log.info("LoggerServlet started.");
  }
  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 something
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    out.println("<html><head><title>Servlet logging</title></head><body>");
    out.println("<h2>Hello from LoggerServlet</h2>");
    out.println("Your logger name is: " + log.getName() + "<br>");
    out.println("Your logger parent is: " + log.getParent().getName()
        + "<br>");
    out.println("</body></html>");
    out.close();
  } //end doGet
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, java.io.IOException {
    doGet(request, response);
  }
}





LoggerSkel for Servlet

 
//Log4j from Apache is required

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import javax.servlet.*;
import javax.servlet.http.*;
public class LoggerSkel extends HttpServlet {
  private Logger log;
  public void init() {
    PropertyConfigurator.configure(getServletContext().getRealPath("/")
        + "WEB-INF/classes/servletLog.properties");
    log = Logger.getLogger(LoggerSkel.class);
    log.debug("Instance created of: " + getClass().getName());
  }
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, java.io.IOException {
    //do logging here if necessary
  } //end doGet
}





Logger without configure file

 
//Log4j from Apache is required
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() {
    log = Logger.getRootLogger();
    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 out = response.getWriter();
    out.println("<html><head><title>Servlet logging</title></head><body>");
    out.println("<h2>Hello from a Logger with no Config file</h2>");
    out.println("Your logger name is: " + log.getName() + "<br>");
    out.println("Your logger parent is: " + log.getParent().getName()
        + "<br>");
    out.println("</body></html>");
  } //end doGet
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, java.io.IOException {
    doGet(request, response);
  }
}





Logging Filter

 
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public final class LoggingFilter implements Filter 
{
  private FilterConfig filterConfig = null;
  public void doFilter(ServletRequest request, ServletResponse response,
    FilterChain chain)
    throws IOException, ServletException 
  {
    long start = System.currentTimeMillis();
    String address =  request.getRemoteAddr();
    String file = ((HttpServletRequest) request).getRequestURI();
        
    chain.doFilter(request, response);
    filterConfig.getServletContext().log(
        "User access! " +      
        " User IP: " + address +      
        " Resource: " + file + 
        " Milliseconds used: " + (System.currentTimeMillis() - start) 
    );
  }
  public void destroy() { }
  public void init(FilterConfig filterConfig) {
    this.filterConfig = filterConfig;
  }
}





Log in ServletContext

 
// web.xml
/*
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.ru/xml/ns/j2ee" 
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
         xsi:schemaLocation="http://java.sun.ru/xml/ns/j2ee
         http://java.sun.ru/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">
  <servlet>
    <servlet-name>LoggingServlet</servlet-name>
    <servlet-class>LoggingServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LoggingServlet</servlet-name>
    <url-pattern>/loggingServlet</url-pattern>
  </servlet-mapping>
</web-app>
*/
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoggingServlet extends HttpServlet {
  private ServletContext context;
  public void init(ServletConfig config) throws ServletException {
    super.init(config);
    context = getServletContext();
    context.log("Init has been invoked");
  }
  public void doGet(HttpServletRequest req, HttpServletResponse res)
      throws IOException {
    ServletOutputStream out = res.getOutputStream();
    context.log("doGet has now been invoked");
    res.setContentType("text/html");
    out.println("<html><head><title>Logging Servlet</title></head>");
    out.println("<body>Visit the <tomcat-home>\\logs and open the xx file to see the log entries");
    out.println("</body></html>");
  }
}





Servlet Logging

 
package net.firstpartners.nounit.utility;
/**
 * Title:        NoUnit - Identify Classes that are not being unit Tested
 *
 * Copyright (C) 2001  Paul Browne , FirstPartners.net
 *
 *
 * This program is free software; you can redistribute it and/or 
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * @author Paul Browne
 * @version 0.6
 */
import java.io.*;
import javax.servlet.*;

/**
 * stores log of system output and system errors
 * If Servlet , writes to Servlet Log File.
 * If non-Servlet , writes to Output Files Specified in parameters.<BR>
 * Class is mainly static , to allow ease of use (one one log file per system!!) ,
 * but has a non-static constructor (for use by servlets - so reference to servlet
 * log file can be set.
 */
public class Logging {
  //Class Level Variables
  static String logFileName;       // both package level to enable testing
  static String errorLogFileName;
  static FileWriter logWriter;
  static FileWriter errorWriter;
  static boolean doLogging=false;   //default no logging unless file says otherwise
  //For use in Servlet Context Logging
  static ServletContext innerContext;

  /**
   * Constructor for Logging from Servlet
   * @param inServletContext used to get access to the Servlet log files
   * @exception IOException if it can"t create log files
   */
   public Logging (ServletContext inServletContext) throws IOException {
    //Store incoming Context + Set Logging Flag
    this.innerContext= inServletContext;
    //Set logging flag
    doLogging=true;
    
  }

  /**
   * do Setup
   * @exception IOException if it can"t create log files
   */
  private static void setup () {
    try {
      //Check if setup required - ie nothing has been setup before
      if (((logFileName==null)&&(errorLogFileName==null))||(innerContext==null))
      {
        //Set logging flag
        
          doLogging=true;
          //Get logging parameters
          logFileName= "LogFile.txt";
          errorLogFileName = "ErrorLogFile.txt";
          //Create the files
          logWriter = new FileWriter(logFileName,true); //append data
          errorWriter = new FileWriter(errorLogFileName,true); //append
        
      }
    } catch (java.io.IOException ie) {
      //do nothing - exists to keep method signature simple
      //will show up as NullPointerException later
    }
  }
  /**
   * Print log of system output
   * @param sysOut
   */
  public static void printOutput(Object sysOut){
    //setup (if required)
    setup();
    //skip out asap if logging is turned off
    if (!doLogging) {return; }

    //Check for Servlet Logging
    if (innerContext!=null) {
      doServletLog(sysOut);
    } else {
      //do file logging
      try {
        if (sysOut instanceof Exception) {
          logWriter.write(((Exception)sysOut).toString());
          logWriter.flush();
        }
        else {
          logWriter.write(sysOut.toString());
          logWriter.flush();
        }
      } catch (java.io.IOException ioe) {
        //do nothing - let app continue
      }
    }
  }
  /**
   * Print log of system errors
   * This method catches java.io.IOExceptions internally , so as to give a
   * similar method signature to System.out.println. Also should we stop system
   * if logging (and only logging) fails?
   * @param sysErr
   */
  public static void printError(Object sysErr){
    //setup (if required)
    setup();
    //skip out asap if logging is turned off
    if (!doLogging) {return; }
    //Check for Servlet Logging
    if (innerContext!=null) {
      doServletLog(sysErr);
    } else {
      //do file logging
      try {
        if (sysErr instanceof Exception) {
          logWriter.write(((Exception)sysErr).toString());
          logWriter.flush();
        }
        else {
          logWriter.write(sysErr.toString());
          logWriter.flush();
        }
      } catch (java.io.IOException ioe) {
        //do nothing - let app continue
      }
    }
  }
  /**
   * private method for handling logging to Servlets
   * @param inObject to Log
   */
  private static void doServletLog (Object inObject) {
    if(inObject instanceof Throwable) {
      //Log as Exception
      innerContext.log("",(Throwable)inObject);
    } else {
      //Log as Normal String
      innerContext.log(inObject.toString());
    }

  }

  /**
   * Prints debug message to system log file.
   * Catches java.io.IOExceptions internally, so as to give a
   * similar method signature to System.out.println.
   *
   * @param object Object containing information to display
   */
  public static void debug(Object object){
    setup();
    if (doLogging) {
      if (innerContext==null) {
        // log debug message to file
        try {
          try {
            logWriter.write(((Exception)object).toString());
          }
          catch (ClassCastException e) {
            logWriter.write(object.toString());
          }
          logWriter.flush();
        } catch (IOException e) {
          //do nothing - let app continue
        }
      } else {
        doServletLog(object);
      }
    }
  }

}





Servlet: Root logger

 
//Log4j from Apache is required
import org.apache.log4j.Logger;
import javax.servlet.*;
import javax.servlet.http.*;
public class LoggerWconfig extends HttpServlet {
  private Logger log = null;
  public void init() {
    log = Logger.getRootLogger();
    log.info("LoggerWconfig started.");
  }
  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 out = response.getWriter();
    out.println("<html><head><title>Servlet logging</title></head><body>");
    out.println("<h2>Hello from a Logger with a log4j.properties file</h2>");
    out.println("Your logger name is: " + log.getName() + "<br>");
    out.println("</body></html>");
  }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, java.io.IOException {
    doGet(request, response);
  }
}





Servlets Logging Filter Demo