问题描述
我正在使用RollingFile appender。我希望每20分钟后滚动一次日志文件,而不管日志记录事件如何。例如,在一小时内我应该有3个日志文件,即使那个小时可能没有任何记录。这可能使用Log4j2吗?如果是,请提供所需的配置(在log4j2.xml中)。
以下配置似乎不起作用:
I am using RollingFile appender. I want the log file to be rolled after every 20 minutes irrespective of the logging event. For instance in an hour I should have 3 log files even though there might have not been any logging in that hour. Is this possible using Log4j2? If yes please provide the configuration ( in log4j2.xml) that are required.The below config does not seem to work :
<RollingFile name="RECHARGE_NMCD" fileName="D:/rc_nmcd/rc_nmcd.log" append="true" bufferedIO="false" filePattern="D:/rc_nmcd/rc_nmcd_%d{yyyy-MM-dd-HH-mm}.process">
<PatternLayout>
<Pattern>%m%n</Pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy interval="20"/>
</Policies>
<DefaultRolloverStrategy max="20" />
</RollingFile>
推荐答案
我推荐这个插件
每个FTimeBasedTriggeringPolicy我有一个Runnable线程它实际上会睡到下一次翻转而不是LogRotateThread,它会在一段无限期的指定时间内休眠。
I referred this plugin https://github.com/mushkevych/log4j2plugin
I had a Runnable thread per FTimeBasedTriggeringPolicy which would actually sleep upto next rollover instead of the LogRotateThread which sleeps for some indefinite specified time.
Thread rotateThread = new Thread(new LogRotateRunnable(this));
rotateThread.start();
在初始化(RollingFileManager)之后添加上述内容
Added the above after initialize(RollingFileManager)
LogRotateRunnable:
LogRotateRunnable :
while (true) {
long sleepTime = fTimeBasedTriggeringPolicy.getNextRollover()
- System.currentTimeMillis();
if (sleepTime > 0) {
try {
Thread.sleep(sleepTime + EMPTY_LOG_EVENT_DELAY);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
fTimeBasedTriggeringPolicy.checkRollover(new EmptyLogEvent());
}
它也不会滚动空文件,但好的部分当然是如果在下一个翻转时间内至少有一个有效的日志条目,它会。
Also it won't roll empty files, but the good part is of course if atleast one valid log entry within next rollover time, it will.
这篇关于Log4j2在指定的持续时间后自动翻转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!