当前位置: 首页 > 面试题库 >

Log4j2-配置RolloverStrategy以删除旧的日志文件

齐振
2023-03-14
问题内容

我正在尝试将 log4j 配置为仅保留指定数量的备份文件或保留不超过一定年龄的文件。最终,我希望有 时间(每天)基于触发策略,
并保留30个备份文件或删除早于30天的文件。

经过一些研究后,我了解到在使用 时间策略
时无法指定备份文件的最大数量,但是遇到了这个问题https://issues.apache.org/jira/browse/LOG4J2-435和此文档片段http:
//logging.apache.org/log4j/2.x/manual/appenders.html#CustomDeleteOnRollover,其中介绍了如何根据文件的年龄和名称格式删除文件。现在,我尝试在一个简单的示例中应用此配置,该配置将每分钟创建一个新的备份文件,并会自动删除早于3分钟的文件。为此,我使用以下pom创建了一个简单的maven项目:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>test</groupId>
    <artifactId>test</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.5</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <executions>
                    <execution>
                        <id>copy-dependencies</id>
                        <phase>prepare-package</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${project.build.directory}/lib</outputDirectory>
                            <overWriteReleases>false</overWriteReleases>
                            <overWriteSnapshots>false</overWriteSnapshots>
                            <overWriteIfNewer>true</overWriteIfNewer>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                            <classpathPrefix>lib/</classpathPrefix>
                            <mainClass>test.Main</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

log4j2.xml配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn" name="MyApp" packages="">
    <Appenders>
        <RollingFile name="RollingFile" fileName="D:/app.log"
                     filePattern="D:/app-%d{yyyy-MM-dd-HH-mm-ss}.log">
            <PatternLayout>
                <Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
            </PatternLayout>
            <Policies>
                <TimeBasedTriggeringPolicy interval="60" modulate="true"/>
                <!--<SizeBasedTriggeringPolicy size="250 MB"/>-->
            </Policies>
            <DefaultRolloverStrategy>
                <Delete basePath="D:" maxDepth="1">
                    <IfFileName glob="app-*.log" />
                    <IfLastModified age="3m" />
                </Delete>
            </DefaultRolloverStrategy>
        </RollingFile>
    </Appenders>
    <Loggers>
        <Root level="trace">
            <AppenderRef ref="RollingFile"/>
        </Root>
    </Loggers>
</Configuration>

和主类:

package test;


import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * Created by mzurawski on 2015-12-22.
 */
public class Main {

    final static Logger logger = LogManager.getLogger(Main.class);

    public static void main(String[] args) {
        runMe("test");
    }

    private static void runMe(String parameterParam){
        String parameter;
        for(int i=0; i<100; ++i) {
            parameter = parameterParam + i;
            System.out.println("log iteration: "+i);
            if (logger.isDebugEnabled()) {
                logger.debug("This is debug : " + parameter);
            }

            if (logger.isInfoEnabled()) {
                logger.info("This is info : " + parameter);
            }

            logger.warn("This is warn : " + parameter);
            logger.error("This is error : " + parameter);
            logger.fatal("This is fatal : " + parameter);
            try {
                Thread.sleep(60000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

构建此程序后,可以使用以下命令运行它(请注意硬编码的光盘位置):

java -jar test-1.0-SNAPSHOT.jar

到目前为止,每分钟都会创建一个日志文件,但是不会删除任何旧文件。如何使该测试配置正常工作?我应该如何修改此配置,以便最终仅保留最近30天的文件?

谢谢你的帮助。


问题答案:

您的配置和测试程序看起来不错。我测试了Main.java和log4j2.xml配置,它按预期工作:触发翻转的每一分钟,“删除”操作都会扫描基本目录,仅删除3分钟之前的文件。

我没有创建独立的应用程序,而是在IDE中进行了测试。(看起来您正在将log4j jar文件以及您的类和配置着色到单个jar中。这可能会引起问题吗?)

通过将config更改为启用log4j内部日志记录后<Configuration status="TRACE" ...,我得到以下输出:

  • 迭代3:尚未删除任何文件:最早的文件为173秒。
  • 迭代4:删除最早的文件。

…(省略启动日志)…

log iteration: 3
2016-01-16 14:26:23,192 main TRACE PatternProcessor.getNextTime returning 2016/01/16-14:27:00.000, nextFileTime=2016/01/16-14:26:59.000, prevFileTime=2016/01/16-14:25:59.000, current=2016/01/16-14:26:23.192, freq=EVERY_SECOND
2016-01-16 14:26:23,193 main TRACE DefaultRolloverStrategy.purge() took 0.0 milliseconds
2016-01-16 14:26:23,194 main DEBUG RollingFileManager executing synchronous FileRenameAction[c:\temp\log\app.log to c:\temp\log\app-2016-01-16-14-25-59.log, renameEmptyFiles=false]
2016-01-16 14:26:23,198 main DEBUG RollingFileManager executing async CompositeAction[DeleteAction[basePath=c:\temp\log, options=[], maxDepth=1, conditions=[IfFileName(glob:app-*.log), IfLastModified(age=PT3M)]]]
2016-01-16 14:26:23,199 Log4j2-2 DEBUG Starting DeleteAction[basePath=c:\temp\log, options=[], maxDepth=1, conditions=[IfFileName(glob:app-*.log), IfLastModified(age=PT3M)]]
2016-01-16 14:26:23,200 Log4j2-2 DEBUG DeleteAction complete in 0.001186309 seconds
2016-01-16 14:26:23,201 Log4j2-2 TRACE Sorted paths:
2016-01-16 14:26:23,201 Log4j2-2 TRACE c:\temp\log\app.log (modified: 2016-01-16T05:26:23.199631Z)
2016-01-16 14:26:23,201 Log4j2-2 TRACE c:\temp\log\app-2016-01-16-14-25-59.log (modified: 2016-01-16T05:25:30.832634Z)
2016-01-16 14:26:23,203 Log4j2-2 TRACE c:\temp\log\app-2016-01-16-14-24-59.log (modified: 2016-01-16T05:25:23.188525Z)
2016-01-16 14:26:23,203 Log4j2-2 TRACE c:\temp\log\app-2016-01-16-14-23-59.log (modified: 2016-01-16T05:23:29.466887Z)
2016-01-16 14:26:23,204 Log4j2-2 TRACE IfFileName REJECTED: 'glob:app-*.log' does not match relative path 'app.log'
2016-01-16 14:26:23,204 Log4j2-2 TRACE Not deleting base=c:\temp\log, relative=app.log
2016-01-16 14:26:23,205 Log4j2-2 TRACE IfFileName ACCEPTED: 'glob:app-*.log' matches relative path 'app-2016-01-16-14-25-59.log'
2016-01-16 14:26:23,205 Log4j2-2 TRACE IfLastModified REJECTED: app-2016-01-16-14-25-59.log ageMillis '52373' < 'PT3M'
2016-01-16 14:26:23,205 Log4j2-2 TRACE Not deleting base=c:\temp\log, relative=app-2016-01-16-14-25-59.log
2016-01-16 14:26:23,206 Log4j2-2 TRACE IfFileName ACCEPTED: 'glob:app-*.log' matches relative path 'app-2016-01-16-14-24-59.log'
2016-01-16 14:26:23,206 Log4j2-2 TRACE IfLastModified REJECTED: app-2016-01-16-14-24-59.log ageMillis '60018' < 'PT3M'
2016-01-16 14:26:23,206 Log4j2-2 TRACE Not deleting base=c:\temp\log, relative=app-2016-01-16-14-24-59.log
2016-01-16 14:26:23,206 Log4j2-2 TRACE IfFileName ACCEPTED: 'glob:app-*.log' matches relative path 'app-2016-01-16-14-23-59.log'
2016-01-16 14:26:23,207 Log4j2-2 TRACE IfLastModified REJECTED: app-2016-01-16-14-23-59.log ageMillis '173740' < 'PT3M'
2016-01-16 14:26:23,207 Log4j2-2 TRACE Not deleting base=c:\temp\log, relative=app-2016-01-16-14-23-59.log
log iteration: 4
2016-01-16 14:27:23,200 main TRACE PatternProcessor.getNextTime returning 2016/01/16-14:28:00.000, nextFileTime=2016/01/16-14:27:59.000, prevFileTime=2016/01/16-14:26:59.000, current=2016/01/16-14:27:23.200, freq=EVERY_SECOND
2016-01-16 14:27:23,201 main TRACE DefaultRolloverStrategy.purge() took 0.0 milliseconds
2016-01-16 14:27:23,202 main DEBUG RollingFileManager executing synchronous FileRenameAction[c:\temp\log\app.log to c:\temp\log\app-2016-01-16-14-26-59.log, renameEmptyFiles=false]
2016-01-16 14:27:23,204 main DEBUG RollingFileManager executing async CompositeAction[DeleteAction[basePath=c:\temp\log, options=[], maxDepth=1, conditions=[IfFileName(glob:app-*.log), IfLastModified(age=PT3M)]]]
2016-01-16 14:27:23,205 Log4j2-3 DEBUG Starting DeleteAction[basePath=c:\temp\log, options=[], maxDepth=1, conditions=[IfFileName(glob:app-*.log), IfLastModified(age=PT3M)]]
2016-01-16 14:27:23,207 Log4j2-3 DEBUG DeleteAction complete in 0.001230382 seconds
2016-01-16 14:27:23,207 Log4j2-3 TRACE Sorted paths:
2016-01-16 14:27:23,207 Log4j2-3 TRACE c:\temp\log\app.log (modified: 2016-01-16T05:27:23.20571Z)
2016-01-16 14:27:23,208 Log4j2-3 TRACE c:\temp\log\app-2016-01-16-14-26-59.log (modified: 2016-01-16T05:26:23.946671Z)
2016-01-16 14:27:23,208 Log4j2-3 TRACE c:\temp\log\app-2016-01-16-14-25-59.log (modified: 2016-01-16T05:25:30.832634Z)
2016-01-16 14:27:23,209 Log4j2-3 TRACE c:\temp\log\app-2016-01-16-14-24-59.log (modified: 2016-01-16T05:25:23.188525Z)
2016-01-16 14:27:23,209 Log4j2-3 TRACE c:\temp\log\app-2016-01-16-14-23-59.log (modified: 2016-01-16T05:23:29.466887Z)
2016-01-16 14:27:23,210 Log4j2-3 TRACE IfFileName REJECTED: 'glob:app-*.log' does not match relative path 'app.log'
2016-01-16 14:27:23,210 Log4j2-3 TRACE Not deleting base=c:\temp\log, relative=app.log
2016-01-16 14:27:23,211 Log4j2-3 TRACE IfFileName ACCEPTED: 'glob:app-*.log' matches relative path 'app-2016-01-16-14-26-59.log'
2016-01-16 14:27:23,211 Log4j2-3 TRACE IfLastModified REJECTED: app-2016-01-16-14-26-59.log ageMillis '59265' < 'PT3M'
2016-01-16 14:27:23,211 Log4j2-3 TRACE Not deleting base=c:\temp\log, relative=app-2016-01-16-14-26-59.log
2016-01-16 14:27:23,212 Log4j2-3 TRACE IfFileName ACCEPTED: 'glob:app-*.log' matches relative path 'app-2016-01-16-14-25-59.log'
2016-01-16 14:27:23,212 Log4j2-3 TRACE IfLastModified REJECTED: app-2016-01-16-14-25-59.log ageMillis '112380' < 'PT3M'
2016-01-16 14:27:23,212 Log4j2-3 TRACE Not deleting base=c:\temp\log, relative=app-2016-01-16-14-25-59.log
2016-01-16 14:27:23,213 Log4j2-3 TRACE IfFileName ACCEPTED: 'glob:app-*.log' matches relative path 'app-2016-01-16-14-24-59.log'
2016-01-16 14:27:23,213 Log4j2-3 TRACE IfLastModified REJECTED: app-2016-01-16-14-24-59.log ageMillis '120025' < 'PT3M'
2016-01-16 14:27:23,213 Log4j2-3 TRACE Not deleting base=c:\temp\log, relative=app-2016-01-16-14-24-59.log
2016-01-16 14:27:23,214 Log4j2-3 TRACE IfFileName ACCEPTED: 'glob:app-*.log' matches relative path 'app-2016-01-16-14-23-59.log'
2016-01-16 14:27:23,214 Log4j2-3 TRACE IfLastModified ACCEPTED: app-2016-01-16-14-23-59.log ageMillis '233748' >= 'PT3M'
2016-01-16 14:27:23,214 Log4j2-3 TRACE Deleting c:\temp\log\app-2016-01-16-14-23-59.log

您可以启用状态日志记录并显示输出吗?



 类似资料:
  • 这是我的log4j2.yaml。现在,这个记录器在一天内创建一个文件,当这一天结束时,记录器将创建一个文件夹“归档”,并将旧的日志文件放在这个文件夹中。我需要删除7天前创建的所有旧日志。我做错了什么?请帮帮我

  • 我使用下面的log4j2。xml 我想要的是旧的日志文件被删除,如果累积的大小超过。但是log4j2首先删除最近修改的文件。https://logging.apache.org/log4j/2.x/manual/appenders.html说有一个路径排序参数可以做到这一点。有人能告诉我如何指定相反的将逻辑排序为默认值?

  • 我正在尝试以编程方式配置log4j2v2。11.1作为DefaultRolloverStrategy的一部分,使用新的删除操作删除旧文件。 正如您可以从下面的代码中看到的,我已将系统设置为每天创建日志文件,并在文件大小达到1MB时滚动该文件。 我尝试使用两个条件将删除操作添加到DefaultRolloverStrategy中—IfFileName和IfLastModified。IfFileName

  • (F.Y.I.我已经在互联网上搜索了很多文档。我正在使用storm-0.10.0-beta1。storm中log4j2的配置文件是worker.xml) 现在,我尝试使用log4j2。 我正在寻找删除旧日志的方法,但我找不到。部分配置如下。 起初,我期望删除超过3天的日志文件。 但事实上,事实并非如此。 所以,我想知道是否有办法删除旧日志。 如果有一条路我还没有找到,请通知我。

  • 我最近一直在使用log4j2,遇到了一个问题。发生翻转时,活动日志文件保留其日志。是否可以清除日志文件,以便滚动的文件将只保留日志在名称中指定的时间段?

  • 我在SpringBoot中使用logback,但无法删除旧的日志文件。 我在logback-spring.xml文件中定义了以下appender: 即使我设置了“MaxHistory”和“CleanHistoryonStart”,超过10天的日志文件也不会被删除。既不是翻转也不是启动。