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