How do I programmatically tell Logback to Reload Configuration

这一生的挚爱 提交于 2019-12-30 03:59:43

问题


I know there's a reloadDefaultConfiguration() jmx operation, but without getting an instance of MBean and invoking this operation, is there a Logback api to reload the default configuration (optionally specifying a log configuration file path)?


回答1:


This is the source code of JMXConfigurator.reloadDefaultConfiguration():

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

What about just running this code wherever you need it?

The only problem is the loggerContext variable. You can obtain it using:

(LoggerContext)LoggerFactory.getILoggerFactory()

Unfortunately it doesn't look like there is well-factored API to do this, what about raising an issue? Also are you aware that Logback has a built-in auto-refreshing feature?




回答2:


I used the following code for this purpose:

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);
}


来源:https://stackoverflow.com/questions/9320133/how-do-i-programmatically-tell-logback-to-reload-configuration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!