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