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

时间:2017-03-31 16:13:08

标签: java log4j2

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

1 个答案:

答案 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[]{"*"};
  }
}

希望这会有所帮助: - )