How do I overwrite a log file in log4j?

2019-01-25 05:18发布

问题:

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 ?

回答1:

Use RollingFileAppender.



回答2:

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).



回答3:

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**));


回答4:

Add to your XML file the following line:

<param name="Append" value="false" />

Note that due to odd XML parsing in log4j, the <param> elements must appear in a block (not intermingled with other types of elements).

For example, this works:

<appender name="appender-log" class="org.apache.log4j.FileAppender">
<param name="File" value="efoimporter.log" />
<param name="Append" value="false" />
<layout class="org.apache.log4j.PatternLayout">
  <param name="ConversionPattern" value="%m%n" />
</layout>
</appender>

But this doesn't (!)

<appender name="appender-log" class="org.apache.log4j.FileAppender">
<param name="File" value="efoimporter.log" />
<layout class="org.apache.log4j.PatternLayout">
  <param name="ConversionPattern" value="%m%n" />
</layout>
<param name="Append" value="false" />
</appender>