6

I am currently using the DailyRollingFileAppender Class in log4j to do daily log file appending but I want to have the log files separated in the following format:

DATA.log.<date>_<time>_<random_#>

This should be done once per program execution so I end up with something like...

DATA.log.2011-01-13_12-46-38_<26>
DATA.log.2011-01-13_12-46-38_<79>
DATA.log.2011-01-13_12-46-38_<590>

Where different log files from different environments can be pooled together.

Is there anyway to do this without extending the FileAppender Class? At least, is there a way to do:

DATA.log.<date>_<time>_<sequential_#>.log

Thanks

Edit: I am already using DailyRollingFileAppender to get something like DATA.log.2011-01-13. What I want to know how to do is get the log file to rollover after each program execution (or before each program execution) and add a random numeric string at the end.

Kevin
  • 161
  • 2
  • 8

2 Answers2

3

have a look at : Setting a log file name to include current date in Log4j

EDIT : Add this class to your project, and use it as appender :

import java.util.Random;

import org.apache.log4j.DailyRollingFileAppender;

public class MyAppender extends DailyRollingFileAppender {    
    @Override
    public void  setFile(String fileName) {
        if (fileName.indexOf("%rnd") >= 0) {
            Random r = new Random();
            fileName = fileName.replaceAll("%rnd", Integer.toString(r.nextInt()));
        }
        super.setFile(fileName);
    }
}

Then just set your appender's filename to something like : filename.%rnd.log

log4j.appender.R=MyAppender.MyAppender
log4j.appender.R.File=.\\test.%rnd.log
Community
  • 1
  • 1
Twister
  • 749
  • 4
  • 9
  • I am already doing what the URL you posted says to do. What I want to do is add an additional random string at the end after each program execution so that I can keep track of multiple logs. I will edit my question for this. – Kevin Jan 14 '11 at 15:15
  • And you can add some other new patterns as well easily. And us it across several projects – Twister Jan 14 '11 at 15:43
1

In your code set a new environment property:

randomString = Long.toString(Math.abs((new Random()).nextLong()), Character.MAX_RADIX);
System.setProperty("randomString", randomString);

Then, in your log4j file use that variable using ${randomString}.

Hope it helps.

gulbrandr
  • 1,005
  • 1
  • 9
  • 16