Java LevelChangePropagator-class And Method Code Example


Here is an example of using the LevelChangePropagator class from the logback-classic library in Java:

import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;
import ch.qos.logback.core.util.StatusPrinter;

public class LogbackExample {
    public static void main(String[] args) {
        LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
        try {
            JoranConfigurator configurator = new JoranConfigurator();
            configurator.setContext(context);
            context.reset();
            configurator.doConfigure("logback.xml");
        } catch (JoranException je) {
            StatusPrinter.printInCaseOfErrorsOrWarnings(context);
        }
        
        Logger rootLogger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
        LevelChangePropagator levelChangePropagator = new LevelChangePropagator();
        levelChangePropagator.setContext(context);
        levelChangePropagator.setResetJUL(true);
        context.addListener(levelChangePropagator);
        rootLogger.setLevel(Level.ERROR);
    }
}

This example uses the LevelChangePropagator class to change the level of the root logger to ERROR and propagate the level change to any logger wrapped by java.util.logging. The LevelChangePropagator class is a listener that can be added to a LoggerContext to propagate level changes to other loggers.

Here, it is assumed that you have a logback.xml configuration file in your classpath to configure the logback loggers.

The setResetJUL(true) call tells the level change propagator to reset the level of loggers wrapped by java.util.logging.

Please note that this is a basic example, usually your logging configuration is more complex. This example just aims to show one possible usage of LevelChangePropagator class.