How do you create log files in log4j to execute each program?

I am currently using the DailyRollingFileAppender class in log4j to add a log file daily, but I want the log files to be split in the following format:

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

This has to be done once to run the program, so I get 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> 

If different log files from different environments can be combined together.

Is there a way to do this without extending the FileAppender class? At least there is 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. I want to know how to do this: get the log file for rollover after each program (or before each program) and add a random number line at the end.

+6
java logging config log4j
source share
2 answers

look: Setting the log file name to include the 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 provide your appender file name something like: filename.% Rnd.log

 log4j.appender.R=MyAppender.MyAppender log4j.appender.R.File=.\\test.%rnd.log 
+3
source share

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 the log4j file use this variable with ${randomString} .

Hope this helps.

+1
source share

All Articles