views:

325

answers:

7

Hi,

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's name.

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

Do you know how I could achieve this?

A: 

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.

Péter Török
A: 

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.

leonbloy
+3  A: 

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);
  }

 ...
Vasil Remeniuk
A: 

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).

The Real Diel
+2  A: 

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.

mdma
A: 

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.

Benjamin Oakes
I therefore use the TimestampFileAppender (http://markmail.org/message/5on2bmatywehnbn7) now .
Bernhard V
+1  A: 

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>

Anand