Log4j:如何以编程方式设置DefaultRolloverStrategy?

8tntrjer  于 2023-10-18  发布在  其他
关注(0)|答案(1)|浏览(138)

我使用下面的代码以编程方式设置我的Log4j配置。

private void initLog4JConfig() {
    if (!firstCall) {
        return;
    }

    Level logLevel = Level.INFO;
    String pattern = "%d{yyyy-MM-dd HH:mm:ss,SSS} | %-5p | %m%n";
    String fileName = GlobalData.getLogFileName();

    if (GlobalData.getDebugLevel() > 10) {
        logLevel = Level.DEBUG;
    }

    // console
    ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
    builder.setStatusLevel(logLevel);
    builder.setConfigurationName("DefaultLogger");

    AppenderComponentBuilder appenderBuilder
            = builder.newAppender("Console", "CONSOLE").addAttribute("target", ConsoleAppender.Target.SYSTEM_OUT);

    appenderBuilder.add(builder.newLayout("PatternLayout"))
            .addAttribute("pattern", pattern);
    RootLoggerComponentBuilder rootLogger = builder.newRootLogger(logLevel);
    rootLogger.add(builder.newAppenderRef("Console"));

    builder.add(appenderBuilder);
    builder.add(rootLogger);
    Configurator.reconfigure(builder.build());

    // rolling file
    ConfigurationBuilder<BuiltConfiguration> builder2 = ConfigurationBuilderFactory.newConfigurationBuilder();
    builder2.setStatusLevel(logLevel);
    builder2.setConfigurationName("DefaultRollingFileLogger");

    LayoutComponentBuilder layoutBuilder = builder2.newLayout("PatternLayout")
            .addAttribute("pattern", pattern);
    ComponentBuilder triggeringPolicy = builder2.newComponent("Policies")
            .addComponent(builder2.newComponent("SizeBasedTriggeringPolicy").addAttribute("size", "10KB"));
    ComponentBuilder filePolicy = builder2.newComponent("DefaultRolloverStrategy").addAttribute("max", 15);

    AppenderComponentBuilder appenderBuilder2 = builder2.newAppender("LogToRollingFile", "RollingFile")
            .addAttribute("fileName", fileName + ".log")
            .addAttribute("filePattern", fileName + "-%i.log.")
            .add(layoutBuilder)
            .addComponent(triggeringPolicy)
            .addComponent(filePolicy);

    builder2.add(appenderBuilder2);
    rootLogger.add(builder2.newAppenderRef("LogToRollingFile"));
    builder2.add(rootLogger);
    Configurator.reconfigure(builder2.build());
}

将SizeBasedTriggeringPolicy设置为10 KB(我使用一个较低的值进行测试)可以正常工作,但将DefaultRolloverStrategy设置为15个文件不起作用。我做错了什么?它只保留原始文件和第二个文件(-1.log)。
FYI:我使用Log4j 2.20.0和Java 8 u381。

0yycz8jy

0yycz8jy1#

我想通了。在filePattern的末尾有一个额外的点。去掉那个之后,它就像预期的那样工作了。
请注意原始问题和下面代码片段中的差异。

.addAttribute("filePattern", fileName + "-%i.log")

相关问题