Java PatternLayoutBase-class And Method Code Example


Here is an example of how to use the PatternLayoutBase class from the logback library to format log messages:

import ch.qos.logback.classic.PatternLayout;
import ch.qos.logback.classic.spi.ILoggingEvent;

public class MyApp {
    public static void main(String[] args) {
        // create a new PatternLayout
        PatternLayout layout = new PatternLayout();
        layout.setPattern("%d{yyyy-MM-dd HH:mm:ss} %-5level %logger{36} - %msg%n");

        // create a new logger
        Logger logger = LoggerFactory.getLogger("MyApp");

        // add the layout to the logger
        logger.addAppender(new ConsoleAppender<ILoggingEvent>(layout));

        // log some messages
        logger.debug("Debug message");
        logger.info("Info message");
        logger.warn("Warning message");
        logger.error("Error message");
    }
}

In this example, the setPattern method is used to set the layout pattern for the log messages. The pattern string "%d{yyyy-MM-dd HH:mm:ss} %-5level %logger{36} - %msg%n" specifies that the log messages should include the date and time, the log level, the logger name, and the log message, separated by a hyphen. The %n at the end specifies that each log message should be printed on a new line. You can customize the pattern string to format the log messages according to your needs.