Log4j2 DefaultRollover策略配置删除日志文件,但不删除空文件夹

8cdiaqws  于 2022-11-06  发布在  其他
关注(0)|答案(3)|浏览(1110)

我将log4j 2用于我的应用程序日志,我使用XML,下面的配置是针对日志的。我将日志存储在以当前日期命名的文件夹中。每天都会创建一个新文件夹,名称为“2018-11-15”,日志存储在其中。代码根据日志文件的大小和时间删除日志文件,但不会删除空文件夹(2018-11-15)这些文件从文件夹中删除后。

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn" name="MyApp" packages="">
  <Properties>
    <Property name="baseDir">logs</Property>
  </Properties>
  <Appenders>
    <RollingFile name="RollingFile" fileName="${baseDir}/app.log"
          filePattern="${baseDir}/$${date:yyyy-MM}/app-%d{yyyy-MM-dd-HH}-%i.log.gz">
      <PatternLayout pattern="%d %p %c{1.} [%t] %m%n" />
      <Policies>
        <TimeBasedTriggeringPolicy />
        <SizeBasedTriggeringPolicy size="250 MB"/>
      </Policies>
      <DefaultRolloverStrategy max="100">
        <!--
        Nested conditions: the inner condition is only evaluated on files
        for which the outer conditions are true.
        -->
        <Delete basePath="${baseDir}" maxDepth="2">
          <IfFileName glob="*/app-*.log.gz">
            <IfLastModified age="30d">
              <IfAny>
                <IfAccumulatedFileSize exceeds="100 GB" />
                <IfAccumulatedFileCount exceeds="10" />
              </IfAny>
            </IfLastModified>
          </IfFileName>
        </Delete>
      </DefaultRolloverStrategy>
    </RollingFile>
  </Appenders>
  <Loggers>
    <Root level="error">
      <AppenderRef ref="RollingFile"/>
    </Root>
  </Loggers>
</Configuration>

我如何删除文件夹,一旦它里面的所有文件都被删除?Thanx!

zy1mlcev

zy1mlcev1#

我遇到了相同的问题/客户要求,并通过以下方式解决了该问题:

<RollingRandomAccessFile name="ROLLING_TEXT_FILE_APPENDER" fileName="${sys:ehr.logDir}/ehr.log"
                             filePattern="${sys:ehr.logDir}/$${date:yyyy-MM}/ehr-%d{yyyy-MM-dd-HH}-%i.log.gz">
        <PatternLayout pattern="%d %p [%t(%T)] %c{-3} - %m%n" />
        <Policies>
            <SizeBasedTriggeringPolicy size="50MB"/>
            <TimeBasedTriggeringPolicy />
        </Policies>
        <DefaultRolloverStrategy>
            <Delete basePath="${sys:ehr.logDir}" maxDepth="2">
                <IfFileName glob="*/ehr-*.log.gz" />
                <IfLastModified age="30d" />
            </Delete>
            <Delete basePath="${sys:ehr.logDir}" maxDepth="2">
                <ScriptCondition>
                    <Script name="GroovyCondition" language="groovy"><![CDATA[
                        import java.nio.file.*
                        import java.nio.file.attribute.BasicFileAttributes;
                        import org.apache.logging.log4j.core.appender.rolling.action.PathWithAttributes;

                        List<PathWithAttributes> result = new ArrayList<PathWithAttributes>();

                        statusLogger.trace 'SCRIPT: Checking for empty folders in base path: ' + basePath
                        Files.list(basePath).filter(p -> p.toFile().isDirectory()).forEach(p ->{
                            statusLogger.trace 'SCRIPT: Testing if folder is empty: ' + p
                            try(DirectoryStream<Path> dirStream = Files.newDirectoryStream(p)) {
                                // is directory empty?
                                if (!dirStream.iterator().hasNext()) {
                                    statusLogger.trace 'SCRIPT: Returning empty folder for deletion: ' + p
                                    BasicFileAttributes attributes = Files.readAttributes(p, BasicFileAttributes.class);
                                    result.add(new PathWithAttributes(p, attributes));
                                }
                            }
                        })

                        return result;
                    ]]>
                    </Script>
                </ScriptCondition>
            </Delete>
        </DefaultRolloverStrategy>
    </RollingRandomAccessFile>
kq4fsx7k

kq4fsx7k2#

你在log4j2中没有一个删除空文件夹的内置选项。你可以检查这个StackOverflow answer,和这个log4j2问题讨论。
我会说处理这个问题最简单的方法是不管log4j配置如何都运行一个cron。

mdfafbf1

mdfafbf13#

默认情况下,删除操作不会删除文件夹,即使文件夹是空的。如果您想根据文件夹的大小和年龄删除文件夹,您可以使用脚本来完成此操作,请参阅官方文档以获取帮助:http://logging.apache.org/log4j/2.x/manual/appenders.html#ScriptCondition
只需返回要从脚本中删除的文件夹。

相关问题