Java LoggerContext-class And Method Code Example


Here is an example of how you can use the LoggerContext class from the logback.classic package:

import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.core.Appender;
import ch.qos.logback.core.spi.AppenderAttachable;
import ch.qos.logback.core.spi.AppenderAttachableImpl;
import org.slf4j.LoggerFactory;

public class MyClass {
  public static void main(String[] args) {
    // Get the logger
    Logger logger = (Logger) LoggerFactory.getLogger(MyClass.class);

    // Get the logger context
    LoggerContext context = logger.getLoggerContext();

    // Get the logger context name
    String contextName = context.getName();
    System.out.println(contextName);

    // Get the logger context status manager
    StatusManager statusManager = context.getStatusManager();

    // Add a status
    Status status = new InfoStatus("This is a test status message", logger);
    statusManager.add(status);

    // Get the logger context appender attachable
    AppenderAttachable<ILoggingEvent> appenderAttachable = logger.getAppenderAttachable();
    if (appenderAttachable instanceof AppenderAttachableImpl) {
      // Get the appenders
      List<Appender<ILoggingEvent>> appenders = ((AppenderAttachableImpl<ILoggingEvent>) appenderAttachable).getAppenders();
      for (Appender<ILoggingEvent> appender : appenders) {
        System.out.println(appender.getName());
      }
    }

    // Reset the logger context
    context.reset();
  }
}

The LoggerContext class is the central class in the logback package. It provides methods for config