View Javadoc
1   package ch.qos.logback.classic.servlet;
2   
3   import static ch.qos.logback.core.CoreConstants.DISABLE_SERVLET_CONTAINER_INITIALIZER_KEY;
4   
5   import java.util.Set;
6   
7   import javax.servlet.ServletContainerInitializer;
8   import javax.servlet.ServletContext;
9   import javax.servlet.ServletException;
10  
11  import ch.qos.logback.classic.util.StatusViaSLF4JLoggerFactory;
12  import ch.qos.logback.core.util.OptionHelper;
13  
14  /**
15   * Attaches a new instance of {@link LogbackServletContextListener} to the current web-applications {@link ServletContext}.
16   * 
17   * @author Ceki Gulcu
18   * @since 1.1.10
19   */
20  public class LogbackServletContainerInitializer implements ServletContainerInitializer {
21  
22      @Override
23      public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException {
24  
25          if (isDisabledByConfiguration(ctx)) {
26              StatusViaSLF4JLoggerFactory.addInfo("Due to deployment instructions will NOT register an instance of " + LogbackServletContextListener.class
27                              + " to the current web-app", this);
28  
29              return;
30          }
31  
32          StatusViaSLF4JLoggerFactory.addInfo("Adding an instance of  " + LogbackServletContextListener.class + " to the current web-app", this);
33          LogbackServletContextListener lscl = new LogbackServletContextListener();
34          ctx.addListener(lscl);
35      }
36  
37      /**
38       * Search for value of DISABLE_SERVLET_CONTAINER_INITIALIZER_KEY in the web-app first, then as a system property and 
39       * as an environment variable last.
40       *
41       * @param ctx
42       * @return True if value of DISABLE_SERVLET_CONTAINER_INITIALIZER_KEY is available and set to "true", false otherwise.
43       */
44      boolean isDisabledByConfiguration(ServletContext ctx) {
45          String disableAttributeStr = null;
46          Object disableAttribute = ctx.getInitParameter(DISABLE_SERVLET_CONTAINER_INITIALIZER_KEY);
47          if (disableAttribute instanceof String) {
48              disableAttributeStr = (String) disableAttribute;
49          }
50  
51          if (OptionHelper.isEmpty(disableAttributeStr)) {
52              disableAttributeStr = OptionHelper.getSystemProperty(DISABLE_SERVLET_CONTAINER_INITIALIZER_KEY);
53          }
54  
55          if (OptionHelper.isEmpty(disableAttributeStr)) {
56              disableAttributeStr = OptionHelper.getEnv(DISABLE_SERVLET_CONTAINER_INITIALIZER_KEY);
57          }
58  
59          if (OptionHelper.isEmpty(disableAttributeStr))
60              return false;
61  
62          return disableAttributeStr.equalsIgnoreCase("true");
63  
64      }
65  
66  }