How do I programmatically tell Logback to Reload Configuration
Asked Answered
A

3

21

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

Arda answered 16/2, 2012 at 22:32 Comment(0)
Q
16

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?

Quickly answered 16/2, 2012 at 22:37 Comment(1)
Yea, thought about using the auto-refreshing feature but seams a bit scary to enable it on anything other than my dev environmentArda
E
15

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);
}
Etienne answered 16/1, 2013 at 8:42 Comment(3)
This doesn't handle configuring logback using a .groovy file ...throws org.xml.sax.SAXParseExceptionFortyfour
The groovy problem is annoying. I'm trying to restart my system mid-run, and I would like to reload the groovy file, since it puts the log files into a time-stamped directory.Nerissanerita
FYI this no longer works since logback 1.3 because of a breaking API change in LOGBACK-1655Fanti
S
0

With logback 1.5.x or later, the following should work

    var loggerCtx = (LoggerContext) LoggerFactory.getILoggerFactory();
    loggerCtx.reset();
    var ci =  new ContextInitializer(loggerCtx);
    ci.autoConfig();
Somebody answered 12/8, 2024 at 1:3 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.