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

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

这是JMXConfigurator.reloadDefaultConfiguration()的源代码:

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

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

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

 (LoggerContext)LoggerFactory.getILoggerFactory() 

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

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

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