Java LogbackServletContextListener-class And Method Code Example

The LogbackServletContextListener class is a Servlet context listener that automatically configures logback when running inside a Servlet container. It's similar to LogbackServletContainerInitializer in function but with different method of registration.

Here's an example of how you could use the LogbackServletContextListener 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 LogbackServletContextListener 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 LogbackServletContextListener 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 LogbackServletContextListener class in the web.xml file of your web application.

When the servlet container starts, the contextInitialized method of your LogbackServletContextListener will be invoked and logback will be configured according to the settings specified in the logback.xml file. You also need to add logback classic library in the classpath to use this example, just like LogbackServletContainerInitializer