日期:2014-05-18  浏览次数:20803 次

Log4j的日志文件夹生成和日志文件编号问题?
log4j集成到了原来的日志输出类中,仅用做日志文件输出

配置如下:
log4j.rootLogger=A2

log4j.appender.A2=org.apache.log4j.RollingFileAppender

log4j.appender.A2.File=C:/test/log4j/info.log <----- 关键是这里

log4j.appender.A2.MaxFileSize=20KB

log4j.appender.A2.MaxBackupIndex=100

log4j.appender.A2.Append=false

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

log4j.appender.A2.layout.ConversionPattern=%m%n

======================================
问题如下
1.指定的日志存放路径是 C:/test/log4j/info.log
但是我想动态生成时间日期文件夹,比如
C:/test/log4j/2008/01/02/info.log
C:/test/log4j/2008/01/02/info2.log
C:/test/log4j/2008/01/02/info3.log

C:/test/log4j/2008/01/03/info.log

C:/test/log4j/2008/02/14/info.log
这个如何在代码里实现,看过类似的动态路径C:/{filepath}/info.log,但也是一次性的,就是{filepath}一被指定,还是不变的

2.动态日志文件编号问题
如上配置生成的动态文件一旦超过20KB,则新文件是
info.log.1
info.log.2
info.log.3
...
...

我如何更改是新文件名为
info.log
info2.log
info3.log
...
...

直接通过log4j的方式编号文件


------解决方案--------------------
关注中。。。。
------解决方案--------------------
关注中。。。。。
------解决方案--------------------
org/apache/log4j/RollingFileAppender.java
修改target 的命名

Java code
  public // synchronization not necessary since doAppend is alreasy synched
  void rollOver() {
    File target;
    File file;

    LogLog.debug("rolling over count=" + ((CountingQuietWriter) qw).getCount());
    LogLog.debug("maxBackupIndex="+maxBackupIndex);

    // If maxBackups <= 0, then there is no file renaming to be done.
    if(maxBackupIndex > 0) {
      // Delete the oldest file, to keep Windows happy.
      file = new File(fileName + '.' + maxBackupIndex);
      if (file.exists())
       file.delete();

      // Map {(maxBackupIndex - 1), ..., 2, 1} to {maxBackupIndex, ..., 3, 2}
      for (int i = maxBackupIndex - 1; i >= 1; i--) {
    file = new File(fileName + "." + i);
    if (file.exists()) {
      target = new File(fileName + '.' + (i + 1));
      LogLog.debug("Renaming file " + file + " to " + target);
      file.renameTo(target);
    }
      }

      // Rename fileName to fileName.1
      target = new File(fileName + "." + 1);

      this.closeFile(); // keep windows happy.

      file = new File(fileName);
      LogLog.debug("Renaming file " + file + " to " + target);
      file.renameTo(target);
    }

    try {
      // This will also close the file. This is OK since multiple
      // close operations are safe.
      this.setFile(fileName, false, bufferedIO, bufferSize);
    }
    catch(IOException e) {
      LogLog.error("setFile("+fileName+", false) call failed.", e);
    }
  }

------解决方案--------------------
有难度啊,我觉得你可以用Timer来动态生成按时间日期的文件夹,但问题怎么将log4j.appender.A2.File=C:/test/log4j/info.log改成动态的,像这样C:/{filepath}/info.log,看接下来有朋友想出好的办法吗?(其实可以使用Maven2 和 Ant来copy,但是多了步骤,麻烦);至于你那个: 2.动态日志文件编号问题 ,没必要吧,把log4j.appender.A2.MaxFileSize=20KB , MaxFileSize设大点,没什么事吧。
PS.继续关注....