Java LoggerModelHandler-class And Method Code Example
The logback.classic.model.LoggerModelHandler
class is used to handle the logger elements in the logback configuration file. It is responsible for creating LoggerModel instances and adding them to the ConfigurationModel based on the configuration. Here's an example of how you might use the LoggerModelHandler 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.model.LoggerModelHandler;
import ch.qos.logback.core.joran.spi.JoranException;
import ch.qos.logback.core.joran.spi.RuleStore;
public class MyApplication {
public static void main(String[] args) {
LoggerContext loggerContext = new LoggerContext();
ConfigurationModel configurationModel = new ConfigurationModel();
RuleStore rs = new RuleStore(loggerContext);
LoggerModelHandler loggerModelHandler = new LoggerModelHandler(loggerContext, configurationModel);
// Adding logger rules
rs.addRule(new ElementSelector("configuration/logger"), loggerModelHandler);
try {
// do parsing here
} catch (JoranException e) {
e.printStackTrace();
}
}
}
In this example, a LoggerContext, ConfigurationModel, and RuleStore are created. Then, we added the logger handler to the RuleStore, with the addRule(new ElementSelector("configuration/logger"), loggerModelHandler) line. This handler will be responsible for creating LoggerModel instances when a element is found in the configuration file, and adding them to the configurationModel.
After adding the logger handler, you can parse your configuration file and then use the install method of your ConfigurationModel or JoranConfigurator class to install the configuration to your logger context.
It is worth noting that this is just a sample, you need to have a logback.xml or logback-test.xml file in your classpath or configure it manually. Also, you can add different appenders, level, additivity and other options in LoggerModel,