Kevin
Kevin

Reputation: 161

How do you create log files in log4j per program execution?

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.

Upvotes: 6

Views: 4824

Answers (2)

Twister
Twister

Reputation: 724

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

Upvotes: 3

gulbrandr
gulbrandr

Reputation: 1013

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.

Upvotes: 1

Related Questions