使用log4j2配置构建器在启动后初始化记录器

时间:2017-06-14 19:59:14

标签: log4j2

我使用ConfigurationBuilder创建了一个自定义log4j配置,并希望初始化此配置并在之后开始使用log4j,而在项目初始化时没有配置文件...

根据重新配置Log4j使用ConfigurationBuilder和Configurator 下的这个页面,它说 -

n >= 2

所以这应该是可能的。

这是我的代码 - 它几乎与在该页面上进行一些调整完全相同 -

An alternative to a custom ConfigurationFactory is to configure with the Configurator. Once a Configuration object has been constructed, it can be passed to one of the Configurator.initialize methods to set up the Log4j configuration. Using the Configurator in this manner allows the application control over when Log4j is initialized. However, should any logging be attempted before Configurator.initialize() is called then the default configuration will be used for those log events.

但是,当我调用该代码,然后立即执行日志语句时,我收到错误 -

ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();

        builder.setStatusLevel(DEBUG);
        builder.setConfigurationName("RollingBuilder");
        //create a console appender
        AppenderComponentBuilder appenderBuilder = builder.newAppender("Stdout", "CONSOLE")
                .addAttribute("target", ConsoleAppender.Target.SYSTEM_OUT);
        appenderBuilder.add(builder.newLayout("PatternLayout"))
                .addAttribute("pattern", "%d{dd/MMM/yyyy HH:mm:ss,SSS}- %c{1}: %m%n");
        builder.add(appenderBuilder);
        //create a rolling file appender
        LayoutComponentBuilder layoutBuilder = builder.newLayout("PatternLayout")
                .addAttribute("pattern", "%d [%t] %-5level: %msg%n");
        ComponentBuilder triggeringPolicy = builder.newComponent("Policies")
                .addComponent(builder.newComponent("TimeBasedTriggeringPolicy")
                        .addAttribute("interval", "1")
                        .addAttribute("modulate", "true"));
        ComponentBuilder rolloverStrategy = builder.newComponent("DefaultRolloverStrategy")
                .addAttribute("max", "4");
        appenderBuilder = builder.newAppender("RollingFile", "RollingFile")
                .addAttribute("fileName", "logs/app-info.log")
                .addAttribute("filePattern", "logs/app-info-%d{yyyy-MM-dd}--%i.log")
                .add(layoutBuilder)
                .addComponent(triggeringPolicy)
                .addComponent(rolloverStrategy);
        builder.add(appenderBuilder);
        //create a new logger
        builder.add(builder.newLogger("root", Level.DEBUG)
                .add(builder.newAppenderRef("RollingFile"))
                .addAttribute("additivity", false));

        builder.add(builder.newRootLogger(Level.DEBUG)
                .add(builder.newAppenderRef("RollingFile")));
        LoggerContext ctx = Configurator.initialize(builder.build());

所以很明显它认为我没有配置文件...有谁知道如何让我的Logger识别我在代码中创建的配置文件?

2 个答案:

答案 0 :(得分:0)

来自Log4j 2 docs

以下是Log4j如何找到可用的ConfigurationFactories:

  1. 可以使用要使用的ConfigurationFactory的名称设置名为“log4j.configurationFactory”的系统属性。
  2. ConfigurationFactory.setConfigurationFactory(ConfigurationFactory) 可以使用ConfigurationFactory的实例调用 用过的。必须在对Log4j进行任何其他调用之前调用此方法。
  3. 可以将ConfigurationFactory实现添加到类路径中 并配置为“ConfigurationFactory”类别中的插件。 Order注释可用于指定相对优先级 找到多个适用的ConfigurationFactories时。
  4. 在测试中,我安排了这个:

    public class Log4j2Example {
    
        static {
            System.setProperty("log4j.configurationFactory", CustomConfigurationFactory.class.getName());
        }
        private static final Logger LOG = LogManager.getLogger(Log4j2Example.class);
    
        public static void main(String[] args) {
            LOG.debug("This Will Be Printed On Debug");
            LOG.info("This Will Be Printed On Info");
            LOG.warn("This Will Be Printed On Warn");
            LOG.error("This Will Be Printed On Error");
            LOG.fatal("This Will Be Printed On Fatal");
            LOG.info("Appending string: {}.", "Hello, World");
        }
    }
    

    实现了ConfigurationFactory:

    @Plugin(name = "CustomConfigurationFactory", category = ConfigurationFactory.CATEGORY)
    @Order(50)
    public class CustomConfigurationFactory extends ConfigurationFactory {
    ---8<----
    

    }

    如果在log4j2启动之前设置了log4j.configurationFactory属性的值,那就完成了。

答案 1 :(得分:0)

如果您更喜欢使用Configurator而不是自定义ConfigurationFactory,则必须确保在调用LogManager.getLogger(...)之前已应用了初始化。例如,您可以使用静态初始化块

public class MyApplication {

  public static final Logger log;

  static {
    createCustomConfiguration();
    log = LogManager.getLogger(MyApplication.class);
  }

  public static void createCustomConfiguration() {
    // your initialization code
  }

  public static void main(String[] args) {
    log.info("Log and roll!");

    // do stuff
  }
}