我知道有一个 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 可以做到这一点,提出一个 issue 怎么样?另外你知道Logback有一个内置的自动刷新功能吗?
我为此目的使用了以下代码:
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);
}
这不适用于 logback 1.3.x/1.4.x,它会给出编译错误:
The method findURLOfDefaultConfigurationFile(boolean) is undefined for the type ContextInitializer
有人知道当前版本的 logback 会做什么吗?