To create multiple log files with log4j based on folder name

I am having multiple folders with each folder having few xml’s.

While unmarshalling XMls in for loop at the starting of the loop i am setting folder variable based on the folder xml’s i am unmarshalling . But i am not able to change the value of folder varialbe in the end.

Log4j file :

log4j.rootLogger=DEBUG, theFileAppender, theFileAppender, theFileAppender

log4j.appender.theFileAppender=org.apache.log4j.FileAppender log4j.appender.theFileAppender.File = ${folder}/error.log



log4j.appender.file.MaxBackupIndex=1 log4j.appender.theFileAppender.layout=org.apache.log4j.PatternLayout log4j.appender.theFileAppender.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c %x - %m%n

Starting of the loop i am setting the folder :

System.setProperty("folder", "E:/Logging/folderName");

At the end of loop : i am setting the folder by :

Properties properties = new Properties(System.getProperties()); properties.setProperty("folder","E:/Logging/folderName");

folderName is my folder name.

Its creating the required folder but its appending to the error log file created in the folder which is created at the starting of loop.

Please help me how to set the variable .


You can change the folder by invoking log4j API like this:

Getting your root logger and then modifying your appender by name (in this case, as your question says: “theFileAppender”).

String logFolderName = "newfoldername";
String logFilePath = "E:/Logging/" + logFolderName + "/error.log";

Logger logger = Logger.getRootLogger();
FileAppender appender = (FileAppender)logger.getAppender("theFileAppender");

As you can see, you just need to modify your logFolderName variable according to your needs for the new log file to be created.

Leave a Reply

Your email address will not be published. Required fields are marked *