以编程方式更改Log4j 2.x的输出格式

时间:2017-03-14 15:52:34

标签: java logging log4j log4j2

我使用以下代码从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());

1 个答案:

答案 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()可确保在创建记录器时使用自定义配置。