log4j use Hibernate admin database to connect __ database

Source: Internet
Author: User
Tags stmt log4j

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);

}

}

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.