2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
17 package org.apache.log4j.jdbc;
19 import java.sql.Connection;
20 import java.sql.DriverManager;
21 import java.sql.SQLException;
22 import java.sql.Statement;
23 import java.util.ArrayList;
24 import java.util.Iterator;
26 import org.apache.log4j.PatternLayout;
27 import org.apache.log4j.spi.ErrorCode;
28 import org.apache.log4j.spi.LoggingEvent;
32 The JDBCAppender provides for sending log events to a database.
34 <p><b><font color="#FF2222">WARNING: This version of JDBCAppender
35 is very likely to be completely replaced in the future. Moreoever,
36 it does not log exceptions</font></b>.
38 <p>Each append call adds to an <code>ArrayList</code> buffer. When
39 the buffer is filled each log event is placed in a sql statement
40 (configurable) and executed.
42 <b>BufferSize</b>, <b>db URL</b>, <b>User</b>, & <b>Password</b> are
43 configurable options in the standard log4j ways.
45 <p>The <code>setSql(String sql)</code> sets the SQL statement to be
46 used for logging -- this statement is sent to a
47 <code>PatternLayout</code> (either created automaticly by the
48 appender or added by the user). Therefore by default all the
49 conversion patterns in <code>PatternLayout</code> can be used
50 inside of the statement. (see the test cases for examples)
52 <p>Overriding the {@link #getLogStatement} method allows more
53 explicit control of the statement used for logging.
55 <p>For use as a base class:
59 <li>Override <code>getConnection()</code> to pass any connection
60 you want. Typically this is used to enable application wide
63 <li>Override <code>closeConnection(Connection con)</code> -- if
64 you override getConnection make sure to implement
65 <code>closeConnection</code> to handle the connection you
66 generated. Typically this would return the connection to the
69 <li>Override <code>getLogStatement(LoggingEvent event)</code> to
70 produce specialized or dynamic statements. The default uses the
75 @author Kevin Steppe (<A HREF="mailto:ksteppe@pacbell.net">ksteppe@pacbell.net</A>)
78 public class JDBCAppender extends org.apache.log4j.AppenderSkeleton {
81 * URL of the DB for default connection handling
83 protected String databaseURL = "jdbc:odbc:myDB";
86 * User to connect as for default connection handling
88 protected String databaseUser = "me";
91 * User to use for default connection handling
93 protected String databasePassword = "mypassword";
96 * Connection used by default. The connection is opened the first time it
97 * is needed and then held open until the appender is closed (usually at
98 * garbage collection). This behavior is best modified by creating a
99 * sub-class and overriding the <code>getConnection</code> and
100 * <code>closeConnection</code> methods.
102 protected Connection connection = null;
105 * Stores the string given to the pattern layout for conversion into a SQL
106 * statement, eg: insert into LogTable (Thread, Class, Message) values
107 * ("%t", "%c", "%m").
109 * Be careful of quotes in your messages!
111 * Also see PatternLayout.
113 protected String sqlStatement = "";
116 * size of LoggingEvent buffer before writting to the database.
119 protected int bufferSize = 1;
122 * ArrayList holding the buffer of Logging Events.
124 protected ArrayList buffer;
127 * Helper object for clearing out the buffer
129 protected ArrayList removes;
131 private boolean locationInfo = false;
133 public JDBCAppender() {
135 buffer = new ArrayList(bufferSize);
136 removes = new ArrayList(bufferSize);
140 * Gets whether the location of the logging request call
141 * should be captured.
144 * @return the current value of the <b>LocationInfo</b> option.
146 public boolean getLocationInfo() {
151 * The <b>LocationInfo</b> option takes a boolean value. By default, it is
152 * set to false which means there will be no effort to extract the location
153 * information related to the event. As a result, the event that will be
154 * ultimately logged will likely to contain the wrong location information
155 * (if present in the log format).
158 * Location information extraction is comparatively very slow and should be
159 * avoided unless performance is not a concern.
162 * @param flag true if location information should be extracted.
164 public void setLocationInfo(final boolean flag) {
170 * Adds the event to the buffer. When full the buffer is flushed.
172 public void append(LoggingEvent event) {
174 event.getThreadName();
175 // Get a copy of this thread's MDC.
178 event.getLocationInformation();
180 event.getRenderedMessage();
181 event.getThrowableStrRep();
184 if (buffer.size() >= bufferSize) {
190 * By default getLogStatement sends the event to the required Layout object.
191 * The layout will format the given pattern into a workable SQL string.
193 * Overriding this provides direct access to the LoggingEvent
194 * when constructing the logging statement.
197 protected String getLogStatement(LoggingEvent event) {
198 return getLayout().format(event);
203 * Override this to provide an alertnate method of getting
204 * connections (such as caching). One method to fix this is to open
205 * connections at the start of flushBuffer() and close them at the
206 * end. I use a connection pool outside of JDBCAppender which is
207 * accessed in an override of this method.
209 protected void execute(String sql) throws SQLException {
211 Connection con = null;
212 Statement stmt = null;
215 con = getConnection();
217 stmt = con.createStatement();
218 stmt.executeUpdate(sql);
223 closeConnection(con);
226 //System.out.println("Execute: " + sql);
231 * Override this to return the connection to a pool, or to clean up the
234 * The default behavior holds a single connection open until the appender
235 * is closed (typically when garbage collected).
237 protected void closeConnection(Connection con) {
241 * Override this to link with your connection pooling system.
243 * By default this creates a single connection which is held open
244 * until the object is garbage collected.
246 protected Connection getConnection() throws SQLException {
247 if (!DriverManager.getDrivers().hasMoreElements()) {
248 setDriver("sun.jdbc.odbc.JdbcOdbcDriver");
251 if (connection == null) {
252 connection = DriverManager.getConnection(databaseURL, databaseUser,
260 * Closes the appender, flushing the buffer first then closing the default
261 * connection if it is open.
268 if (connection != null && !connection.isClosed()) {
271 } catch (SQLException e) {
272 errorHandler.error("Error closing connection", e, ErrorCode.GENERIC_FAILURE);
278 * loops through the buffer of LoggingEvents, gets a
279 * sql string from getLogStatement() and sends it to execute().
280 * Errors are sent to the errorHandler.
282 * If a statement fails the LoggingEvent stays in the buffer!
284 public void flushBuffer() {
285 //Do the actual logging
286 removes.ensureCapacity(buffer.size());
287 for (Iterator i = buffer.iterator(); i.hasNext();) {
288 LoggingEvent logEvent = (LoggingEvent)i.next();
290 String sql = getLogStatement(logEvent);
293 catch (SQLException e) {
294 errorHandler.error("Failed to excute sql", e,
295 ErrorCode.FLUSH_FAILURE);
297 removes.add(logEvent);
301 // remove from the buffer any events that were reported
302 buffer.removeAll(removes);
304 // clear the buffer of reported events
309 /** closes the appender before disposal */
310 public void finalize() {
316 * JDBCAppender requires a layout.
318 public boolean requiresLayout() {
326 public void setSql(String sql) {
328 if (getLayout() == null) {
329 this.setLayout(new PatternLayout(sql));
332 ((PatternLayout)getLayout()).setConversionPattern(sql);
338 * Returns pre-formated statement eg: insert into LogTable (msg) values ("%m")
340 public String getSql() {
345 public void setUser(String user) {
350 public void setURL(String url) {
355 public void setPassword(String password) {
356 databasePassword = password;
360 public void setBufferSize(int newBufferSize) {
361 bufferSize = newBufferSize;
362 buffer.ensureCapacity(bufferSize);
363 removes.ensureCapacity(bufferSize);
367 public String getUser() {
372 public String getURL() {
377 public String getPassword() {
378 return databasePassword;
382 public int getBufferSize() {
388 * Ensures that the given driver class has been loaded for sql connection
391 public void setDriver(String driverClass) {
393 Class.forName(driverClass);
394 } catch (Exception e) {
395 errorHandler.error("Failed to load driver", e,
396 ErrorCode.GENERIC_FAILURE);