我正在使用以下代码从manual配置Log4j。我想改变模式。无论我如何编辑pattern
属性,输出格式都保持不变。如何更改输出格式?我想将pattern
设置为%-5level: %msg%n%throwable
。
ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
builder.setStatusLevel(Level.ERROR);
builder.setConfigurationName("BuilderTest");
builder.add(builder.newFilter("ThresholdFilter", Filter.Result.ACCEPT, Filter.Result.NEUTRAL)
.addAttribute("level", Level.DEBUG));
AppenderComponentBuilder appenderBuilder = builder.newAppender("Stdout", "CONSOLE").addAttribute("target",
ConsoleAppender.Target.SYSTEM_OUT);
appenderBuilder.add(builder.newLayout("PatternLayout")
.addAttribute("pattern", "%d [%t] %-5level: %msg%n%throwable"));
appenderBuilder.add(builder.newFilter("MarkerFilter", Filter.Result.DENY, Filter.Result.NEUTRAL)
.addAttribute("marker", "FLOW"));
builder.add(appenderBuilder);
builder.add(builder.newLogger("org.apache.logging.log4j", Level.DEBUG)
.add(builder.newAppenderRef("Stdout")).addAttribute("additivity", false));
builder.add(builder.newRootLogger(Level.ERROR).add(builder.newAppenderRef("Stdout")));
ctx = Configurator.initialize(builder.build());
最佳答案
似乎工作正常。我在测试类中有以下内容(实例初始化程序中的代码):
{
ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
builder.setStatusLevel(Level.ERROR);
builder.setConfigurationName("BuilderTest");
builder.add(builder.newFilter("ThresholdFilter", Filter.Result.ACCEPT, Filter.Result.NEUTRAL).addAttribute("level", Level.DEBUG));
AppenderComponentBuilder appenderBuilder = builder.newAppender("Stdout", "CONSOLE").addAttribute("target", ConsoleAppender.Target.SYSTEM_OUT);
appenderBuilder.add(builder.newLayout("PatternLayout").addAttribute("pattern", "%d Thread:[%t] %-5level: MSG: %msg%n%throwable"));
appenderBuilder.add(builder.newFilter("MarkerFilter", Filter.Result.DENY, Filter.Result.NEUTRAL).addAttribute("marker", "FLOW"));
builder.add(appenderBuilder);
builder.add(builder.newLogger("org.apache.logging.log4j", Level.DEBUG).add(builder.newAppenderRef("Stdout")).addAttribute("additivity", false));
builder.add(builder.newRootLogger(Level.ERROR).add(builder.newAppenderRef("Stdout")));
Configurator.initialize(builder.build());
}
使用
Configurator.initialize()
确保将新建的配置用作新的默认配置,因此在创建Logger
时不必显式使用创建的上下文。@Test
public void testLogger() throws Exception {
Logger log = LogManager.getLogger("loggerName");
log.error("Error");
log.warn("Warning");
log.debug("Debug");
log.info("Info");
}
以上结果(请注意修改的模式):
2017-03-14 16:29:03,188 Thread:[main] ERROR: MSG:Error
2017-03-14 16:29:03,190 Thread:[main] WARN : MSG:Warning
2017-03-14 16:29:03,190 Thread:[main] DEBUG: MSG:Debug
2017-03-14 16:29:03,190 Thread:[main] INFO : MSG:Info
编辑:不必显式使用
LoggerContext.getLogger()
,常规的LogManager.getLogger()
可确保在创建记录器时使用自定义配置。