【问题标题】:How to set logback configuration file at runtime?如何在运行时设置 logback 配置文件?
【发布时间】:2015-09-05 12:50:59
【问题描述】:

我想在我的暂存环境中有一个用于生产的 logback.xml 文件和另一个具有不同参数的文件。我的代码能够在运行时自动知道它是在生产还是运行时。有没有办法在运行时设置 logback 配置文件?

【问题讨论】:

  • 不!普通的旧 java。

标签: java logging logback apache-commons-config


【解决方案1】:

方法一:从不同文件加载

您可以保存两个不同的配置文件,并在应用程序启动时使用JoranConfiguratior#doConfigure 为特定环境加载文件。

http://logback.qos.ch/manual/configuration.html#joranDirectly。 示例代码也从那里获取并针对您的案例进行了修改:

public class MyApp3 {
  final static String STAGING_CONFIGURATION = "/path/to/staging.xml";
  final static String PRODUCTION_CONFIGURATION  = "/path/to/production.xml";

  final static Logger logger = LoggerFactory.getLogger(MyApp3.class);

  public static void main(String[] args) {
    // assume SLF4J is bound to logback in the current environment
    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();

    // determine environmental specific configuration path
    final String path = isProdcution() ?  PRODUCTION_CONFIGURATION : STAGING_CONFIGURATION;

    try {
      JoranConfigurator configurator = new JoranConfigurator();
      configurator.setContext(context);
      // Call context.reset() to clear any previous configuration, e.g. default 
      // configuration. For multi-step configuration, omit calling context.reset().
      context.reset(); 
      configurator.doConfigure(path);
    } catch (JoranException je) {
      // StatusPrinter will handle this
    }
    StatusPrinter.printInCaseOfErrorsOrWarnings(context);

    logger.info("Entering application.");

    Foo foo = new Foo();
    foo.doIt();
    logger.info("Exiting application.");
  }
}

当然,您获取正确文件名的代码可以根据您的需要进行调整。 此外,还有一些重载的 doConfigure 方法 (http://logback.qos.ch/apidocs/ch/qos/logback/core/joran/GenericConfigurator.html#doConfigure%28java.io.File%29) 也接受 InputStreams、Files 和 URL。

方法二:在一个文件中使用条件句

如果你可以使用 logback 的内置属性或系统属性确定你的环境,你可以使用条件配置:

http://logback.qos.ch/manual/configuration.html#conditional

<!-- if-then form -->
<if condition="condition for your production">
    <then>
       ...
    </then>
    <else>
       ...
    </else>
</if>

【讨论】:

  • 感谢您的第二种方法,我不知道我们可以添加这种类型的条件。顺便说一句,您的第一个“”中有一个小错字... :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-26
  • 2016-12-08
  • 1970-01-01
  • 1970-01-01
  • 2012-06-30
  • 1970-01-01
  • 2011-01-28
相关资源
最近更新 更多