You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@tomcat.apache.org by cr...@locus.apache.org on 2000/01/30 03:32:52 UTC

cvs commit: jakarta-tomcat/proposals/catalina/src/share/org/apache/tomcat/valves AccessLogValve.java Constants.java LocalStrings.properties

craigmcc    00/01/29 18:32:52

  Added:       proposals/catalina/src/share/org/apache/tomcat/valves
                        AccessLogValve.java Constants.java
                        LocalStrings.properties
  Log:
  Initial check-in of a Valve that implements web-server-like access logging.
  This Valve supports a configurable pattern string for defining the format
  of each logged message, similar to (but currently simpler than) the syntax
  supported by Apache's "mod_log_config" module.  In addition, this component
  supports automatic rollover to new log files when the date changes.
  
  This Valve is useful in stand-alone deployments of Tomcat, where you want
  a traditional access log (for example, because you want to run hit count
  analysis software against it).  In an Apache-connected deployment, you
  would simply use Apache's log files, because they already include accesses
  for servlet-processed requests.
  
  Revision  Changes    Path
  1.1                  jakarta-tomcat/proposals/catalina/src/share/org/apache/tomcat/valves/AccessLogValve.java
  
  Index: AccessLogValve.java
  ===================================================================
  /*
   * ====================================================================
   *
   * The Apache Software License, Version 1.1
   *
   * Copyright (c) 1999 The Apache Software Foundation.  All rights 
   * reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions
   * are met:
   *
   * 1. Redistributions of source code must retain the above copyright
   *    notice, this list of conditions and the following disclaimer. 
   *
   * 2. Redistributions in binary form must reproduce the above copyright
   *    notice, this list of conditions and the following disclaimer in
   *    the documentation and/or other materials provided with the
   *    distribution.
   *
   * 3. The end-user documentation included with the redistribution, if
   *    any, must include the following acknowlegement:  
   *       "This product includes software developed by the 
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowlegement may appear in the software itself,
   *    if and wherever such third-party acknowlegements normally appear.
   *
   * 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
   *    Foundation" must not be used to endorse or promote products derived
   *    from this software without prior written permission. For written 
   *    permission, please contact apache@apache.org.
   *
   * 5. Products derived from this software may not be called "Apache"
   *    nor may "Apache" appear in their names without prior written
   *    permission of the Apache Group.
   *
   * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
   * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
   * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
   * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
   * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   * SUCH DAMAGE.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   *
   * [Additional notices, if required by prior licensing conditions]
   *
   */ 
  
  
  package org.apache.tomcat.valves;
  
  
  import java.io.File;
  import java.io.FileWriter;
  import java.io.IOException;
  import java.io.PrintWriter;
  import java.sql.Timestamp;
  import javax.servlet.ServletException;
  import org.apache.tomcat.Lifecycle;
  import org.apache.tomcat.LifecycleException;
  import org.apache.tomcat.Request;
  import org.apache.tomcat.Response;
  import org.apache.tomcat.core.ValveBase;
  import org.apache.tomcat.util.StringManager;
  
  
  /**
   * Implementation of the <b>Valve</b> interface that generates a web server
   * access log with the detailed line contents matching a configurable pattern.
   * The syntax of the available patterns is similar to that supported by the
   * Apache <code>mod_log_config</code> module.  As an additional feature,
   * automatic rollover of log files when the date changes is also supported.
   * <p>
   * Patterns for the logged message may include constant text or any of the
   * following replacement strings, for which the corresponding information
   * from the specified Response is substituted:
   * <ul>
   * <li><b>%a</b> - Remote IP address
   * <li><b>%A</b> - Local IP address
   * <li><b>%b</b> - Bytes sent, excluding HTTP headers, or '-' if no bytes
   *     were sent
   * <li><b>%B</b> - Bytes sent, excluding HTTP headers
   * <li><b>%h</b> - Remote host name
   * <li><b>%H</b> - Request protocol
   * <li><b>%l</b> - Remote logical username from identd (always returns '-')
   * <li><b>%m</b> - Request method
   * <li><b>%p</b> - Local port
   * <li><b>%q</b> - Query string (prepended with a '?' if it exists, otherwise
   *     an empty string
   * <li><b>%r</b> - First line of the request
   * <li><b>%s</b> - HTTP status code of the response
   * <li><b>%t</b> - Date and time, in Common Log Format format
   * <li><b>%u</b> - Remote user that was authenticated
   * <li><b>%U</b> - Requested URL path
   * <li><b>%v</b> - Local server name
   * </ul>
   * In addition, the caller can specify one of the following aliases for
   * commonly utilized patterns:
   * <ul>
   * <li><b>common</b> - <code>%h %l %u %t "%r" %s %b</code>
   * </ul>
   *
   * <b>FIXME</b> - Improve the parsing so that things like <code>%{xxx}i</code>
   * can be implemented.
   *
   * @author Craig R. McClanahan
   * @version $Revision: 1.1 $ $Date: 2000/01/30 02:32:52 $
   */
  
  public final class AccessLogValve
      extends ValveBase
      implements Lifecycle {
  
  
      // ----------------------------------------------------------- Constructors
  
  
      /**
       * Construct a new instance of this class with default property values.
       */
      public AccessLogValve() {
  
  	super();
  	setPattern("common");
  
      }
  
  
      // ----------------------------------------------------- Instance Variables
  
  
      /**
       * The as-of date for the currently open log file, or a zero-length
       * string if there is no open log file.
       */
      private String date = "";
  
  
      /**
       * The directory in which log files are created.
       */
      private String directory = "./LOG";
  
  
      /**
       * The descriptive information about this implementation.
       */
      protected static final String info =
  	"org.apache.tomcat.valves.AccessLogValve/1.0";
  
  
      /**
       * The set of month abbreviations for log messages.
       */
      protected static final String months[] =
      { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
        "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  
  
      /**
       * The pattern used to format our access log lines.
       */
      private String pattern = null;
  
  
      /**
       * The prefix that is added to log file filenames.
       */
      private String prefix = "access_log.";
  
  
      /**
       * The string manager for this package.
       */
      private StringManager sm =
  	StringManager.getManager(Constants.Package);
  
  
      /**
       * Has this component been started yet?
       */
      private boolean started = false;
  
  
      /**
       * The suffix that is added to log file filenames.
       */
      private String suffix = "";
  
  
      /**
       * The PrintWriter to which we are currently logging, if any.
       */
      private PrintWriter writer = null;
  
  
      // ------------------------------------------------------------- Properties
  
  
      /**
       * Return the directory in which we create log files.
       */
      public String getDirectory() {
  
  	return (directory);
  
      }
  
  
      /**
       * Set the directory in which we create log files.
       *
       * @param directory The new log file directory
       */
      public void setDirectory(String directory) {
  
  	this.directory = directory;
  
      }
  
  
      /**
       * Return descriptive information about this implementation.
       */
      public String getInfo() {
  
  	return (this.info);
  
      }
  
  
      /**
       * Return the format pattern.
       */
      public String getPattern() {
  
  	return (this.pattern);
  
      }
  
  
      /**
       * Set the format pattern, first translating any recognized alias.
       *
       * @param pattern The new pattern
       */
      public void setPattern(String pattern) {
  
  	if (pattern == null)
  	    pattern = "";
  	if (pattern.equals(Constants.AccessLog.COMMON_ALIAS))
  	    pattern = Constants.AccessLog.COMMON_PATTERN;
  	this.pattern = pattern;
  
      }
  
  
      /**
       * Return the log file prefix.
       */
      public String getPrefix() {
  
  	return (prefix);
  
      }
  
  
      /**
       * Set the log file prefix.
       *
       * @param prefix The new log file prefix
       */
      public void setPrefix(String prefix) {
  
  	this.prefix = prefix;
  
      }
  
  
      /**
       * Return the log file suffix.
       */
      public String getSuffix() {
  
  	return (suffix);
  
      }
  
  
      /**
       * Set the log file suffix.
       *
       * @param suffix The new log file suffix
       */
      public void setSuffix(String suffix) {
  
  	this.suffix = suffix;
  
      }
  
  
      // --------------------------------------------------------- Public Methods
  
  
      /**
       * Log a message summarizing the specified request and response, according
       * to the format specified by the <code>pattern</code> property.
       *
       * @param request Request being processed
       * @param response Response being processed
       *
       * @exception IOException if an input/output error has occurred
       * @exception ServletException if a servlet error has occurred
       */
      public void invoke(Request request, Response response)
  	throws IOException, ServletException {
  
  	// Pass this request on to the next valve in our pipeline
  	if (getNext() != null)
  	    getNext().invoke(request, response);
  	else
  	    throw new IllegalStateException
  		(sm.getString("accessLogValve.noNext"));
  
  	// Generate a message based on the defined pattern
  	StringBuffer result = new StringBuffer();
  	boolean replace = false;
  	for (int i = 0; i < pattern.length(); i++) {
  	    char ch = pattern.charAt(i);
  	    if (replace) {
  		result.append(replace(ch, request, response));
  		replace = false;
  	    } else if (ch == '%')
  		replace = true;
  	    else
  		result.append(ch);
  	}
  	log(result.toString());
  
      }
  
  
      // -------------------------------------------------------- Private Methods
  
  
      /**
       * Close the currently open log file (if any)
       */
      private void close() {
  
  	if (writer == null)
  	    return;
  	writer.flush();
  	writer.close();
  	writer = null;
  	date = "";
  
      }
  
  
      /**
       * Log the specified message to the log file, switching files if the date
       * has changed since the previous log call.
       *
       * @param message Message to be logged
       */
      public void log(String message) {
  
  	// Check for a change of date
  	Timestamp ts = new Timestamp(System.currentTimeMillis());
  	String tsString = ts.toString().substring(0, 19);
  	String tsDate = tsString.substring(0, 10);
  
  	// If the date has changed, switch log files
  	if (!date.equals(tsDate)) {
  	    synchronized (this) {
  		close();
  		date = tsDate;
  		open();
  	    }
  	}
  
  	// Log this message
  	if (writer != null) {
  	    writer.println(message);
  	}
  
      }
  
  
      /**
       * Return the month abbreviation for the specified month, which must
       * be a two-digit String.
       *
       * @param month Month number ("01" .. "12").
       */
      private String lookup(String month) {
  
  	int index;
  	try {
  	    index = Integer.parseInt(month) - 1;
  	} catch (Throwable t) {
  	    index = 0;	// Can not happen, in theory
  	}
  	return (months[index]);
  
      }
  
  
      /**
       * Open the new log file for the date specified by <code>date</code>.
       */
      private void open() {
  
  	// Create the directory if necessary
  	File dir = new File(directory);
  	dir.mkdirs();
  
  	// Open the current log file
  	try {
  	    String pathname = directory +
  		System.getProperty("file.separator") +
  		prefix + date + suffix;
  	    writer = new PrintWriter(new FileWriter(pathname, true), true);
  	} catch (IOException e) {
  	    writer = null;
  	}
  
      }
  
  
      /**
       * Return the replacement text for the specified pattern character.
       *
       * @param pattern Pattern character identifying the desired text
       * @param request Request being processed
       * @param response Response being processed
       */
      private String replace(char pattern, Request request, Response response) {
  
  	String value = null;
  
  	if (pattern == 'a') {
  	    value = request.getRequest().getRemoteAddr();
  	} else if (pattern == 'A') {
  	    value = "127.0.0.1";	// FIXME
  	} else if (pattern == 'b') {
  	    int length = response.getContentLength();
  	    if (length <= 0)
  		value = "-";
  	    else
  		value = "" + length;
  	} else if (pattern == 'B') {
  	    value = "" + response.getContentLength();
  	} else if (pattern == 'h') {
  	    value = request.getRequest().getRemoteHost();
  	} else if (pattern == 'H') {
  	    value = request.getRequest().getProtocol();
  	} else if (pattern == 'l') {
  	    value = "-";
  	} else if (pattern == 'm') {
  	    value = request.getRequest().getMethod();
  	} else if (pattern == 'p') {
  	    value = "" + request.getRequest().getServerPort();
  	} else if (pattern == 'q') {
  	    String query = request.getRequest().getQueryString();
  	    if (query != null)
  		value = "?" + query;
  	    else
  		value = "";
  	} else if (pattern == 'r') {
  	    value = request.getRequest().getMethod() + " " +
  		request.getRequest().getRequestURI() + " " +
  		request.getRequest().getProtocol();
  	} else if (pattern == 's') {
  	    value = "" + response.getStatus();
  	} else if (pattern == 't') {
  	    String timestamp =
  		new Timestamp(System.currentTimeMillis()).toString();
  	    StringBuffer temp = new StringBuffer("[");
  	    temp.append(timestamp.substring(8, 2));		// Day
  	    temp.append('/');
  	    temp.append(lookup(timestamp.substring(5, 2)));	// Month
  	    temp.append('/');
  	    temp.append(timestamp.substring(0, 4));		// Year
  	    temp.append(':');
  	    temp.append(timestamp.substring(11, 8));		// Time
  	    temp.append(' ');
  	    temp.append("-0800");				// FIXME!!!
  	    temp.append(']');
  	    value = temp.toString();
  	} else if (pattern == 'u') {
  	    value = request.getRequest().getRemoteUser();
  	} else if (pattern == 'U') {
  	    value = request.getRequest().getRequestURI();
  	} else if (pattern == 'v') {
  	    value = request.getRequest().getServerName();
  	} else {
  	    value = "???" + pattern + "???";
  	}
  
  	if (value == null)
  	    return ("");
  	else
  	    return (value);
  
      }
  
  
      // ------------------------------------------------------ Lifecycle Methods
  
  
      /**
       * Prepare for the beginning of active use of the public methods of this
       * component.  This method should be called after <code>configure()</code>,
       * and before any of the public methods of the component are utilized.
       *
       * @exception IllegalStateException if this component has already been
       *  started
       * @exception LifecycleException if this component detects a fatal error
       *  that prevents this component from being used
       */
      public void start() throws LifecycleException {
  
  	// Validate and update our current component state
  	if (started)
  	    throw new LifecycleException
  		(sm.getString("accessLogValve.alreadyStarted"));
  	started = true;
  
      }
  
  
      /**
       * Gracefully terminate the active use of the public methods of this
       * component.  This method should be the last one called on a given
       * instance of this component.
       *
       * @exception IllegalStateException if this component has not been started
       * @exception LifecycleException if this component detects a fatal error
       *  that needs to be reported
       */
      public void stop() throws LifecycleException {
  
  	// Validate and update our current component state
  	if (!started)
  	    throw new LifecycleException
  		(sm.getString("accessLogValve.notStarted"));
  	started = false;
  
  	close();
  
      }
  
  
  }
  
  
  
  1.1                  jakarta-tomcat/proposals/catalina/src/share/org/apache/tomcat/valves/Constants.java
  
  Index: Constants.java
  ===================================================================
  /*
   * ====================================================================
   *
   * The Apache Software License, Version 1.1
   *
   * Copyright (c) 1999 The Apache Software Foundation.  All rights 
   * reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions
   * are met:
   *
   * 1. Redistributions of source code must retain the above copyright
   *    notice, this list of conditions and the following disclaimer. 
   *
   * 2. Redistributions in binary form must reproduce the above copyright
   *    notice, this list of conditions and the following disclaimer in
   *    the documentation and/or other materials provided with the
   *    distribution.
   *
   * 3. The end-user documentation included with the redistribution, if
   *    any, must include the following acknowlegement:  
   *       "This product includes software developed by the 
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowlegement may appear in the software itself,
   *    if and wherever such third-party acknowlegements normally appear.
   *
   * 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
   *    Foundation" must not be used to endorse or promote products derived
   *    from this software without prior written permission. For written 
   *    permission, please contact apache@apache.org.
   *
   * 5. Products derived from this software may not be called "Apache"
   *    nor may "Apache" appear in their names without prior written
   *    permission of the Apache Group.
   *
   * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
   * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
   * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
   * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
   * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   * SUCH DAMAGE.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   *
   * [Additional notices, if required by prior licensing conditions]
   *
   */ 
  
  
  package org.apache.tomcat.valves;
  
  
  /**
   * Manifest constants for the <code>org.apache.tomcat.valves</code>
   * package.
   *
   * @author Craig R. McClanahan
   */
  
  public final class Constants {
  
      public static final String Package = "org.apache.tomcat.valves";
  
      // Constants for the AccessLogValve class
      public static final class AccessLog {
  	public static final String COMMON_ALIAS = "common";
  	public static final String COMMON_PATTERN = "%h %l %u %t \"%r\" %s %b";
      }
  
  }
  
  
  
  1.1                  jakarta-tomcat/proposals/catalina/src/share/org/apache/tomcat/valves/LocalStrings.properties
  
  Index: LocalStrings.properties
  ===================================================================
  accessLogValve.alreadyStarted=Access Logger has already been started
  accessLogValve.noNext=Configuration error:  No 'next' valve configured
  accessLogValve.notStarted=Access Logger has not yet been started