Java LogbackServletContainerInitializer-class And Method Code Example

The LogbackServletContainerInitializer class is used to automatically configure logback when running inside a Servlet 3.0 container.

Here's an example of how you could use the LogbackServletContainerInitializer in a web application:

  1. Create a logback.xml file in the WEB-INF directory of your web application, where you can specify your logback configuration.
    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>

    <root level="info">
        <appender-ref ref="FILE" />
  1. Create a LogbackServletContainerInitializer class which will be invoked during the Servlet container startup process to configure logback.
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;
import ch.qos.logback.core.util.StatusPrinter;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class LogbackServletContainerInitializer implements ServletContextListener {
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext servletContext = sce.getServletContext();
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
        JoranConfigurator configurator = new JoranConfigurator();
        try {
        } catch (JoranException | IOException e) {
    public void contextDestroyed(ServletContextEvent sce) {
  1. Register the LogbackServletContainerInitializer class in the web.xml file of your web application.

This way, when the servlet container starts, the contextInitialized method of your LogbackServletContainerInitializer will be invoked and logback will be configured according to the settings specified in the logback.xml file.

You need to add logback classic library in the classpath to use this example.