Log4j to the database to write log, and Jdbcappender have to go to the database connection, and write log operation is very frequent, so that if the Jdbcappender method to frequently disconnect the database operation, obviously, this is not the ideal. An article on the internet to change this into a database connection pool. Hibernate is now widely used in the Java EE Project, and the following describes how to extend the Jdbcappender and connect to the hibernate database.
Looking at Jdbcappender, we can see that as long as the following three methods are overloaded:
Protected Connection getconnection () throws SQLException;
protected void execute (String sql) throws SQLException;
protected void CloseConnection (Connection con);
The specific implementation of the original code is as follows:
Package com.common.util;
Import java.sql.Connection;
Import java.sql.SQLException;
Import Org.apache.log4j.spi.ErrorCode;
Import org.apache.log4j.spi.LoggingEvent;
public class Jdbcconnappender extends Org.apache.log4j.jdbc.JDBCAppender {
/**
* Override This function to return a hibernate connection.
*/
Protected Connection getconnection () throws SQLException {
Return hibernateutil.currentsession (). connection ();
}
/**
* Perform database operations.
*/
protected void execute (String sql) throws SQLException {
Connection con = null;
Statement stmt = null;
try {
con = getconnection ();
stmt = Con.createstatement ();
Stmt.execute (SQL);
Con.commit ();
catch (SQLException e) {
if (stmt!= null)
Stmt.close ();
Throw e;
}
Stmt.close ();
CloseConnection (con);
}
/**
* Close the database connection.
*/
protected void CloseConnection (Connection con) {
try {
if (connection!= null &&!connection.isclosed ())
Connection.close ();
catch (SQLException e) {
Errorhandler.error ("Error closing connection", E,
Errorcode.generic_failure);
}
}
}