log4j2无法删除旧文件

时间:2017-12-20 21:21:14

标签: java logging log4j2

我到处寻找答案。在归档的文件数超过10之后,我必须删除文件。

这是我的log4j2.xml

  <?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn" name="MyApp" packages="">
    <Appenders>
        <RollingFile name="RollingFile" fileName="C:/temp/logs/app.log"
            filePattern="C:/temp/logs/app.log.%i">
            <PatternLayout>
                <Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
            </PatternLayout>
            <Policies>
                <SizeBasedTriggeringPolicy size="1000 kb" />
            </Policies>
            <DefaultRolloverStrategy max="10">
                <Delete basePath="C:/temp/logs/" maxDepth="1">
                    <IfFileName glob="app*.log*">
                        <IfLastModified age="2m">
                            <IfAny>
                                <IfAccumulatedFileCount exceeds="11" />
                            </IfAny>
                        </IfLastModified>
                    </IfFileName>
                </Delete>
            </DefaultRolloverStrategy>
        </RollingFile>
    </Appenders>
    <Loggers>
        <Root level="trace">
            <AppenderRef ref="RollingFile" />
        </Root>
    </Loggers>
</Configuration>

但它不会删除文件夹中的所有文件。例如,在下面的屏幕截图中,它不会删除旧的日志文件:

logs

我已经完成了所有文档和大量讨论,但我无法解决这个问题。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

这是一个问题类似的问题,可能会对您要做的事情提供一些帮助= Log4j2 - Configure RolloverStrategy to delete old log files

评论应该解释删除下的每个条件会做什么。在您的示例中,如果您希望删除app-log-12-20 *,则需要删除IfLastModified或IfAccumulatedFileCount - 您将看到文件被删除

 <Configuration status="warn" name="MyApp" packages="">
<Appenders>
    <RollingFile name="RollingFile" fileName="C:/temp/logs/app.log"
        filePattern="C:/temp/logs/app.log.%i">
        <PatternLayout>
            <Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
        </PatternLayout>
        <Policies>
            <SizeBasedTriggeringPolicy size="1000 kb" />
        </Policies>
        <DefaultRolloverStrategy max="10">
            <Delete basePath="C:/temp/logs/" maxDepth="1">
                <IfAll> 

                    <!-- Looks for file names starting with app*.log*. Any file including app.log.1 will satisfy this condition. Could delete current log app.log -->
                    <IfFileName glob="app*.log*" />
                    <!-- Looks for files that are older than 2 mins --> 
                    <IfLastModified age="2m" />  
                     <!-- This means there need to be 11 fails that satisfy the above conditions, that i.e. their name is app*log* and have time stamp greater than 2 mins. Keeps the most recent files that satisfy the condition -->
                    <IfAccumulatedFileCount exceeds="11" /> 
                </IfAll>
            </Delete>
        </DefaultRolloverStrategy>
    </RollingFile>
</Appenders>
<Loggers>
    <Root level="trace">
        <AppenderRef ref="RollingFile" />
    </Root>
</Loggers>