log4j mysql 异步_用log4j把日志异步写入数据库中

白青青
2023-12-01

发表时间:2008-03-19

BufferSize没什么作用,JDBCAppender

只是把用户输出的log现在一个ArrayList中保存,当其数量达到了BufferSize,才启动写日志。而且JDBCAppender还是每次都生成Connection,每一个Log还是单独写入,不是批量写入。

Log4J的数据库写入方式就是一个鸡肋,如果需要提高性能,首先,自己需要实现一个连接池。而且其还不支持addBatch,赫赫,如下是log4j源代码(JDBCAppender.java)

########################

public void flushBuffer() {

//Do the actual logging

removes.ensureCapacity(buffer.size());

for (Iterator i = buffer.iterator(); i.hasNext();) {

try {

LoggingEvent logEvent = (LoggingEvent)i.next();

String sql = getLogStatement(logEvent);

execute(sql);

removes.add(logEvent);

}

catch (SQLException e) {

errorHandler.error("Failed to excute sql", e,

ErrorCode.FLUSH_FAILURE);

}

}

// remove from the buffer any events that were reported

buffer.removeAll(removes);

// clear the buffer of reported events

removes.clear();

}

###########################

protected void execute(String sql) throws SQLException {

Connection con = null;

Statement stmt = null;

try {

con = getConnection();

stmt = con.createStatement();

stmt.executeUpdate(sql);

} catch (SQLException e) {

if (stmt != null)

stmt.close();

throw e;

}

stmt.close();

closeConnection(con);

//System.out.println("Execute: " + sql);

}

 类似资料: