log4j2 - DefaultRolloverStrategy for daily RollingFile appender, max not respected

北战南征 提交于 2020-08-08 07:26:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!