开发者

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 o开发者_JS百科nce 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.


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


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜