ログ4 jにデータソースをサポートさせる
1768 ワード
package gfsoft.his.util;
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import org.apache.log4j.jdbc.JDBCAppender;
import org.apache.log4j.spi.ErrorCode;
/**
* JDBCAppender,
* :
* 1、 : JNDI ,
* 2、 : LOG4J , ,
*
*/
public class JNDIAppender extends JDBCAppender {
private String jndiName;
public String getJndiName() {
return jndiName;
}
public void setJndiName(String jndiName) {
this.jndiName = jndiName;
}
/**
* JNDI
*/
private DataSource lookupDataSource(){
try {
Context context = new InitialContext();
return (DataSource) context.lookup(getJndiName());
} catch (NamingException e) {
throw new RuntimeException("Cannot find JNDI DataSource: " + getJndiName(), e);
}
}
/**
*
*/
protected Connection getConnection() throws SQLException {
if (getJndiName() == null) {
return super.getConnection();
} else {
return lookupDataSource().getConnection();
}
}
protected void closeConnection(Connection con) {
try {
con.close();
} catch (SQLException e) {
errorHandler.error("Failed to close connection", e, ErrorCode.CLOSE_FAILURE);
}
}
}