views:

669

answers:

4

I have a log file that has the following appender added to it :


logger.addAppender(new FileAppender(new PatternLayout(),"log.txt"));

the thing is, each time I'm running my application, additional logging information gets appended to the same log file. What can I do to overwrite the file each time ?

+4  A: 

Use RollingFileAppender.

Dev er dev
API link: http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/RollingFileAppender.html
AgileJon
also, sending another boolean parameter with a false value to the FileAppender, yields the same result.
Geo
+2  A: 

If you have an appender declared like so in a properties file:

log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=file.log
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d %-5p %c - %m%n

Then what you want to add is

log4j.appender.LOGFILE.Append=false

The default value is true.

So, if you are declaring your appenders programmatically, then what you want to do is call setAppend(false).

matt b
+2  A: 

The previous answer by Matt is correct except that it uses a properties file. If you are looking for a programmatic approach, I suggest that you disable append mode by modify your code as follows:

logger.addAppender(new FileAppender(new PatternLayout(),"log.txt", **false**));
Ceki
A: 

All the above answers are assuming that the application will be restarted. This option does not work when running an application in a thread... i.e. a scheduler. In this case I found that this property was rendered useless.

Does anyone know a solution that does not require the restart of an application to overwrite the log file?

Andrew Harrison