如何以编程方式将log4j 2配置为异步模式? [英] How to configure log4j 2 to asynchonous mode programmatically?

查看:43
本文介绍了如何以编程方式将log4j 2配置为异步模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经找到了一些编程配置的例子,但是都没有提到异步日志记录.如何配置log4j 2以使所有记录器异步?只是要清楚一点:我无法通过设置System属性来实现.我需要的是这样的:如何纯粹配置log4j 2.x以编程方式?

I've found several examples of programmatic configuration, but none of those mention asynchronous logging. How can I configure log4j 2 to make all loggers asynchronous? Just to be clear: I can't make it by setting the System property. What I need is something like this: How to configure log4j 2.x purely programmatically?

推荐答案

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

If you can't use system property and log4j2.component.properties file. You can try the ConfigurationFactory.setConfigurationFactory method.

这是一个简短的示例:

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

希望这会有所帮助:-)

Hope this helps :-)

这篇关于如何以编程方式将log4j 2配置为异步模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆