如何覆盖 log4j 中的日志文件?
我有一个日志文件,其中添加了以下附加程序:
logger.addAppender(new FileAppender(new PatternLayout(),"log.txt"));
问题是,每次运行应用程序时,附加日志记录信息都会附加到同一个日志文件中。 我该怎么做才能每次都覆盖该文件?
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 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您在属性文件中像这样声明了一个附加程序:
那么您要添加的是
默认值为
true
。因此,如果您以编程方式声明附加程序,那么您要做的就是调用
setAppend(false)
。If you have an appender declared like so in a properties file:
Then what you want to add is
The default value is
true
.So, if you are declaring your appenders programmatically, then what you want to do is call
setAppend(false)
.将以下行添加到您的 XML 文件中:
请注意,由于 log4j 中的奇怪 XML 解析,
元素必须出现在块中(不与其他类型的元素混合)。
例如,这有效:
但这不起作用(!)
Add to your XML file the following line:
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:
But this doesn't (!)
使用 RollingFileAppender。
Use RollingFileAppender.
马特之前的回答是正确的,只是它使用了属性文件。 如果您正在寻找一种编程方法,我建议您通过修改代码来禁用附加模式,如下所示:
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: