如何以编程方式告诉Logback重新加载配置

Yon*_*ony 16 java logging logback

我知道有一个reloadDefaultConfiguration()jmx操作,但是没有得到MBean的实例并调用此操作,是否有一个Logback api来重新加载默认配置(可选择指定一个日志配置文件路径)?

Tom*_*icz 13

这是源代码JMXConfigurator.reloadDefaultConfiguration():

public void reloadDefaultConfiguration() throws JoranException {
  ContextInitializer ci = new ContextInitializer(loggerContext);
  URL url = ci.findURLOfDefaultConfigurationFile(true);
  loggerContext.reset();
  ci.configureByResource(url);
}
Run Code Online (Sandbox Code Playgroud)

如果只在您需要的地方运行此代码呢?

唯一的问题是loggerContext变量.您可以使用以下方式获取:

(LoggerContext)LoggerFactory.getILoggerFactory()
Run Code Online (Sandbox Code Playgroud)

不幸的是,它看起来不像有一个很好的API来做这个,那么提出一个问题呢?您是否也知道Logback具有内置的自动刷新功能?

  • 是的,考虑过使用自动刷新功能,但在除我的开发环境之外的任何环境中启用它似乎有点可怕 (2认同)

sas*_*trn 13

我为此目的使用了以下代码:

public static void reloadLogger() {
    LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();

    ContextInitializer ci = new ContextInitializer(loggerContext);
    URL url = ci.findURLOfDefaultConfigurationFile(true);

    try {
        JoranConfigurator configurator = new JoranConfigurator();
        configurator.setContext(loggerContext);
        loggerContext.reset();
        configurator.doConfigure(url);
    } catch (JoranException je) {
        // StatusPrinter will handle this
    }
    StatusPrinter.printInCaseOfErrorsOrWarnings(loggerContext);
}
Run Code Online (Sandbox Code Playgroud)