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

问题描述 投票:0回答:3

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

java logging logback
3个回答
15
投票

这是

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有一个内置的自动刷新功能吗?


15
投票

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

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

0
投票

这不适用于 logback 1.3.x/1.4.x,它会给出编译错误:

The method findURLOfDefaultConfigurationFile(boolean) is undefined for the type ContextInitializer

有人知道当前版本的 logback 会做什么吗?

© www.soinside.com 2019 - 2024. All rights reserved.