1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.logging.log4j.core.lookup;
18
19
20 import org.apache.logging.log4j.LogManager;
21 import org.apache.logging.log4j.core.LogEvent;
22 import org.apache.logging.log4j.core.LoggerContext;
23 import org.apache.logging.log4j.core.config.plugins.Plugin;
24 import org.apache.logging.log4j.core.impl.ContextAnchor;
25 import org.apache.logging.log4j.core.lookup.StrLookup;
26
27 import javax.servlet.ServletContext;
28
29
30 @Plugin(name = "web", category = "Lookup")
31 public class WebLookup implements StrLookup {
32 private static final String ATTR_PREFIX = "attr.";
33 private static final String INIT_PARAM_PREFIX = "initParam.";
34
35 protected ServletContext getServletContext() {
36 LoggerContext lc = ContextAnchor.THREAD_CONTEXT.get();
37 if (lc == null) {
38 lc = (LoggerContext) LogManager.getContext(false);
39 }
40 if (lc != null) {
41 Object obj = lc.getExternalContext();
42 return obj != null && obj instanceof ServletContext ? (ServletContext) obj : null;
43 }
44 return null;
45 }
46
47 @Override
48 public String lookup(String key) {
49 ServletContext ctx = getServletContext();
50 if (ctx == null) {
51 return null;
52 }
53
54 if (key.startsWith(ATTR_PREFIX)) {
55 String attrName = key.substring(ATTR_PREFIX.length());
56 Object attrValue = ctx.getAttribute(attrName);
57 return attrValue == null ? null : attrValue.toString();
58 }
59
60 if (key.startsWith(INIT_PARAM_PREFIX)) {
61 String paramName = key.substring(INIT_PARAM_PREFIX.length());
62 return ctx.getInitParameter(paramName);
63 }
64
65 if ("rootDir".equals(key)) {
66 String root = ctx.getRealPath("/");
67 if (root == null) {
68 String msg = "failed to resolve web:rootDir -- " +
69 "servlet container unable to translate virtual path " +
70 " to real path (probably not deployed as exploded";
71 throw new RuntimeException(msg);
72
73 }
74 return root;
75 }
76
77 if ("contextPath".equals(key)) {
78 return ctx.getContextPath();
79 }
80
81 if ("servletContextName".equals(key)) {
82 return ctx.getServletContextName();
83 }
84
85 if ("serverInfo".equals(key)) {
86 return ctx.getServerInfo();
87 }
88
89 if ("effectiveMajorVersion".equals(key)) {
90 return String.valueOf(ctx.getEffectiveMajorVersion());
91 }
92
93 if ("effectiveMinorVersion".equals(key)) {
94 return String.valueOf(ctx.getEffectiveMinorVersion());
95 }
96
97 if ("majorVersion".equals(key)) {
98 return String.valueOf(ctx.getMajorVersion());
99 }
100
101 if ("minorVersion".equals(key)) {
102 return String.valueOf(ctx.getMinorVersion());
103 }
104
105 if (ctx.getAttribute(key) != null) {
106 return ctx.getAttribute(key).toString();
107 }
108
109 if (ctx.getInitParameter(key) != null) {
110 return ctx.getInitParameter(key);
111 }
112
113 ctx.log(getClass().getName() + " unable to resolve key '" + key + "'");
114 return null;
115 }
116
117 @Override
118 public String lookup(LogEvent event, String key) {
119 return lookup(key);
120 }
121 }