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