我正在寻找在已运行的应用程序中更改 log4j2 日期格式的可能性。我需要它用于用户可以在不同语言之间进行选择的客户端。根据他的选择,我想更改当前(仅作为示例)配置为的模式(布局)
<Console name="console" target="SYSTEM_OUT"><br/>
<PatternLayout pattern="%d{HH:mm:ss} [%t] %-5level %logger{36} - %msg%n" /><br/>
</Console>
有没有人有提示/线索如何做到这一点?我还找不到任何资源,因为 log4j 1 最常用....
最佳答案
我不确定这是正确的方法,因为 API 目前可能缺少此选项,但它对我有用:
XML:
<Configuration status="WARN">
<Appenders>
<Console name="console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="debug">
<AppenderRef ref="console"/>
</Root>
</Loggers>
</Configuration>
Java:
logger.info("hey!");
LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
Configuration conf = ctx.getConfiguration();
Appender console = conf.getAppenders().get("console"); // <-- your appender name
PatternLayout layout = (PatternLayout) console.getLayout();
layout.setConversionPattern("%d{HH:mm:ss} [%t] %-5level %logger{36} - %msg%n");
ctx.updateLoggers(conf);
logger.info("hey!");
结果:
14:02:00.343 [main] INFO test.Log4j2Sample - hey!
14:02:00 [main] INFO test.Log4j2Sample - hey!
关于java - 如何在正在运行的应用程序中更改 log4j2 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20042545/