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 jakarta.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 @Override
34 public String lookup(final LogEvent event, final String key) {
35 final ServletContext ctx = WebLoggerContextUtils.getServletContext();
36 if (ctx == null) {
37 return null;
38 }
39
40 if (key.startsWith(ATTR_PREFIX)) {
41 final String attrName = key.substring(ATTR_PREFIX.length());
42 final Object attrValue = ctx.getAttribute(attrName);
43 return attrValue == null ? null : attrValue.toString();
44 }
45
46 if (key.startsWith(INIT_PARAM_PREFIX)) {
47 final String paramName = key.substring(INIT_PARAM_PREFIX.length());
48 return ctx.getInitParameter(paramName);
49 }
50
51 if ("rootDir".equals(key)) {
52 final String root = ctx.getRealPath("/");
53 if (root == null) {
54 final String msg = "Failed to resolve web:rootDir -- " +
55 "servlet container unable to translate virtual path " +
56 " to real path (probably not deployed as exploded";
57 throw new IllegalStateException(msg);
58 }
59 return root;
60 }
61
62 if ("contextPathName".equals(key)) {
63 String path = ctx.getContextPath();
64 if (path.trim().contains("/")) {
65 String[] fields = path.split("/");
66 for (String field : fields) {
67 if (field.length() > 0) {
68 return field;
69 }
70 }
71 return null;
72 }
73 return ctx.getContextPath();
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 " + Strings.quote(key));
113 return null;
114 }
115 }