如何使用log4j2删除旧日志

问题描述 投票:0回答:3

(仅供参考,我已经在网上查了很多文档。我使用的是storm-0.10.0-beta1。Storm中log4j2的配置文件是worker.xml)

现在,我尝试使用log4j2。

我正在寻找删除旧日志的方法,但我找不到。 部分配置如下。

    <RollingFile name="SERVICE_APPENDER"
             fileName="${sys:storm.home}/logs/${sys:logfile.name}.service"
             filePattern="${sys:storm.home}/logs/${sys:logfile.name}.service.%d{yyyyMMdd}">
        <PatternLayout>
            <pattern>${pattern}</pattern>
        </PatternLayout>
        <Policies>
            <TimeBasedTriggeringPolicy interval="1" modulate="true"/>
        </Policies>
        <DefaultRolloverStrategy max="9"/>
    </RollingFile>

起初,我预计超过 3 天的日志文件会被删除。

但实际上并非如此。

所以,我想知道是否有办法删除旧日志。

如果有我没掌握的方法,请通知我。

java logging log4j log4j2
3个回答
23
投票

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

您可以通过以下任意组合来控制删除哪些文件:

  1. 名称(匹配 globregex
  2. 年龄(“如果年龄超过 14 天则删除”)
  3. 计数(“仅保留最近的 3 个”)
  4. 大小(“仅保留最大 500MB 的最新文件”)

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

请查看文档,它包含三个可能有用的完整示例。

对于你的问题,这个片段应该有效:

<RollingFile name="rollingFile" 
      fileName="/path/app.log"
      filePattern="/path/app.%d{yyyy-MM-dd}.log"
      ignoreExceptions="false">
. . .
      <DefaultRolloverStrategy>
        <!--
          * only files in the log folder, no sub folders
          * only rolled over log files (name match)
          * only files that are 4 days old or older
        -->
        <Delete basePath="${sys:storm.home}/logs/" maxDepth="1">
          <IfFileName glob="*.service.????????" />
          <IfLastModified age="4d" />
        </Delete>
      </DefaultRolloverStrategy>
 . . .

<RollingFile>

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


3
投票

您可以在 log4j 的 JIRA 条目中找到更多背景信息:

https://issues.apache.org/jira/browse/LOG4J2-524

当您只使用

TimeBasedTriggeringPolicy

时,自动删除旧日志文件似乎不起作用

0
投票

查看此处 https://logging.apache.org/log4j/log4j-2.7/manual/appenders.html 您可以在

Delete
 中使用 
DefaultRolloverStrategy

策略

它的伟大之处在于,您可以使用逻辑

and
or
来确定何时应删除日志。

这是我的样本:

    <RollingFile name="RLog" fileName="logpath/apps.log" filePattern="%d{yyyyMMdd-HH}-apps-%i.log">
        <PatternLayout pattern="%d{YYYY-MM-dd HH:mm:ss} [%-5level] %t - %c: %msg%n" />
        <Policies>
            <OnStartupTriggeringPolicy />
            <SizeBasedTriggeringPolicy size="20MB" />
        </Policies>
        <DefaultRolloverStrategy max="2">
            <Delete basePath="logpath" maxDepth="2">
                <IfFileName glob="*">
                <!-- Deletes log files older that match any of the conditions below. -->
                    <IfAny>
                        <IfAccumulatedFileCount exceeds="50" />
                        <IfLastModified age="P30D" />
                        <IfAccumulatedFileSize  exceeds="1GB" />
                    </IfAny>
                </IfFileName>
            </Delete>
        </DefaultRolloverStrategy>
    </RollingFile>

如果您查看上面的内容,它将删除基本

logpath
目录中满足以下条件的
any
的任何文件,这些条件是:

  • 文件总数超过 50 OR
  • 如果文件已存在至少 30 天 OR
  • 所有日志的文件总大小超过1GB
© www.soinside.com 2019 - 2024. All rights reserved.