How do I overwrite a log file in log4j?

2019-01-25 04:59发布

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条回答
够拽才男人
2楼-- · 2019-01-25 05:37

Use RollingFileAppender.

查看更多
The star\"
3楼-- · 2019-01-25 05:50

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**));
查看更多
Rolldiameter
4楼-- · 2019-01-25 05:50

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>
查看更多
Lonely孤独者°
5楼-- · 2019-01-25 05:51

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

查看更多
登录 后发表回答