Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Licensed to the Apache Software Foundation (ASF) under one or more
   * contributor license agreements.  See the NOTICE file distributed with
   * this work for additional information regarding copyright ownership.
   * The ASF licenses this file to You under the Apache License, Version 2.0
   * (the "License"); you may not use this file except in compliance with
   * the License.  You may obtain a copy of the License at
   * 
   *      http://www.apache.org/licenses/LICENSE-2.0
  * 
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 
 package org.apache.catalina.valves;
 
 
 import static org.jboss.web.CatalinaMessages.MESSAGES;
 
 
 

This Tomcat extension logs server access directly to a database, and can be used instead of the regular file-based access log implemented in AccessLogValve. To use, copy into the server/classes directory of the Tomcat installation and configure in server.xml as:

      <Valve className="org.apache.catalina.valves.JDBCAccessLogValve"
          driverName="your_jdbc_driver"
          connectionURL="your_jdbc_url"
          pattern="combined" resolveHosts="false"
      />
 

Many parameters can be configured, such as the database connection (with driverName and connectionURL), the table name (tableName) and the field names (corresponding to the get/set method names). The same options as AccessLogValve are supported, such as resolveHosts and pattern ("common" or "combined" only).

When Tomcat is started, a database connection (with autoReconnect option) is created and used for all the log activity. When Tomcat is shutdown, the database connection is closed. This logger can be used at the level of the Engine context (being shared by all the defined hosts) or the Host context (one instance of the logger per host, possibly using different databases).

The database table can be created with the following command:

 CREATE TABLE access (
 id INT UNSIGNED AUTO_INCREMENT NOT NULL,
 remoteHost CHAR(15) NOT NULL,
 userName CHAR(15),
 timestamp TIMESTAMP NOT NULL,
 virtualHost VARCHAR(64) NOT NULL,
 method VARCHAR(8) NOT NULL,
 query VARCHAR(255) NOT NULL,
 status SMALLINT UNSIGNED NOT NULL,
 bytes INT UNSIGNED NOT NULL,
 referer VARCHAR(128),
 userAgent VARCHAR(128),
 PRIMARY KEY (id),
 INDEX (timestamp),
 INDEX (remoteHost),
 INDEX (virtualHost),
 INDEX (query),
 INDEX (userAgent)
 );
 

Set JDBCAccessLogValve attribute useLongContentLength="true" as you have more then 4GB outputs. Please, use long SQL datatype at access.bytes attribute. The datatype of bytes at oracle is number and other databases use bytes BIGINT NOT NULL.

If the table is created as above, its name and the field names don't need to be defined.

If the request method is "common", only these fields are used: remoteHost, user, timeStamp, query, status, bytes

TO DO: provide option for excluding logging of certain MIME types.

Author(s):
Andre de Jesus
Peter Rossbach
public final class JDBCAccessLogValve 
    extends ValveBase 
    implements Lifecycle {
    // ----------------------------------------------------------- Constructors


    
Class constructor. Initializes the fields with the default values. The defaults are:
      driverName = null;
      connectionURL = null;
      tableName = "access";
      remoteHostField = "remoteHost";
      userField = "userName";
      timestampField = "timestamp";
      virtualHostField = "virtualHost";
      methodField = "method";
      queryField = "query";
      statusField = "status";
      bytesField = "bytes";
      refererField = "referer";
      userAgentField = "userAgent";
      pattern = "common";
      resolveHosts = false;
 
    public JDBCAccessLogValve() {
        super();
         = null;
         = null;
         = "access";
         = "remoteHost";
         = "userName";
         = "timestamp";
         = "virtualHost";
         = "method";
         = "query";
         = "status";
         = "bytes";
         = "referer";
         = "userAgent";
         = "common";
         = false;
         = null;
         = null;
         = new java.util.Date().getTime();
    }
    // ----------------------------------------------------- Instance Variables

   
Use long contentLength as you have more 4 GB output.

Since:
6.0.15
    protected boolean useLongContentLength = false ;
    
   
The connection username to use when trying to connect to the database.
    protected String connectionName = null;


    
The connection URL to use when trying to connect to the database.
    protected String connectionPassword = null;

   
Instance of the JDBC Driver class we use as a connection factory.
    protected Driver driver = null;
    private String driverName;
    private String connectionURL;
    private String tableName;
    private String remoteHostField;
    private String userField;
    private String timestampField;
    private String virtualHostField;
    private String methodField;
    private String queryField;
    private String statusField;
    private String bytesField;
    private String refererField;
    private String userAgentField;
    private String pattern;
    private boolean resolveHosts;
    private Connection conn;
    private PreparedStatement ps;
    private long currentTimeMillis;


    
The descriptive information about this implementation.
    protected static String info = 
        "org.apache.catalina.valves.JDBCAccessLogValve/1.1";


    
The lifecycle event support for this component.
    protected LifecycleSupport lifecycle = new LifecycleSupport(this);


    
Has this component been started yet?
    private boolean started = false;
    // ------------------------------------------------------------- Properties
 
    
Return the username to use to connect to the database.
    public String getConnectionName() {
        return ;
    }

    
Set the username to use to connect to the database.

Parameters:
connectionName Username
    public void setConnectionName(String connectionName) {
        this. = connectionName;
    }

    
Sets the database driver name.

Parameters:
driverName The complete name of the database driver class.
    public void setDriverName(String driverName) {
        this. = driverName;
    }

   
Return the password to use to connect to the database.
    public String getConnectionPassword() {
        return ;
    }

    
Set the password to use to connect to the database.

Parameters:
connectionPassword User password
    public void setConnectionPassword(String connectionPassword) {
        this. = connectionPassword;
    }

    
Sets the JDBC URL for the database where the log is stored.

Parameters:
connectionURL The JDBC URL of the database.
    public void setConnectionURL(String connectionURL) {
        this. = connectionURL;
    }


    
Sets the name of the table where the logs are stored.

Parameters:
tableName The name of the table.
    public void setTableName(String tableName) {
        this. = tableName;
    }


    
Sets the name of the field containing the remote host.

Parameters:
remoteHostField The name of the remote host field.
    public void setRemoteHostField(String remoteHostField) {
        this. = remoteHostField;
    }


    
Sets the name of the field containing the remote user name.

Parameters:
userField The name of the remote user field.
    public void setUserField(String userField) {
        this. = userField;
    }


    
Sets the name of the field containing the server-determined timestamp.

Parameters:
timestampField The name of the server-determined timestamp field.
    public void setTimestampField(String timestampField) {
        this. = timestampField;
    }


    
Sets the name of the field containing the virtual host information (this is in fact the server name).

Parameters:
virtualHostField The name of the virtual host field.
    public void setVirtualHostField(String virtualHostField) {
        this. = virtualHostField;
    }


    
Sets the name of the field containing the HTTP request method.

Parameters:
methodField The name of the HTTP request method field.
    public void setMethodField(String methodField) {
        this. = methodField;
    }


    
Sets the name of the field containing the URL part of the HTTP query.

Parameters:
queryField The name of the field containing the URL part of the HTTP query.
    public void setQueryField(String queryField) {
        this. = queryField;
    }


  
Sets the name of the field containing the HTTP response status code.

Parameters:
statusField The name of the HTTP response status code field.
  
    public void setStatusField(String statusField) {
        this. = statusField;
    }


    
Sets the name of the field containing the number of bytes returned.

Parameters:
bytesField The name of the returned bytes field.
    public void setBytesField(String bytesField) {
        this. = bytesField;
    }


    
Sets the name of the field containing the referer.

Parameters:
refererField The referer field name.
    public void setRefererField(String refererField) {
        this. = refererField;
    }


    
Sets the name of the field containing the user agent.

Parameters:
userAgentField The name of the user agent field.
    public void setUserAgentField(String userAgentField) {
        this. = userAgentField;
    }


    
Sets the logging pattern. The patterns supported correspond to the file-based "common" and "combined". These are translated into the use of tables containing either set of fields.

TO DO: more flexible field choices.

Parameters:
pattern The name of the logging pattern.
    public void setPattern(String pattern) {
        this. = pattern;
    }


    
Determines whether IP host name resolution is done.

Parameters:
resolveHosts "true" or "false", if host IP resolution is desired or not.
    public void setResolveHosts(String resolveHosts) {
        this. = new Boolean(resolveHosts).booleanValue();
    }

    
get useLongContentLength
    public  boolean getUseLongContentLength() {
        return this. ;
    }
    
    

Parameters:
useLongContentLength the useLongContentLength to set
    public void setUseLongContentLength(boolean useLongContentLength) {
        this. = useLongContentLength;
    }
    // --------------------------------------------------------- Public Methods


    
This method is invoked by Tomcat on each query.

Parameters:
request The Request object.
response The Response object.
Throws:
java.io.IOException Should not be thrown.
javax.servlet.ServletException Database SQLException is wrapped in a ServletException.
    
    public void invoke(Request requestResponse response
        throws IOExceptionServletException {
        final String EMPTY = "" ;
        
        getNext().invoke(requestresponse);
        String remoteHost = EMPTY;
        if()
            remoteHost = request.getRemoteHost();
        else
            remoteHost = request.getRemoteAddr();
        String user = EMPTY;
        if(request != null)
            user = request.getRemoteUser();
        String query="";
        if(request != null)
            query = request.getRequestURI();
        
        long bytes = response.getContentCountLong() ;
        if(bytes < 0)
            bytes = 0;
        int status = response.getStatus();
        String virtualHost = EMPTY;
        String method = EMPTY;
        String referer = EMPTY;
        String userAgent = EMPTY;
        if (.equals("combined") && request != null) {
            virtualHost = request.getServerName();
            method = request.getMethod();
            referer = request.getHeader("referer");
            userAgent = request.getHeader("user-agent");
        }
        synchronized (this) {
          int numberOfTries = 2;
          while (numberOfTries>0) {
            try {
                open();
    
                .setString(1, remoteHost);
                .setString(2, user);
                .setTimestamp(3, new Timestamp(getCurrentTimeMillis()));
                .setString(4, query);
                .setInt(5, status);
                
                if() {
                    .setLong(6, bytes);                
                } else {
                    if (bytes > .)
                        bytes = -1 ;
                    .setInt(6, (intbytes);
                }               
                if (.equals("combined")) {
                      .setString(7, virtualHost);
                      .setString(8, method);
                      .setString(9, referer);
                      .setString(10, userAgent);
                }
                .executeUpdate();
                return;
              } catch (SQLException e) {
                // Log the problem for posterity
                  .getLogger().error(.jdbcAccessLogValveInsertError(), e);
                // Close the connection so that it gets reopened next time
                if ( != null)
                    close();
              }
              numberOfTries--;
           }
        }
    }


    
Adds a Lifecycle listener.

Parameters:
listener The listener to add.
  
    public void addLifecycleListener(LifecycleListener listener) {
        .addLifecycleListener(listener);
    }


    
Get the lifecycle listeners associated with this lifecycle. If this Lifecycle has no listeners registered, a zero-length array is returned.
        return .findLifecycleListeners();
    }


    
Removes a Lifecycle listener.

Parameters:
listener The listener to remove.
    public void removeLifecycleListener(LifecycleListener listener) {
        .removeLifecycleListener(listener);
    }

    
Open (if necessary) and return a database connection for use by this AccessLogValve.

Throws:
java.sql.SQLException if a database error occurs
    protected void open() throws SQLException {
        // Do nothing if there is a database connection already open
        if ( != null)
            return ;
        // Instantiate our database driver if necessary
        if ( == null) {
            try {
                Class clazz = Class.forName();
                 = (Driverclazz.newInstance();
            } catch (Throwable e) {
                throw new SQLException(e.getMessage());
            }
        }
        // Open a new connection
        Properties props = new Properties();
        props.put("autoReconnect""true");
        if ( != null)
            props.put("user");
        if ( != null)
            props.put("password");
         = .connect(props);
        .setAutoCommit(true);
        if (.equals("common")) {
                 = .prepareStatement
                    ("INSERT INTO " +  + " (" 
                     +  + ", " +  + ", "
                     +  +", " +  + ", "
                     +  + ", " +  
                     + ") VALUES(?, ?, ?, ?, ?, ?)");
        } else if (.equals("combined")) {
                 = .prepareStatement
                    ("INSERT INTO " +  + " (" 
                     +  + ", " +  + ", "
                     +  + ", " +  + ", " 
                     +  + ", " +  + ", " 
                     +  + ", " +  + ", "
                     +  + ", " + 
                     + ") VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        }
    }

    
Close the specified database connection.
    protected void close() {
        // Do nothing if the database connection is already closed
        if ( == null)
            return;
        // Close our prepared statements (if any)
        try {
            .close();
        } catch (Throwable f) {
            ;
        }
        this. = null;
        // Close this database connection, and log any errors
        try {
            .close();
        } catch (SQLException e) {
            .getLogger().error(.jdbcAccessLogValveConnectionCloseError(), e); // Just log it here            
        } finally {
           this. = null;
        }
    }
    
Invoked by Tomcat on startup. The database connection is set here.

Throws:
org.apache.catalina.LifecycleException Can be thrown on lifecycle inconsistencies or on database errors (as a wrapped SQLException).
    public void start() throws LifecycleException {
        if ()
            throw new LifecycleException
                (.valveAlreadyStarted());
         = true;
        try {
            open() ;        
        } catch (SQLException e) {
            throw new LifecycleException(e);
        }
    }


    
Invoked by tomcat on shutdown. The database connection is closed here.

Throws:
org.apache.catalina.LifecycleException Can be thrown on lifecycle inconsistencies or on database errors (as a wrapped SQLException).
    public void stop() throws LifecycleException {
        if (!)
            throw new LifecycleException
                (.valveNotStarted());
        .fireLifecycleEvent(null);
         = false;
        
        close() ;
    }
    public long getCurrentTimeMillis() {
        long systime  =  System.currentTimeMillis();
        if ((systime - ) > 1000) {
              =  new java.util.Date(systime).getTime();
        }
        return ;
    }
New to GrepCode? Check out our FAQ X