gpt4 book ai didi

java - 如何分离 Log4j 配置?

转载 作者:行者123 更新时间:2023-12-04 10:49:26 25 4
gpt4 key购买 nike

我有一个程序,它有一个用 XML 编写的 log4j 配置。我正在尝试修改原始应用程序,并尝试改进以前的记录器配置。

由于我不能修改xml文件本身,我希望能够通过ConfigurationBuilderFactory生成一个新的配置,并将其与其他配置一起使用。唯一的问题是,我无法做到这一点。它似乎不想与两者一起工作。

我能做什么?

以下是我的代码,大大简化了:

/**
* Internally uses {@link org.apache.logging.log4j.Logger}
*/
public final class MyLogger {
private static final LoggerContext context;

static {
ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
{
builder.setStatusLevel(WARN);

AppenderComponentBuilder console = builder.newAppender("SysOut", "Console");
console.addAttribute(...);
console.add(builder.newLayout(...).addAttribute(...));
builder.add(console);

// ... more configuration below
}

context = Configurator.initialize(builder.build()); // only works if no previous config exists, but will not replace an old config
}
}

// later on...

context.getLogger("MyLogger"); // uses the xml config, not the one written above

最佳答案

要以编程方式使用 ConfigurationBuilder API 创建记录器,您可以引用以下代码。

它在 log4j2 环境中创建了一个记录器,并添加了一些布局和附加器定义:

public class Log4j2Logger {

int counter = 0;

LoggerContext ctx;

Configuration config;

Logger logger;

String loggerName = "testLogger";

String appenderName = "myAppender";

static String testMessage = "This is a Test Message";

public void log() {

final ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
final LoggerComponentBuilder loggerComp = builder.newLogger(loggerName, Level.ALL).addAttribute("additivity",
false);
builder.add(loggerComp);
config = builder.build();
ctx = Configurator.initialize(config);
config = ctx.getConfiguration();
ctx.start(config);
ctx.updateLoggers(config);

// To create/add the logger of the configuration specified above we can use the
// getLogger(..) method
logger = ctx.getLogger(loggerName);

// Now we need to attach an appender to the logger so that our messages could be
// logged
logger.addAppender(addConsoleAppender(ctx.getConfiguration(), appenderName));
while (counter < 10) {
logger.error(testMessage + counter);
counter++;
}

}

private Appender addConsoleAppender(Configuration config, String appenderName) {
Appender consoleAppender = ConsoleAppender.newBuilder().setConfiguration(config).setName(appenderName)
.withImmediateFlush(true).build();
consoleAppender.start();
return consoleAppender;
}

}

对于测试,您可以在任何测试类中进行以下操作:
Log4j2Logger testLogger = new Log4j2Logger();
testLogger.log();

此 API 可帮助您以强大的方式处理日志。

你可以 :
  • 使用您的配置创建多个记录器
  • 向其中添加多个 Appender。
  • 也配置它们。
  • 使用结束后删除记录器。
  • 也创建异步记录器。

  • PS:我用的是log4j2 2.12.1版本。

    关于java - 如何分离 Log4j 配置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59548893/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com