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.
<configuration>
    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <file>/path/to/application.log</file>
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <root level="info">
        <appender-ref ref="FILE" />
    </root>
</configuration>
  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 {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext servletContext = sce.getServletContext();
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
        JoranConfigurator configurator = new JoranConfigurator();
        configurator.setContext(loggerContext);
        try {
            configurator.doConfigure(servletContext.getResource("/WEB-INF/logback.xml"));
        } catch (JoranException | IOException e) {
            e.printStackTrace();
        }
        StatusPrinter.printInCaseOfErrorsOrWarnings(loggerContext);
    }
    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        //no-op
    }
}
  1. Register the LogbackServletContainerInitializer class in the web.xml file of your web application.
<listener>
    <listener-class>com.example.LogbackServletContainerInitializer</listener-class>
</listener>

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.