使用ConfigurationBuilder以编程方式配置Log4j2

时间:2016-09-30 10:40:45

标签: log4j2

我正在使用Log4j2 2.6.2。在应用程序的开头,我正在调用以下代码

ConfigurationBuilder< BuiltConfiguration > builder = ConfigurationBuilderFactory.newConfigurationBuilder();
builder.setStatusLevel( Level.ERROR );
builder.setConfigurationName("OverrideDefaultConsoleLayout");
AppenderComponentBuilder appenderBuilder = builder.newAppender("Stdout", "CONSOLE").addAttribute("target", ConsoleAppender.Target.SYSTEM_OUT);
appenderBuilder.add(builder.newLayout("PatternLayout").addAttribute("pattern", "%% %msg%n"));       
builder.add(appenderBuilder);
builder.add(builder.newLogger("Log4j2Test", Level.DEBUG).add(builder.newAppenderRef("Stdout")).addAttribute("additivity", false));
builder.add(builder.newRootLogger(Level.DEBUG).add(builder.newAppenderRef("Stdout")));
Configurator.initialize(builder.build());
LogManager.getLogger("Log4j2Test").error("Output % followed by this message");

我参考了以下文档:http://logging.apache.org/log4j/2.x/manual/customconfig.html

我的目标是以编程方式配置Log4j2。作为试用版,我试图覆盖控制台Appender的默认布局。

应用程序无法使用配置文件(.properties,.xml)。因此,在启动时,将显示以下消息。

ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console. 

输出显示为

15:43:50.865 [main] ERROR Log4j2Test - Output % followed by this message

即。默认布局正在使用中。我的默认程序覆盖不起作用。任何人都可以帮助纠正代码吗?

1 个答案:

答案 0 :(得分:1)

只是调用您显示的代码可能无效。它需要编码为扩展ConfigurationFactory的类,并使用@Plugin进行注释,以便Log4j可以发现它并使用它而不是查找配置文件。

您链接到的Log4j手册页上的示例代码显示了如何执行此操作。

相关问题