Java ConfigurationModel-class And Method Code Example


Here's an example of how you might use the logback.classic.model.ConfigurationModel class in a Java application:

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.model.ConfigurationModel;
import ch.qos.logback.classic.model.LoggerModel;
import ch.qos.logback.classic.spi.LoggerContextListener;
import ch.qos.logback.core.Context;
import ch.qos.logback.core.joran.spi.JoranException;
import java.util.ArrayList;
import java.util.List;

public class MyApplication {
  public static void main(String[] args) {
    LoggerContext loggerContext = new LoggerContext();
    ConfigurationModel configurationModel = new ConfigurationModel();

    // Add a logger to the configuration model
    LoggerModel loggerModel = new LoggerModel();
    loggerModel.setLevel("DEBUG");
    loggerModel.setName("com.mycompany");
    configurationModel.addLogger(loggerModel);

    // Add a listener to the configuration model
    List<LoggerContextListener> listeners = new ArrayList<>();
    listeners.add(new MyLoggerContextListener());
    configurationModel.setListenerList(listeners);

    // Configure the logger context with the configuration model
    try {
        configurationModel.install(loggerContext);
    } catch (JoranException e) {
        e.printStackTrace();
    }
  }

  private static class MyLoggerContextListener implements LoggerContextListener {
    @Override
    public void onStart(LoggerContext context) {
        System.out.println("Logger context started");
    }

    @Override
    public void onReset(LoggerContext context) {
        System.out.println("Logger context reset");
    }

    @Override
    public void onStop(LoggerContext context) {
        System.out.println("Logger context stopped");
    }

    @Override
    public void onLevelChange(ch.qos.logback.classic.Logger logger, ch.qos.logback.classic.Level level) {
        System.out.println("Logger level changed for logger: " + logger.getName() + " to level: " + level.toString());
    }
  }
}

In this example, a LoggerContext and ConfigurationModel are created. Then we added LoggerModel to configuration model and set the level to DEBUG and the name of logger. In the next step, we added a LoggerContextListener to the configuration model and configured the logger context with the configuration model. When we run the application, it will start the logger context and the onStart() method of the MyLoggerContextListener class will be called.

This example is a basic example, you can add appenders, filters, Async appenders and much more on your LoggerModel.