How to delete older rolled over log4j2 logs, keeping up to 10 files?

风流意气都作罢 提交于 2019-12-01 03:56:53

Since 2.5, Log4j supports a custom Delete action that is executed on every rollover.

You can control which files are deleted by:

  1. Name (matching a glob or a regex)
  2. Age ("delete if 14 days old or older")
  3. Count ("keep only the most recent 3")
  4. Size ("keep only the most recent files up to 500MB")

The above can be combined. Instead of only specifying a size condition to keep disk usage down to max 500MB, it's a good idea to also match the name so you don't inadvertently delete unrelated files.

Users who need even more fine-grained control over which files to delete can specify a script condition using any supported JSR-223 scripting language.

Please check out the documentation, it has three full examples that may be useful.

For your question, this snippet may work:

  <DefaultRolloverStrategy>
    <!--
      * only files in the log folder, no sub folders
      * only rolled over log files (name match)
      * either when more than 10 matching files exist or when the max disk usage is exceeded
    -->
    <Delete basePath="log" maxDepth="1">
      <IfFileName glob="my-??-??-????-*.log">
        <IfAny>
          <IfAccumulatedFileSize exceeds="500 MB" />
          <IfAccumulatedFileCount exceeds="10" />
        </IfAny>
      </IfFileName>
    </Delete>
  </DefaultRolloverStrategy>

As an aside, note that you can compress log files on rollover to make them take up less disk space.

Finally, be careful! There is no way to recover files deleted this way. :-)

The TimeBasedTriggeringPolicy works based of the filePattern. Basically, the smallest unit of time in the file pattern (%d) is the triggering time interval. In your case the value is 'dd' hence the policy is triggered every day.

The presence of %i in your filePattern keeps multiple log files for a day. I would recommend trying without the %i in the filePattern.

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