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

标签 java logging logback apache-commons-config

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

最佳答案

方法一:从不同文件加载

您可以保存两个不同的配置文件,并在应用程序启动时使用 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、文件和 URL。

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

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

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

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

关于java - 如何在运行时设置 logback 配置文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30939814/

相关文章:

java - PrintWriter——没有输出?

c - 在 C 中记录错误

spring-boot - 带有 Spring Boot 应用程序的 logack 中的 is_undefined 目录错误

Java Spring Boot 登录

java - 在java中使用套接字向服务器发送请求

java - 在 JavaFX 中使用枚举类填充组合框?

ruby - Rspec 无法检查记录器信息输出

spring - 你能解释一下这个Spring环境变量解析吗?

java - 是否有用于数据完整性验证的标准 DSL?

logging - 是否可以在 Nginx 上指定自定义错误日志格式?