我找到了几个编程配置的例子,但没有一个提到异步日志记录。 如何配置log4j 2以使所有记录器异步? 需要明确的是:我无法通过设置System属性来实现。我需要的是这样的:How to configure log4j 2.x purely programmatically?
答案 0 :(得分:2)
如果您不能使用系统属性和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[]{"*"};
}
}
希望这会有所帮助: - )