Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 244
Yony Avatar asked Feb 16 '12 22:02

Yony


People also ask

How do I debug Logback configuration?

You can now use -Dlogback. debug=true to enable debugging of the logback setup. Unfortunately, there is no way to enable debugging via a System property. You have to use <configuration debug="true"> in the logback.

How do I use application properties in Logback xml?

xml , you can use <springProperty> to access properties from Spring's environment including those configured in application. properties . This is described in the documentation: The tag allows you to surface properties from the Spring Environment for use within Logback.

What is Appender in Logback?

The Logback architecture is comprised of three classes: Logger, Appender, and Layout. A Logger is a context for log messages. This is the class that applications interact with to create log messages. Appenders place log messages in their final destinations. A Logger can have more than one Appender.


2 Answers

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?

like image 145
Tomasz Nurkiewicz Avatar answered Sep 17 '22 15:09

Tomasz Nurkiewicz


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);
}
like image 39
sasha_trn Avatar answered Sep 19 '22 15:09

sasha_trn