javalogginglogback

How do I programmatically tell Logback to Reload Configuration


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)?


Solution

  • 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?