我使用以下代码从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());
答案 0 :(得分:1)
似乎工作正常。我在测试类(实例初始化器中的代码)中跟随:
{
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()
可确保在创建记录器时使用自定义配置。