Servlet Logging : Log « Servlets « Java






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);
      }
    }
  }


}

   
  








Related examples in the same category

1.Servlets Logging Filter Demo
2.Logging Filter
3.Context log
4.Logger without configure file
5.Logger Servlet
6.Another logger servlet
7.Logger new config
8.Servlet: Root logger
9.Session logger
10.LoggerSkel for Servlet
11.Context logger
12.Log Filter
13.Log in ServletContext