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