启动后使用log4j2配置构建器初始化记录器 [英] using log4j2 configuration builder to initialize logger after startup

查看:505
本文介绍了启动后使用log4j2配置构建器初始化记录器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I created a custom log4j configuration using ConfigurationBuilder and want to initialize this configuration and start using log4j afterwards, in otherwards without having a configuration file when the project initializes...

根据此页面下的使用ConfigurationBuilder和Configurator重新配置Log4j ,它表示-

according to this page under Reconfigure Log4j Using ConfigurationBuilder with the Configurator, it says -

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.

所以这应该是可能的.

这是我的代码-几乎与该页面上的代码完全一样,但有一些调整-

This is my code - its almost exactly as it is on that page with a few adjustments -

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());

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

However, when I call that code, then do log statements right after, I get the error -

ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console. Set system property 'org.apache.logging.log4j.simplelog.StatusLogger.level' to TRACE to show Log4j2 internal initialization logging.

显然,它认为我没有配置文件...是否有人知道我如何让Logger识别我在代码中创建的此配置文件?

So obviously it thinks I dont have a configuration file... does anyone know how I can get my Logger to recognize this configuration file I created in code?

推荐答案

如果您更喜欢使用Configurator而不是自定义ConfigurationFactory,则必须确保在对.例如,您可以使用静态初始化块

If you prefer using the Configurator instead of using a custom ConfigurationFactory, you have to make sure that your initialization is applied before any call to LogManager.getLogger(...). For instance, you could use a static initialization block

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
  }
}

这篇关于启动后使用log4j2配置构建器初始化记录器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆