Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
   * Copyright 1999-2005 The Apache Software Foundation.
   * Licensed 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
  * 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.log4j.jdbc;

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 getLogStatement(org.apache.log4j.spi.LoggingEvent) 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.

Kevin Steppe (
 public class JDBCAppender extends org.apache.log4j.AppenderSkeleton
     implements org.apache.log4j.Appender {

URL of the DB for default connection handling
   protected String databaseURL = "jdbc:odbc:myDB";

User to connect as for default connection handling
   protected String databaseUser = "me";

User to use for default connection handling
   protected String databasePassword = "mypassword";

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 Connection connection = null;

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 String sqlStatement = "";

size of LoggingEvent buffer before writting to the database. Default is 1.
  protected int bufferSize = 1;

ArrayList holding the buffer of Logging Events.
  protected ArrayList buffer;

Helper object for clearing out the buffer
  protected ArrayList removes;
  public JDBCAppender() {
     = new ArrayList();
     = new ArrayList();

Adds the event to the buffer. When full the buffer is flushed.
  public void append(LoggingEvent event) {
    if (.size() >= )

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.
  protected String getLogStatement(LoggingEvent event) {
    return getLayout().format(event);

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.
  protected void execute(String sqlthrows SQLException {
    Connection con = null;
    Statement stmt = null;
    try {
        con = getConnection();
        stmt = con.createStatement();
    } catch (SQLException e) {
       if (stmt != null)
       throw e;
    //System.out.println("Execute: " + sql);

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 void closeConnection(Connection con) {

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.
  protected Connection getConnection() throws SQLException {
      if (!DriverManager.getDrivers().hasMoreElements())
      if ( == null) {
         = DriverManager.getConnection(,
      return ;

Closes the appender, flushing the buffer first then closing the default connection if it is open.
  public void close()
    try {
      if ( != null && !.isClosed())
    } catch (SQLException e) {
        .error("Error closing connection"e.);
    this. = true;

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!
  public void flushBuffer() {
    //Do the actual logging
    for (Iterator i = .iterator(); i.hasNext();) {
      try {
        LoggingEvent logEvent = (LoggingEvent);
	    String sql = getLogStatement(logEvent);
      catch (SQLException e) {
	    .error("Failed to excute sql"e,
    // remove from the buffer any events that were reported
    // clear the buffer of reported events

closes the appender before disposal
  public void finalize() {

JDBCAppender requires a layout.
  public boolean requiresLayout() {
    return true;

  public void setSql(String s) {
     = s;
    if (getLayout() == null) {
        this.setLayout(new PatternLayout(s));
    else {

Returns pre-formated statement eg: insert into LogTable (msg) values ("%m")
  public String getSql() {
    return ;
  public void setUser(String user) {
     = user;
  public void setURL(String url) {
     = url;
  public void setPassword(String password) {
     = password;
  public void setBufferSize(int newBufferSize) {
     = newBufferSize;
  public String getUser() {
    return ;
  public String getURL() {
    return ;
  public String getPassword() {
    return ;
  public int getBufferSize() {
    return ;

Ensures that the given driver class has been loaded for sql connection creation.
  public void setDriver(String driverClass) {
    try {
    } catch (Exception e) {
      .error("Failed to load driver"e,
New to GrepCode? Check out our FAQ X