Home Coding Create new log file with log4j FileAppender when using Quartz Scheduler

Create new log file with log4j FileAppender when using Quartz Scheduler

by Benny

Recently came across a problem whereby the quartz scheduler could not recreate a new log4j FileAppender log when the job is call again.

Googled a bit and found out a couple of solutions such as using a custom log4j classes, which create a seperate thread when being called in quartz scheduler.

I find that it is too complex and had try several ways to recreate the log file inside Quartz.

And finally came up with this one line of code.

Before I begin, let’s take a look at my log4j config.
This log4j config will create a simple console system out logger and also a FileAppender logger.
For my case, I want to re-create a new log file whenever this job is run.

log4j.rootLogger=INFO, stdout
log4j.additivity.stdout=false
log4j.additivity.joblog=false
log4j.appender.ROOT.layout.ConversionPattern=[%d] %t %c %-5p - %m%n

#console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p - %m%n

#per job execution log
log4j.logger.com.yourcompany=INFO, joblog
log4j.appender.joblog=org.apache.log4j.FileAppender 
log4j.appender.joblog.layout=org.apache.log4j.PatternLayout
log4j.appender.joblog.File=../jobtemp.log
log4j.appender.joblog.Append=false
log4j.appender.joblog.layout.ConversionPattern=%d %p - %m%n

and here’s the schedule job

public class ScheduleJob implements StatefulJob {
	
	private static Logger logger = Logger.getLogger(ScheduleJob.class);

	public void startJob() throws SchedulerException{
		Scheduler scheduler =
			StdSchedulerFactory.getDefaultScheduler();
		scheduler.start();
	}
    
	public void execute(JobExecutionContext context) 
		throws JobExecutionException {
		
		//reset log4j config for FileAppender
		PropertyConfigurator.configure("../conf/log4j.properties");
		
		RunJobImmediately newJob  = new RunJobImmediately();
		newJob.performJob();
		
	}
	
	public static void main(String args[]){
    	try{
    		ScheduleJob scheduleJob = new ScheduleJob();
    		scheduleJob.startJob();
    		
		}catch(Exception e){
			logger.error(e);
		}    
	}
}

and finally the one line of code to recreate the log file.
Apparently, this line will somehow ‘reload’ the log4j  utitlies, which thus recreate the FileAppender logger to re-create the log file.

PropertyConfigurator.configure("../conf/log4j.properties");

Feel free to let me know if there is any performance issues or it is not working at your side.

You may also like

Leave a Comment