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 javax.servlet.ServletContext;
20 import javax.servlet.ServletContextEvent;
21 import javax.servlet.ServletContextListener;
22
23 import org.apache.logging.log4j.core.LoggerContext;
24 import org.apache.logging.log4j.core.config.Configurator;
25 import org.apache.logging.log4j.core.lookup.Interpolator;
26 import org.apache.logging.log4j.core.lookup.StrLookup;
27 import org.apache.logging.log4j.core.lookup.StrSubstitutor;
28
29
30
31
32 public class Log4jContextListener implements ServletContextListener {
33
34
35
36
37 public static final String LOG4J_CONTEXT_ATTRIBUTE = "Log4jContext";
38
39
40
41
42 public static final String LOG4J_CONFIG = "log4jConfiguration";
43
44
45
46
47 public static final String LOG4J_CONTEXT_NAME = "log4jContextName";
48
49 private final StrSubstitutor subst = new StrSubstitutor(new Interpolator());
50
51
52
53
54
55 @Override
56 public void contextInitialized(final ServletContextEvent event) {
57 final ServletContext context = event.getServletContext();
58 final String locn = subst.replace(context.getInitParameter(LOG4J_CONFIG));
59 String name = subst.replace(context.getInitParameter(LOG4J_CONTEXT_NAME));
60 if (name == null) {
61 name = context.getServletContextName();
62 }
63 if (name == null && locn == null) {
64 context.log("No Log4j context configuration provided");
65 return;
66 }
67 context.setAttribute(LOG4J_CONTEXT_ATTRIBUTE, Configurator.initialize(name, getClassLoader(context), locn));
68 }
69
70
71
72
73
74 @Override
75 public void contextDestroyed(final ServletContextEvent event) {
76 final LoggerContext ctx = (LoggerContext) event.getServletContext().getAttribute(LOG4J_CONTEXT_ATTRIBUTE);
77 Configurator.shutdown(ctx);
78 }
79
80 private ClassLoader getClassLoader(final ServletContext context) {
81 try {
82
83 return (ClassLoader)context.getClass().getMethod("getClassLoader").invoke(context);
84 } catch (Exception ignore) {
85
86 return Log4jContextListener.class.getClassLoader();
87 }
88 }
89 }