扩展Log4j支持JNDI数据源

log4j.properties配置文件:

log4j.rootLogger=INFO,db



#使用log4j扩展支持JNDI数据源

log4j.appender.db=com.qdgswx.log4j.ds.JndiDSAppender

log4j.appender.db.jndiName=wstjndi

log4j.appender.db.BufferSize=1

log4j.appender.db.sql=insert into wx_log (openid,nsrsbh,logtype,classname,methodname,oprtime,loglevel,content) values ('%X{openid}','%X{nsrsbh}','%X{logtype}','%C','%M','%d{yyyy-MM-dd HH:mm:ss}','%p','%m')  

log4j.appender.db.layout=org.apache.log4j.PatternLayout

扩展类JndiDSAppender.java

public class JndiDSAppender extends JDBCAppender {



    protected DataSource ds = null;

    protected String jndiName;



    public void setJndiName(String jndiName) {

        this.jndiName = jndiName;

    }

    

    protected synchronized void init() {

        if (ds != null) {

            return;

        }

        try {

            InitialContext context = new InitialContext();

            ds = (DataSource) context.lookup(jndiName);

        } catch (NamingException e) {

            this.errorHandler.error(e.getMessage());

        }

    }

    

     @Override  

    protected Connection getConnection() throws SQLException {  

        while(ds==null){

            init();

        }

        

        Connection conn = ds.getConnection();

        conn.setAutoCommit(true);

        

        return conn;

    }

    

    @Override  

    protected void closeConnection(Connection conn) {  

        try {  

            if(conn!=null&&!conn.isClosed()) {

                conn.close();  

            } 

        } catch (SQLException e) {  

            this.errorHandler.error(e.getMessage());  

        }  

    }  

}

 

你可能感兴趣的:(log4j)