Skip to content

Instantly share code, notes, and snippets.

@lenny
Created January 4, 2012 17:50
Show Gist options
  • Save lenny/1561176 to your computer and use it in GitHub Desktop.
Save lenny/1561176 to your computer and use it in GitHub Desktop.
Custom Log4j appender to log messages into database via Hibernate
package org.aps.webprowo.hibernate;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Vector;
import org.apache.log4j.Appender;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.spi.LoggingEvent;
import org.aps.eop.dao.DataAccessUtils;
import org.aps.eop.hibernate.TransactionUtil.TransactionHolder;
import org.aps.eop.hibernate.springtx.TxCallback;
import org.aps.eop.hibernate.springtx.TxTemplate;
import org.hibernate.Transaction;
/**
* Log4J appender that uses Hibernate to store log messages in a database.
*
* <p>
*
* This implementation assumes that the log message itself is a persistent
* entity. Logging messages will be accumulated in a buffer of size
* <i>bufferSize</i> and saved to the database when the buffer is full.
*
* @author Lenny Marks ([email protected])
*
*/
public class HibernateAppender extends AppenderSkeleton implements Appender {
private Vector buffer = new Vector();
private int bufferSize = 20;
private TxTemplate txTemplate;
private DataAccessUtils daoUtils;
public HibernateAppender(TxTemplate txTemplate, DataAccessUtils daoUtils) {
this.txTemplate = txTemplate;
this.daoUtils = daoUtils;
}
public void setBufferSize(int size) {
this.bufferSize = size;
}
/*
* (non-Javadoc)
*
* @see org.apache.log4j.AppenderSkeleton#append(org.apache.log4j.spi.LoggingEvent)
*/
protected void append(LoggingEvent loggingEvent) {
buffer.add(loggingEvent);
synchronized (buffer) {
if(buffer.size() >= bufferSize) {
try {
persistEvents(new ArrayList(buffer));
} catch(Exception e) {
System.err.println("Failed to write audit logs");
e.printStackTrace();
} finally {
buffer.clear();
}
}
}
}
private void persistEvents(final ArrayList logEvents) {
txTemplate.execute(new TxCallback() {
public Object execute(TransactionHolder tx) throws Exception {
for(Iterator i = logEvents.iterator(); i.hasNext();) {
LoggingEvent logEvent = (LoggingEvent)i.next();
daoUtils.saveObject(logEvent.getMessage());
}
return null;
}
});
}
public void close() {
}
public boolean requiresLayout() {
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment