gpt4 book ai didi

java - 如何以编程方式将 log4j 2 配置为异步模式?

转载 作者:行者123 更新时间:2023-11-29 04:32:44 29 4
gpt4 key购买 nike

我找到了几个编程配置的示例,但没有一个提到异步日志记录。如何配置 log4j 2 以使所有记录器异步?明确一点:我无法通过设置系统属性来实现。我需要的是这样的:How to configure log4j 2.x purely programmatically?

最佳答案

如果您不能使用系统属性和 log4j2.component.properties 文件。您可以尝试使用 ConfigurationFactory.setConfigurationFactory 方法。

这是一个简单的例子:

Log4j2.java

public class Log4j2 {

static {
ConfigurationFactory.setConfigurationFactory(new CustomConfigurationFactory()); // This must be called before any other calls to Log4j
}

private static Logger logger = LogManager.getLogger();

public static void main(String[] args) {
logger.info("hello");
}
}

CustomConfigurationFactory.java

@Plugin(name = "CustomConfigurationFactory", category = ConfigurationFactory.CATEGORY)
@Order(50)
public class CustomConfigurationFactory extends ConfigurationFactory {

private static Configuration createConfiguration(final String name, ConfigurationBuilder<BuiltConfiguration> builder) {
builder.setConfigurationName(name);

AppenderComponentBuilder appenderBuilder = builder.newAppender("Stdout", "CONSOLE").
addAttribute("target", ConsoleAppender.Target.SYSTEM_OUT);
appenderBuilder.add(builder.newLayout("PatternLayout").
addAttribute("pattern", "%level: %msg%n"));
builder.add(appenderBuilder);

RootLoggerComponentBuilder rootLoggerBuilder = builder.newAsyncRootLogger(Level.DEBUG); // use newAsyncRootLogger instead of newRootLogger
rootLoggerBuilder.add(builder.newAppenderRef("Stdout"));

builder.add(rootLoggerBuilder);
return builder.build();
}

@Override
public Configuration getConfiguration(final LoggerContext loggerContext, final ConfigurationSource source) {
return getConfiguration(loggerContext, source.toString(), null);
}

@Override
public Configuration getConfiguration(final LoggerContext loggerContext, final String name, final URI configLocation) {
ConfigurationBuilder<BuiltConfiguration> builder = newConfigurationBuilder();
return createConfiguration(name, builder);
}

@Override
protected String[] getSupportedTypes() {
return new String[]{"*"};
}
}

希望这有帮助:-)

关于java - 如何以编程方式将 log4j 2 配置为异步模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43145250/

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