View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements. See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache license, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License. You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the license for the specific language governing permissions and
15   * limitations under the license.
16   */
17  package org.apache.logging.log4j.core.lookup;
18  
19  import java.util.HashMap;
20  import java.util.List;
21  import java.util.Map;
22  
23  import org.apache.logging.log4j.Logger;
24  import org.apache.logging.log4j.core.LogEvent;
25  import org.apache.logging.log4j.core.config.plugins.util.PluginManager;
26  import org.apache.logging.log4j.core.config.plugins.util.PluginType;
27  import org.apache.logging.log4j.core.util.Loader;
28  import org.apache.logging.log4j.core.util.ReflectionUtil;
29  import org.apache.logging.log4j.status.StatusLogger;
30  
31  /**
32   * Proxies all the other {@link StrLookup}s.
33   */
34  public class Interpolator extends AbstractLookup {
35  
36      private static final Logger LOGGER = StatusLogger.getLogger();
37  
38      /** Constant for the prefix separator. */
39      private static final char PREFIX_SEPARATOR = ':';
40  
41      private final Map<String, StrLookup> lookups = new HashMap<>();
42  
43      private final StrLookup defaultLookup;
44  
45      public Interpolator(final StrLookup defaultLookup) {
46          this(defaultLookup, null);
47      }
48  
49      /**
50       * Constructs an Interpolator using a given StrLookup and a list of packages to find Lookup plugins in.
51       *
52       * @param defaultLookup  the default StrLookup to use as a fallback
53       * @param pluginPackages a list of packages to scan for Lookup plugins
54       * @since 2.1
55       */
56      public Interpolator(final StrLookup defaultLookup, final List<String> pluginPackages) {
57          this.defaultLookup = defaultLookup == null ? new MapLookup(new HashMap<String, String>()) : defaultLookup;
58          final PluginManager manager = new PluginManager(CATEGORY);
59          manager.collectPlugins(pluginPackages);
60          final Map<String, PluginType<?>> plugins = manager.getPlugins();
61  
62          for (final Map.Entry<String, PluginType<?>> entry : plugins.entrySet()) {
63              try {
64                  final Class<? extends StrLookup> clazz = entry.getValue().getPluginClass().asSubclass(StrLookup.class);
65                  lookups.put(entry.getKey(), ReflectionUtil.instantiate(clazz));
66              } catch (final Exception ex) {
67                  LOGGER.error("Unable to create Lookup for {}", entry.getKey(), ex);
68              }
69          }
70      }
71  
72      /**
73       * Create the default Interpolator using only Lookups that work without an event.
74       */
75      public Interpolator() {
76          this((Map<String, String>) null);
77      }
78  
79      /**
80       * Creates the Interpolator using only Lookups that work without an event and initial properties.
81       */
82      public Interpolator(final Map<String, String> properties) {
83          this.defaultLookup = new MapLookup(properties == null ? new HashMap<String, String>() : properties);
84          // TODO: this ought to use the PluginManager
85          lookups.put("log4j", new Log4jLookup());
86          lookups.put("sys", new SystemPropertiesLookup());
87          lookups.put("env", new EnvironmentLookup());
88          lookups.put("main", MainMapLookup.MAIN_SINGLETON);
89          lookups.put("marker", new MarkerLookup());
90          lookups.put("java", new JavaLookup());
91          // JNDI
92          try {
93              // [LOG4J2-703] We might be on Android
94              lookups.put("jndi",
95                  Loader.newCheckedInstanceOf("org.apache.logging.log4j.core.lookup.JndiLookup", StrLookup.class));
96          } catch (final Throwable e) {
97              // java.lang.VerifyError: org/apache/logging/log4j/core/lookup/JndiLookup
98              LOGGER.warn(
99                      "JNDI lookup class is not available because this JRE does not support JNDI. JNDI string lookups will not be available, continuing configuration.",
100                     e);
101         }
102         // JMX input args
103         try {
104             // We might be on Android
105             lookups.put("jvmrunargs",
106                 Loader.newCheckedInstanceOf("org.apache.logging.log4j.core.lookup.JmxRuntimeInputArgumentsLookup", StrLookup.class));
107         } catch (final Throwable e) {
108             // java.lang.VerifyError: org/apache/logging/log4j/core/lookup/JmxRuntimeInputArgumentsLookup
109             LOGGER.warn(
110                     "JMX runtime input lookup class is not available because this JRE does not support JMX. JMX lookups will not be available, continuing configuration.",
111                     e);
112         }
113         lookups.put("date", new DateLookup());
114         lookups.put("ctx", new ContextMapLookup());
115         if (Loader.isClassAvailable("javax.servlet.ServletContext")) {
116             try {
117                 lookups.put("web",
118                     Loader.newCheckedInstanceOf("org.apache.logging.log4j.web.WebLookup", StrLookup.class));
119             } catch (final Exception ignored) {
120                 LOGGER.info("Log4j appears to be running in a Servlet environment, but there's no log4j-web module " +
121                     "available. If you want better web container support, please add the log4j-web JAR to your " +
122                     "web archive or server lib directory.");
123             }
124         } else {
125             LOGGER.debug("Not in a ServletContext environment, thus not loading WebLookup plugin.");
126         }
127     }
128 
129     /**
130      * Resolves the specified variable. This implementation will try to extract
131      * a variable prefix from the given variable name (the first colon (':') is
132      * used as prefix separator). It then passes the name of the variable with
133      * the prefix stripped to the lookup object registered for this prefix. If
134      * no prefix can be found or if the associated lookup object cannot resolve
135      * this variable, the default lookup object will be used.
136      *
137      * @param event The current LogEvent or null.
138      * @param var the name of the variable whose value is to be looked up
139      * @return the value of this variable or <b>null</b> if it cannot be
140      * resolved
141      */
142     @Override
143     public String lookup(final LogEvent event, String var) {
144         if (var == null) {
145             return null;
146         }
147 
148         final int prefixPos = var.indexOf(PREFIX_SEPARATOR);
149         if (prefixPos >= 0) {
150             final String prefix = var.substring(0, prefixPos);
151             final String name = var.substring(prefixPos + 1);
152             final StrLookup lookup = lookups.get(prefix);
153             String value = null;
154             if (lookup != null) {
155                 value = event == null ? lookup.lookup(name) : lookup.lookup(event, name);
156             }
157 
158             if (value != null) {
159                 return value;
160             }
161             var = var.substring(prefixPos + 1);
162         }
163         if (defaultLookup != null) {
164             return event == null ? defaultLookup.lookup(var) : defaultLookup.lookup(event, var);
165         }
166         return null;
167     }
168 
169     @Override
170     public String toString() {
171         final StringBuilder sb = new StringBuilder();
172         for (final String name : lookups.keySet()) {
173             if (sb.length() == 0) {
174                 sb.append('{');
175             } else {
176                 sb.append(", ");
177             }
178 
179             sb.append(name);
180         }
181         if (sb.length() > 0) {
182             sb.append('}');
183         }
184         return sb.toString();
185     }
186 }