问题
I am trying to write an appender with a daily rolling policy with 10 maximum total files no matter the day.
Every 10 MB it creates a new log file and stores it with today's date and an index.
This is what I have so far:
<RollingFile name="MyRollingFile" fileName="./log/logs.log"
filePattern="./log/logs-%d{yyyy-MM-dd}-%i.log">
<PatternLayout>
<pattern>%n%d{yy-MM-dd HH:mm:ss.SSS} [%p] %m</pattern>
</PatternLayout>
<Policies>
<SizeBasedTriggeringPolicy size="10MB" />
</Policies>
<DefaultRolloverStrategy max="10" />
</RollingFile>
It is not correct because this saves a maximum of ten files every single day but I want ten maximum files in total. So obviously I find up to 100 files after 10 days. I want to limit the total file maximum to 10. How could I do that?
回答1:
See the Delete operation for the DefaultRolloverStrategy documented at http://logging.apache.org/log4j/2.x/manual/appenders.html#RollingFileAppender. In short what you want is
<DefaultRolloverStrategy max="10">
<Delete basePath="./logs">
<IfFileName glob="*/logs-*.log" />
<IfAccumulatedFileCount exceeds="10" />
</Delete>
</DefaultRolloverStrategy>
I should also point out that since you do not have a time-based rollover policy the date in your filePattern is always going to contain the time of when Log4j configured and the index will endlessly increment. You need to add either the TimeBasedTriggeringPolicy or CronTriggeringPolicy to have the date change every day.
来源:https://stackoverflow.com/questions/54403686/log4j2-defaultrolloverstrategy-for-daily-rollingfile-appender-max-not-respect