如何在运行时设置logback配置文件?

poi*_*rez 10 java logging logback apache-commons-config

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

flo*_*flo 11

方法1:从不同的文件加载

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

请参阅http://logback.qos.ch/manual/configuration.html#joranDirectly.示例代码也取自那里并对您的案例进行了修改:

public class MyApp3 {
  final static String STAGING_CONFIGURATION = "/path/to/statging.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.");
  }
}
Run Code Online (Sandbox Code Playgroud)

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

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

如果您可以使用logbag的内置属性或系统属性来确定您的环境,则可以使用条件配置:

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

<!-- if-then form -->
<if condition="condition for your production">
    <then>
       ...
    </then>
    <else>
       ...
    </else>
</if>
Run Code Online (Sandbox Code Playgroud)