FileDocCategorySizeDatePackage
JDBCAppender.javaAPI DocApache log4j 1.2.159450Sat Aug 25 00:09:40 BST 2007org.apache.log4j.jdbc

JDBCAppender

public class JDBCAppender extends AppenderSkeleton implements Appender

WARNING: This version of JDBCAppender is very likely to be completely replaced in the future. Moreoever, it does not log exceptions. The JDBCAppender provides for sending log events to a database.

Each append call adds to an ArrayList buffer. When the buffer is filled each log event is placed in a sql statement (configurable) and executed. BufferSize, db URL, User, & Password are configurable options in the standard log4j ways.

The setSql(String sql) sets the SQL statement to be used for logging -- this statement is sent to a PatternLayout (either created automaticly by the appender or added by the user). Therefore by default all the conversion patterns in PatternLayout can be used inside of the statement. (see the test cases for examples)

Overriding the {@link #getLogStatement} method allows more explicit control of the statement used for logging.

For use as a base class:

  • Override getConnection() to pass any connection you want. Typically this is used to enable application wide connection pooling.
  • Override closeConnection(Connection con) -- if you override getConnection make sure to implement closeConnection to handle the connection you generated. Typically this would return the connection to the pool it came from.
  • Override getLogStatement(LoggingEvent event) to produce specialized or dynamic statements. The default uses the sql option value.
author
Kevin Steppe (ksteppe@pacbell.net)

Fields Summary
protected String
databaseURL
URL of the DB for default connection handling
protected String
databaseUser
User to connect as for default connection handling
protected String
databasePassword
User to use for default connection handling
protected Connection
connection
Connection used by default. The connection is opened the first time it is needed and then held open until the appender is closed (usually at garbage collection). This behavior is best modified by creating a sub-class and overriding the getConnection and closeConnection methods.
protected String
sqlStatement
Stores the string given to the pattern layout for conversion into a SQL statement, eg: insert into LogTable (Thread, Class, Message) values ("%t", "%c", "%m"). Be careful of quotes in your messages! Also see PatternLayout.
protected int
bufferSize
size of LoggingEvent buffer before writting to the database. Default is 1.
protected ArrayList
buffer
ArrayList holding the buffer of Logging Events.
protected ArrayList
removes
Helper object for clearing out the buffer
Constructors Summary
public JDBCAppender()


    
    super();
    buffer = new ArrayList(bufferSize);
    removes = new ArrayList(bufferSize);
  
Methods Summary
public voidappend(org.apache.log4j.spi.LoggingEvent event)
Adds the event to the buffer. When full the buffer is flushed.

    buffer.add(event);

    if (buffer.size() >= bufferSize)
      flushBuffer();
  
public voidclose()
Closes the appender, flushing the buffer first then closing the default connection if it is open.

    flushBuffer();

    try {
      if (connection != null && !connection.isClosed())
          connection.close();
    } catch (SQLException e) {
        errorHandler.error("Error closing connection", e, ErrorCode.GENERIC_FAILURE);
    }
    this.closed = true;
  
protected voidcloseConnection(java.sql.Connection con)
Override this to return the connection to a pool, or to clean up the resource. The default behavior holds a single connection open until the appender is closed (typically when garbage collected).

  
protected voidexecute(java.lang.String sql)
Override this to provide an alertnate method of getting connections (such as caching). One method to fix this is to open connections at the start of flushBuffer() and close them at the end. I use a connection pool outside of JDBCAppender which is accessed in an override of this method.


    Connection con = null;
    Statement stmt = null;

    try {
        con = getConnection();

        stmt = con.createStatement();
        stmt.executeUpdate(sql);
    } catch (SQLException e) {
       if (stmt != null)
	     stmt.close();
       throw e;
    }
    stmt.close();
    closeConnection(con);

    //System.out.println("Execute: " + sql);
  
public voidfinalize()
closes the appender before disposal

    close();
  
public voidflushBuffer()
loops through the buffer of LoggingEvents, gets a sql string from getLogStatement() and sends it to execute(). Errors are sent to the errorHandler. If a statement fails the LoggingEvent stays in the buffer!

    //Do the actual logging
    removes.ensureCapacity(buffer.size());
    for (Iterator i = buffer.iterator(); i.hasNext();) {
      try {
        LoggingEvent logEvent = (LoggingEvent)i.next();
	    String sql = getLogStatement(logEvent);
	    execute(sql);
        removes.add(logEvent);
      }
      catch (SQLException e) {
	    errorHandler.error("Failed to excute sql", e,
			   ErrorCode.FLUSH_FAILURE);
      }
    }
    
    // remove from the buffer any events that were reported
    buffer.removeAll(removes);
    
    // clear the buffer of reported events
    removes.clear();
  
public intgetBufferSize()

    return bufferSize;
  
protected java.sql.ConnectiongetConnection()
Override this to link with your connection pooling system. By default this creates a single connection which is held open until the object is garbage collected.

      if (!DriverManager.getDrivers().hasMoreElements())
	     setDriver("sun.jdbc.odbc.JdbcOdbcDriver");

      if (connection == null) {
        connection = DriverManager.getConnection(databaseURL, databaseUser,
					databasePassword);
      }

      return connection;
  
protected java.lang.StringgetLogStatement(org.apache.log4j.spi.LoggingEvent event)
By default getLogStatement sends the event to the required Layout object. The layout will format the given pattern into a workable SQL string. Overriding this provides direct access to the LoggingEvent when constructing the logging statement.

    return getLayout().format(event);
  
public java.lang.StringgetPassword()

    return databasePassword;
  
public java.lang.StringgetSql()
Returns pre-formated statement eg: insert into LogTable (msg) values ("%m")

    return sqlStatement;
  
public java.lang.StringgetURL()

    return databaseURL;
  
public java.lang.StringgetUser()

    return databaseUser;
  
public booleanrequiresLayout()
JDBCAppender requires a layout.

    return true;
  
public voidsetBufferSize(int newBufferSize)

    bufferSize = newBufferSize;
    buffer.ensureCapacity(bufferSize);
    removes.ensureCapacity(bufferSize);
  
public voidsetDriver(java.lang.String driverClass)
Ensures that the given driver class has been loaded for sql connection creation.

    try {
      Class.forName(driverClass);
    } catch (Exception e) {
      errorHandler.error("Failed to load driver", e,
			 ErrorCode.GENERIC_FAILURE);
    }
  
public voidsetPassword(java.lang.String password)

    databasePassword = password;
  
public voidsetSql(java.lang.String s)

    sqlStatement = s;
    if (getLayout() == null) {
        this.setLayout(new PatternLayout(s));
    }
    else {
        ((PatternLayout)getLayout()).setConversionPattern(s);
    }
  
public voidsetURL(java.lang.String url)

    databaseURL = url;
  
public voidsetUser(java.lang.String user)

    databaseUser = user;