java 如何删除旧的滚动 log4j2 日志,最多保留 10 个文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34692415/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 23:12:32  来源:igfitidea点击:

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

javalogginglog4jlog4j2rollingfileappender

提问by pdeva

What I want is:

我想要的是:

  • Maximum of 10 log files, in total
  • Each log file, not more than 50MB in size.
  • 总共最多 10 个日志文件
  • 每个日志文件,大小不超过 50MB。

Thus the logs folder never grows over (50MB *10 )= 500MB.

因此,日志文件夹永远不会超过 (50MB *10 )= 500MB。

But it seems my log4j2 config is not properly done.

但似乎我的 log4j2 配置没有正确完成。

What is happening is:

正在发生的事情是:

  • Logs do roll over after 50 MB
  • But there are upto 10 logs kept per day
  • Thus there is no limit of number of log files kept in log folder (since for eg, in 2 days, 20 logs of 50mb each have collected)
  • 日志在 50 MB 后会翻转
  • 但是每天最多保存 10 个日志
  • 因此,日志文件夹中保存的日志文件数量没有限制(因为例如,在 2 天内,收集了 20 个 50mb 的日志)

Here is the config:

这是配置:

<Configuration status="WARN">
    <Appenders>
        <RollingFile name="RollingFile" fileName="log/my.log" filePattern="log/my-%d{MM-dd-yyyy}-%i.log">
          <PatternLayout>
                <Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
          </PatternLayout>
          <Policies>
                <OnStartupTriggeringPolicy />
                <TimeBasedTriggeringPolicy />
                <SizeBasedTriggeringPolicy size="50 MB"/>
          </Policies>
          <DefaultRolloverStrategy max="10"/>
        </RollingFile>
    </Appenders>
    <Loggers>
        <Root level="info">
            <AppenderRef ref="RollingFile"/>
        </Root>
    </Loggers>
</Configuration>

What am I doing wrong?

我究竟做错了什么?

回答by Remko Popma

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

从 2.5 开始,Log4j 支持在每次翻转时执行的自定义删除操作

You can control which files are deleted by:

您可以通过以下方式控制删除哪些文件:

  1. Name (matching a globor 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")
  1. 名称(匹配globregex
  2. 年龄(“如果超过 14 天,则删除”)
  3. 计数(“只保留最近的 3 个”)
  4. 大小(“仅保留最新的文件,最大为 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.

以上可以结合。与其仅指定大小条件以将磁盘使用量降低到最大 500MB,还不如匹配名称,以免无意中删除不相关的文件。

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.

需要更精细地控制要删除哪些文件的用户可以使用任何受支持的 JSR-223 脚本语言指定脚本条件。

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 rolloverto make them take up less disk space.

顺便说一句,请注意,您可以在滚动时压缩日志文件,以减少它们占用的磁盘空间。

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

最后,小心!无法恢复以这种方式删除的文件。:-)

回答by Taha

The TimeBasedTriggeringPolicyworks 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.

TimeBasedTriggeringPolicy工程基础的filePattern。基本上,文件模式中的最小时间单位 ( %d) 是触发时间间隔。在您的情况下,该值为“dd”,因此该策略每天都会触发。

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

%i 的存在会在filePattern一天内保留多个日志文件。我会建议您尝试不%ifilePattern