`
masterkey
  • 浏览: 331059 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

答复: 用log4j把日志异步写入数据库中

阅读更多
http://www.iteye.com/topic/172125

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);
  }
1
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics