开发者

Create a new log file every time my program is run

I am using the Apache commons logging library and log4j to generate my log files.

Now I want to create a new file every time I run my program. The current count should be appended to the log file'开发者_如何学JAVAs name.

For example: program_1.log program_2.log program_3.log

Do you know how I could achieve this?


Turning my comment into an answer, as requested:

Any reason why you don't want to use a timestamp? I've found them to be more meaningful as suffixes when I have to look back at log files.


I think this is not supported by log4j, so you should create your own implementation, extending FileAppender:

public class CustomAppender extends FileAppender {

 ...

  public
  CustomAppender(Layout layout, String filename, boolean append, boolean bufferedIO,
               int bufferSize) throws IOException {
    this.layout = layout;     
    // file name will be the basis; you should calculate the suffix yourself
    customname = filename + ...
    this.setFile(customname, append, bufferedIO, bufferSize);
  }

 ...


This article gives an example of how to write to a dynamically determined log file. This gives you the flexibility to determine which filename you want when your program starts.

The hardest part is knowing what the current count is. It's probably simplest to do a binary search of the filenames to find the highest number filename - this wouldn't be too bad - requiring log n file existence tests where n is the number of logs. If you have 1 million logs, that's only 20 file checks.


It seems that plain Log4J does not support this. However, there is a Log4J Extras Companion, containing its own RollingFileAppender, which seems to be quite freely configurable via RollingPolicy and TriggeringPolicy parameters. So you could try implementing your own policy.


I assume that you intend to create a new file for each JVM instance. I think you can implement that (not trivial but not difficult) by extending FileAppender. You can look at the code of DatedFileAppender for some inspiration.


In a less elegant way, every time your program runs it could create a file log_num.dat where it will keep track of a single number (the next log file to create).


this works for me,

<appender name="fileAppender" class="org.apache.log4j.DailyRollingFileAppender">
  <param name="Threshold" value="TRACE" />
  <param name="File" value="amLog.log"/>
  <param name="DatePattern" value="'.'YYYY-MM-dd-HH-mm"/>
  <layout class="org.apache.log4j.PatternLayout">
     <param name="ConversionPattern" value="%d %-5p  [%c{1}] %m %n" />
  </layout>

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜