Reputation: 383
Currently I am using log4j for logging. It is generating the log file perfectly.But the problem is: whenever I run my program new logs which are generated are getting appended to already generated logs in the same file. Below is my log4j properties file:
log4j.rootCategory=INFO,LOGFILE
log4j.logger.org.apache.axis.enterprise=FATAL, LOGFILE
log4j.appender.LOGFILE = org.apache.log4j.DailyRollingFileAppender
log4j.appender.LOGFILE.File=applicationLogs.txt
log4j.appender.LOGFILE.Append = true
log4j.appender.LOGFILE.Threshold=DEBUG
log4j.appender.LOGFILE.DatePattern = \u2018.\u2019yyy-MM-dd
log4j.appender.LOGFILE.layout = org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} %c{1} [%p] %m%n
I need to generate a new log file every-time I run my program.How to do that? This file is perfect.But I want a slight modification.
Upvotes: 1
Views: 3869
Reputation: 1
In your code add something like below:
String today= Calendar.getInstance()
.getTime()
.toString()
.replaceAll(" ", "_")
.replaceAll(":", "");
System.setProperty("logfilename", today);
and in your properties file:
log4j.appender.file.File=C:\\${logfilename}.log
Upvotes: 0
Reputation: 2692
Take following steps:
1. log4j.appender.LOGFILE.File=applicationLogs_${current_date}.txt
2. log4j.appender.LOGFILE.Append=false
.
For current_date
to work edit your main class and add following code:
static{
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy hhmmss");
System.setProperty("current_date", dateFormat.format(new Date()));
}
First setting will create a new log file each time your program starts depending on current date (so that you do not lose old logs) and by second setting it will not append to your old file but overwrite it.
You can use any one of the setting. First one is preferable as you are not losing your old logs.
Upvotes: 2
Reputation: 1815
Set the append to false, overwrite
log4j.appender.FILE.Append=false
This article helps you. https://www.tutorialspoint.com/log4j/log4j_logging_files.htm
Also this question will help you. One logfile per run with log4j
Upvotes: 2