1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.logging.log4j.core.web;
18
19 import java.util.EnumSet;
20 import java.util.Set;
21 import javax.servlet.DispatcherType;
22 import javax.servlet.FilterRegistration;
23 import javax.servlet.ServletContainerInitializer;
24 import javax.servlet.ServletContext;
25 import javax.servlet.ServletException;
26
27
28
29
30
31
32 public class Log4jServletContainerInitializer implements ServletContainerInitializer {
33
34 @Override
35 public void onStartup(final Set<Class<?>> classes, final ServletContext servletContext) throws ServletException {
36 if (servletContext.getMajorVersion() > 2 && servletContext.getEffectiveMajorVersion() > 2 &&
37 !"true".equalsIgnoreCase(servletContext.getInitParameter(
38 Log4jWebSupport.IS_LOG4J_AUTO_INITIALIZATION_DISABLED
39 ))) {
40 servletContext.log("Log4jServletContainerInitializer starting up Log4j in Servlet 3.0+ environment.");
41
42 final FilterRegistration.Dynamic filter =
43 servletContext.addFilter("log4jServletFilter", Log4jServletFilter.class);
44 if (filter == null) {
45 servletContext.log("WARNING: In a Servlet 3.0+ application, you should not define a " +
46 "log4jServletFilter in web.xml. Log4j 2 normally does this for you automatically. Log4j 2 " +
47 "web auto-initialization has been canceled.");
48 return;
49 }
50
51 final Log4jWebInitializer initializer = Log4jWebInitializerImpl.getLog4jWebInitializer(servletContext);
52 initializer.initialize();
53 initializer.setLoggerContext();
54
55 servletContext.addListener(new Log4jServletContextListener());
56
57 filter.setAsyncSupported(true);
58 filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), false, "/*");
59 }
60 }
61 }