package com.javaranch.common ; import java.io.* ; import java.util.* ; import javax.servlet.* ; import javax.servlet.http.* ; import LocalSystem ; /** Used for tracking events in a Servlet.

Log messages are sent to a logging object that defaults to being turned off. Activating the servlet via a web browser gives you access to activate logging for debugging purposes.

Override this class and call logMessage() to add messages to the log.

Override doGet() to disable the error logging feature for production.

Example:

      
 *     public class EchoServlet extends LogServlet
 *     {
 *         
 *         public void doPost( PrintWriter out , CastMap parms )
 *         {
 *             String text = parms.getString( "text" );
 *             if ( usable( text )  )
 *             {
 *                 for ( int i = 0 ; i < 100 ; i++ )
 *                 {
 *                     out.println( text + "<br>" );
 *                 }
 *             }
 *             else
 *             {
 *                 reportProblem( out , "invalid parameters" );
 *             }
 *         }
 *         
 *     }
      
      
    
- - - - - - - - - - - - - - - - -

Copyright (c) 1999-2000 Paul Wheaton

Copyright (c) 1999-2000 EarthWatch, Inc.

You are welcome to do whatever you want to with this source file provided that you maintain this comment fragment (between the dashed lines). Modify it, change the package name, change the class name ... personal or business use ... sell it, share it ... add a copyright for the portions you add ...

My goal in giving this away and maintaining the copyright is to hopefully direct developers back to JavaRanch.

I originally developed this class while working as a contractor at EarthWatch, Inc. in Longmont, Colorado. They gave me permission to distribute this code this way provided that their message would also be carried along. Their message is that they hire Java programmers and would like you to consider working with them. I have to say that my experience with them was first rate and I would encourage engineers to work there. Check out their web site at http://www.digitalglobe.com.

The original source can be found at JavaRanch

- - - - - - - - - - - - - - - - -

@author Paul Wheaton */ public abstract class LogServlet extends HttpServlet { /** increment this if you override the traditional doPost() */ protected int postCount = 0 ; /** increment this if you override the traditional doGet() */ protected int getCount = 0 ; private ErrorLog log ; // during the init cycle, console logging is temporarily turned on. If the user // calls setLogConsole during the init cycle, consoleLock is set to true and console // logging won't be turned off.

private boolean consoleLock = false ; public LogServlet() { log = new ErrorLog(); } /** Messages are logged to memory so they can be viewed by a GET command.

*/ protected void setLogMemory( boolean on ) { log.setInternalLog( on ); } /** Messages are sent to STDOUT so they can be tracked in the servlet server logs.

*/ protected void setLogConsole( boolean on ) { log.setConsole( on ); consoleLock = true ; } /** Call this as the first thing you do if you override the traditional doGet() or doPost().

This makes sure that console logging is turned off if it is no longer desired.

*/ protected void checkConsoleLogging() { if ( ! consoleLock ) { log.setConsole( false ); consoleLock = true ; } } /** Add a message to the log.

*/ public void logMessage( String s ) { s = "(" + getClass().getName() + ") " + s ; log.add( s ); } /** This convenience method sends the message to the log and sends it to out.

*/ protected void reportProblem( PrintWriter out , String message ) { // if "out" were not passed in and were instead kept as an instance variable, this servlet would // not be safely reentrant. logMessage( message ); out.println( message ); } /** Convenience method - returns true if the string is not null and not empty.

*/ protected boolean usable( String s ) { return ( ( s != null ) && ( s.length() > 0 ) ); } /** E-mail a message to the admin and add the same message to the log.

*/ public void emailMessage( String s ) { String from = getClass().getName(); // the name of this servlet try { String mailBody = "This e-mail is automatically generated by the servlet " + from + ".\n\n" + s ; Email.send( LocalSystem.getAdminEmail() , mailBody ); logMessage( "e-mail sent: " + s ); } catch( Exception e ) { logMessage( "Could not e-mail message: " + s ); } } /** E-mail a message to the admin, send it to the user and add it to the log.

*/ public void emailMessage( PrintWriter out , String s ) { out.println( s ); emailMessage( s ); } /** Override this if you have more to say in the GET debug information.

*/ public void debugReport( PrintWriter out ) { } private boolean validAccess( HttpServletRequest req ) { boolean returnVal = false ; String password = req.getParameter( LocalSystem.getLogServletAccessParameterName() ); if ( password != null ) { if ( password.equals( LocalSystem.getLogServletAccessParameterValue() ) ) { returnVal = true ; } } return returnVal ; } // extract all of the parameters from HttpServletRequest so they can be passes seperately. private CastMap getParms( HttpServletRequest req ) { CastMap parms = new CastMap(); Enumeration enum = req.getParameterNames(); while( enum.hasMoreElements() ) { String key = (String)enum.nextElement(); parms.put( key , req.getParameter( key ) ); } return parms ; } /** if you need doPost(), override this instead of the normal doPost().

@param out use this to send HTML to the browser.

@param parameters all of the parameters sent to the servlet are stored in this hash table.

*/ protected void doPost( PrintWriter out , CastMap parameters ) { } public void doPost( HttpServletRequest req , HttpServletResponse resp ) throws ServletException, IOException { checkConsoleLogging(); postCount++ ; resp.setContentType("text/html"); try { PrintWriter out = resp.getWriter(); CastMap parms = getParms( req ); try { doPost( out , parms ); } catch ( Exception e ) { logMessage( "exception encountered in POST: " + e ); } out.close(); } catch( Exception e ) { logMessage( "cannot get writer: " + e ); } } /** if you need doGet, override this instead of the normal doGet.

@param out use this to send HTML to the browser.

@param parameters all of the parameters sent to the servlet are stored in this hash table.

*/ protected void doGet( PrintWriter out , CastMap parameters ) { } /** Override this to make the debugger log unavailable.

*/ public void doGet( HttpServletRequest req , HttpServletResponse resp ) { checkConsoleLogging(); getCount++ ; resp.setContentType("text/html"); try { if ( validAccess( req ) ) { String url = req.getRequestURI(); // some servers strip this info out, so I need to put it back in if ( url.indexOf( "servlet/" ) == -1 ) { Str fix = new Str( url ); fix.insert( "/servlet" , fix.lastIndexOf( '/' ) ); url = fix.toString(); } PrintWriter out = resp.getWriter() ; String parm = req.getParameter("log"); String accessPhrase = "?" + LocalSystem.getLogServletAccessParameterPhrase(); if ( parm == null ) { out.println(""); String name = "status page for " + getClass().getName() ; out.println( "" + name + "" ); out.println( "

" + name + "

" ); out.println( "POST count = " + postCount + "

" ); out.println( "GET count = " + getCount + "

" ); out.print("logging to stdout.log is currently " ); if ( log.isConsoleLogOn() ) { out.println( "on . . . . turn off

" ); } else { out.println( "off . . . . turn on

" ); } out.print("logging to memory buffer is currently "); if ( log.isInternalLogOn() ) { out.println( "on . . . . turn off

" ); String[] s = log.getList(); if ( s == null ) { out.println("no log messages.

"); } else { out.println("log messages:

"); } } else { out.println( "off . . . . turn on

" ); } out.println("


"); debugReport( out ); out.println(""); } else { if ( parm.equals("conon") ) { log.setConsole( true ); out.println("future log entries will now be routed to stdout.log

"); } else if ( parm.equals("conoff") ) { log.setConsole( false ); out.println("further log entries will not be routed to stdout.log

"); } else if ( parm.equals("memon") ) { log.setInternalLog( true ); out.println("future log entries will now be kept in memory

"); } else if ( parm.equals("memoff") ) { log.setInternalLog( false ); out.println("The memory log has been erased and further log entries will not be kept in memory

"); } } out.println( "\n\n

get new servlet data

" ); out.close(); } else { try { PrintWriter out = resp.getWriter(); CastMap parms = getParms( req ); try { doGet( out , parms ); } catch ( Exception e ) { reportProblem( out , "exception encountered in GET: " + e ); } out.close(); } catch( Exception e ) { logMessage( "cannot get writer: " + e ); } } } catch ( Exception e ) { log.add( "LogServlet GET: " + e ); } } public static void unitTest( TestLog log ) { // xxx need tests } }