Java Level-class And Method Code Example


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

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import org.slf4j.LoggerFactory;

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

    // Set the logger level to ERROR
    logger.setLevel(Level.ERROR);

    // Check if the logger is enabled for the DEBUG level
    boolean isDebugEnabled = logger.isDebugEnabled();
    System.out.println(isDebugEnabled);  // prints false

    // Check if the logger is enabled for the ERROR level
    boolean isErrorEnabled = logger.isErrorEnabled();
    System.out.println(isErrorEnabled);  // prints true

    // Log a message at the ERROR level
    logger.error("This is an error message");
  }
}

The Level class is an enumeration of log levels used by logback. It provides constants for the following log levels:

  • ALL: All levels including custom levels
  • TRACE: Tracing information
  • DEBUG: Debugging information
  • INFO: Informational messages
  • WARN: Warning messages
  • ERROR: Error messages
  • OFF: No logging

In this example, we use the setLevel method to set the logger level to ERROR and the isDebugEnabled and isErrorEnabled methods to check if the logger is enabled for the respective levels. We also use the error method to log a message at the ERROR level.