关于Log4j的性能优化--FileAppender

本文以slf4j.1.7.19为源码展示样例。

项目中用的Appender是org.apache.log4j.RollingFileAppender

在配置文件中加以下两句可以减少磁盘IO操作

log4j.appender.all.bufferedIO=true
log4j.appender.all.bufferSize=81920

第一个表示IO使用缓冲区;

第二个参数表示缓冲区的大小,单位是B,字节;

相关源码如下:org.apache.log4j.FileAppender

public
  synchronized
  void setFile(String fileName, boolean append, boolean bufferedIO, int bufferSize)
                                                            throws IOException {
    LogLog.debug("setFile called: "+fileName+", "+append);

    // It does not make sense to have immediate flush and bufferedIO.
    if(bufferedIO) {
      setImmediateFlush(false);
    }

    reset();
    FileOutputStream ostream = null;
    try {
          //
          //   attempt to create file
          //
          ostream = new FileOutputStream(fileName, append);
    } catch(FileNotFoundException ex) {
          //
          //   if parent directory does not exist then
          //      attempt to create it and try to create file
          //      see bug 9150
          //
          String parentName = new File(fileName).getParent();
          if (parentName != null) {
             File parentDir = new File(parentName);
             if(!parentDir.exists() && parentDir.mkdirs()) {
                ostream = new FileOutputStream(fileName, append);
             } else {
                throw ex;
             }
          } else {
             throw ex;
          }
    }
    Writer fw = createWriter(ostream);
    if(bufferedIO) {
      fw = new BufferedWriter(fw, bufferSize);
    }
    this.setQWForFiles(fw);
    this.fileName = fileName;
    this.fileAppend = append;
    this.bufferedIO = bufferedIO;
    this.bufferSize = bufferSize;
    writeHeader();
    LogLog.debug("setFile ended");
  }

可见只有bufferedIO配置为true,才会使用缓冲区。

bufferedIO默认为false,相关源码如下:

/**
     Do we do bufferedIO? */
  protected boolean bufferedIO = false;

  /**
   * Determines the size of IO buffer be. Default is 8K. 
   */
  protected int bufferSize = 8*1024;

bufferSize默认为8K,如果够用的话,可以不配置,只配置bufferedIO为true,即可。

另外,如果IO确实是应用的瓶颈,可以考虑使用org.apache.log4j.AsyncAppender。这是异步的操作。

猜你喜欢

转载自buddie.iteye.com/blog/2289308