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.Locale;
22  import java.util.Map;
23  
24  import org.apache.logging.log4j.Logger;
25  import org.apache.logging.log4j.core.LogEvent;
26  import org.apache.logging.log4j.core.config.ConfigurationAware;
27  import org.apache.logging.log4j.core.config.plugins.util.PluginManager;
28  import org.apache.logging.log4j.core.config.plugins.util.PluginType;
29  import org.apache.logging.log4j.core.net.JndiManager;
30  import org.apache.logging.log4j.core.util.Loader;
31  import org.apache.logging.log4j.core.util.ReflectionUtil;
32  import org.apache.logging.log4j.status.StatusLogger;
33  import org.apache.logging.log4j.util.Constants;
34  
35  /**
36   * Proxies all the other {@link StrLookup}s.
37   */
38  public class Interpolator extends AbstractConfigurationAwareLookup {
39  
40      private static final String LOOKUP_KEY_WEB = "web";
41  
42      private static final String LOOKUP_KEY_DOCKER = "docker";
43  
44      private static final String LOOKUP_KEY_JNDI = "jndi";
45  
46      private static final String LOOKUP_KEY_JVMRUNARGS = "jvmrunargs";
47  
48      private static final Logger LOGGER = StatusLogger.getLogger();
49  
50      /** Constant for the prefix separator. */
51      static final char PREFIX_SEPARATOR = ':';
52  
53      private final Map<String, StrLookup> strLookupMap = new HashMap<>();
54  
55      private final StrLookup defaultLookup;
56  
57      public Interpolator(final StrLookup defaultLookup) {
58          this(defaultLookup, null);
59      }
60  
61      /**
62       * Constructs an Interpolator using a given StrLookup and a list of packages to find Lookup plugins in.
63       *
64       * @param defaultLookup  the default StrLookup to use as a fallback
65       * @param pluginPackages a list of packages to scan for Lookup plugins
66       * @since 2.1
67       */
68      public Interpolator(final StrLookup defaultLookup, final List<String> pluginPackages) {
69          this.defaultLookup = defaultLookup == null ? new MapLookup(new HashMap<String, String>()) : defaultLookup;
70          final PluginManager manager = new PluginManager(CATEGORY);
71          manager.collectPlugins(pluginPackages);
72          final Map<String, PluginType<?>> plugins = manager.getPlugins();
73  
74          for (final Map.Entry<String, PluginType<?>> entry : plugins.entrySet()) {
75              try {
76                  final Class<? extends StrLookup> clazz = entry.getValue().getPluginClass().asSubclass(StrLookup.class);
77                  if (!clazz.getName().equals("org.apache.logging.log4j.core.lookup.JndiLookup") || JndiManager.isJndiLookupEnabled()) {
78                      strLookupMap.put(entry.getKey().toLowerCase(), ReflectionUtil.instantiate(clazz));
79                  }
80              } catch (final Throwable t) {
81                  handleError(entry.getKey(), t);
82              }
83          }
84      }
85  
86      /**
87       * Create the default Interpolator using only Lookups that work without an event.
88       */
89      public Interpolator() {
90          this((Map<String, String>) null);
91      }
92  
93      /**
94       * Creates the Interpolator using only Lookups that work without an event and initial properties.
95       */
96      public Interpolator(final Map<String, String> properties) {
97          this.defaultLookup = new MapLookup(properties == null ? new HashMap<String, String>() : properties);
98          // TODO: this ought to use the PluginManager
99          strLookupMap.put("log4j", new Log4jLookup());
100         strLookupMap.put("sys", new SystemPropertiesLookup());
101         strLookupMap.put("env", new EnvironmentLookup());
102         strLookupMap.put("main", MainMapLookup.MAIN_SINGLETON);
103         strLookupMap.put("marker", new MarkerLookup());
104         strLookupMap.put("java", new JavaLookup());
105         // JNDI
106         if (JndiManager.isJndiLookupEnabled()) {
107             try {
108                 // [LOG4J2-703] We might be on Android
109                 strLookupMap.put(LOOKUP_KEY_JNDI,
110                         Loader.newCheckedInstanceOf("org.apache.logging.log4j.core.lookup.JndiLookup", StrLookup.class));
111             } catch (final LinkageError | Exception e) {
112                 handleError(LOOKUP_KEY_JNDI, e);
113             }
114         }
115         // JMX input args
116         try {
117             // We might be on Android
118             strLookupMap.put(LOOKUP_KEY_JVMRUNARGS,
119                 Loader.newCheckedInstanceOf("org.apache.logging.log4j.core.lookup.JmxRuntimeInputArgumentsLookup",
120                         StrLookup.class));
121         } catch (final LinkageError | Exception e) {
122             handleError(LOOKUP_KEY_JVMRUNARGS, e);
123         }
124         strLookupMap.put("date", new DateLookup());
125         strLookupMap.put("ctx", new ContextMapLookup());
126         if (Constants.IS_WEB_APP) {
127             try {
128                 strLookupMap.put(LOOKUP_KEY_WEB,
129                     Loader.newCheckedInstanceOf("org.apache.logging.log4j.web.WebLookup", StrLookup.class));
130             } catch (final Exception ignored) {
131                 handleError(LOOKUP_KEY_WEB, ignored);
132             }
133         } else {
134             LOGGER.debug("Not in a ServletContext environment, thus not loading WebLookup plugin.");
135         }
136         try {
137             strLookupMap.put(LOOKUP_KEY_DOCKER,
138                 Loader.newCheckedInstanceOf("org.apache.logging.log4j.docker.DockerLookup", StrLookup.class));
139         } catch (final Exception ignored) {
140             handleError(LOOKUP_KEY_DOCKER, ignored);
141         }
142     }
143 
144     public Map<String, StrLookup> getStrLookupMap() {
145         return strLookupMap;
146     }
147 
148     private void handleError(final String lookupKey, final Throwable t) {
149         switch (lookupKey) {
150             case LOOKUP_KEY_JNDI:
151                 // java.lang.VerifyError: org/apache/logging/log4j/core/lookup/JndiLookup
152                 LOGGER.warn( // LOG4J2-1582 don't print the whole stack trace (it is just a warning...)
153                         "JNDI lookup class is not available because this JRE does not support JNDI." +
154                         " JNDI string lookups will not be available, continuing configuration. Ignoring " + t);
155                 break;
156             case LOOKUP_KEY_JVMRUNARGS:
157                 // java.lang.VerifyError: org/apache/logging/log4j/core/lookup/JmxRuntimeInputArgumentsLookup
158                 LOGGER.warn(
159                         "JMX runtime input lookup class is not available because this JRE does not support JMX. " +
160                         "JMX lookups will not be available, continuing configuration. Ignoring " + t);
161                 break;
162             case LOOKUP_KEY_WEB:
163                 LOGGER.info("Log4j appears to be running in a Servlet environment, but there's no log4j-web module " +
164                         "available. If you want better web container support, please add the log4j-web JAR to your " +
165                         "web archive or server lib directory.");
166                 break;
167             case LOOKUP_KEY_DOCKER:
168                 break;
169             default:
170                 LOGGER.error("Unable to create Lookup for {}", lookupKey, t);
171         }
172     }
173 
174     /**
175      * Resolves the specified variable. This implementation will try to extract
176      * a variable prefix from the given variable name (the first colon (':') is
177      * used as prefix separator). It then passes the name of the variable with
178      * the prefix stripped to the lookup object registered for this prefix. If
179      * no prefix can be found or if the associated lookup object cannot resolve
180      * this variable, the default lookup object will be used.
181      *
182      * @param event The current LogEvent or null.
183      * @param var the name of the variable whose value is to be looked up
184      * @return the value of this variable or <b>null</b> if it cannot be
185      * resolved
186      */
187     @Override
188     public String lookup(final LogEvent event, String var) {
189         if (var == null) {
190             return null;
191         }
192 
193         final int prefixPos = var.indexOf(PREFIX_SEPARATOR);
194         if (prefixPos >= 0) {
195             final String prefix = var.substring(0, prefixPos).toLowerCase(Locale.US);
196             final String name = var.substring(prefixPos + 1);
197             final StrLookup lookup = strLookupMap.get(prefix);
198             if (lookup instanceof ConfigurationAware) {
199                 ((ConfigurationAware) lookup).setConfiguration(configuration);
200             }
201             String value = null;
202             if (lookup != null) {
203                 value = event == null ? lookup.lookup(name) : lookup.lookup(event, name);
204             }
205 
206             if (value != null) {
207                 return value;
208             }
209             var = var.substring(prefixPos + 1);
210         }
211         if (defaultLookup != null) {
212             return event == null ? defaultLookup.lookup(var) : defaultLookup.lookup(event, var);
213         }
214         return null;
215     }
216 
217     @Override
218     public String toString() {
219         final StringBuilder sb = new StringBuilder();
220         for (final String name : strLookupMap.keySet()) {
221             if (sb.length() == 0) {
222                 sb.append('{');
223             } else {
224                 sb.append(", ");
225             }
226 
227             sb.append(name);
228         }
229         if (sb.length() > 0) {
230             sb.append('}');
231         }
232         return sb.toString();
233     }
234 
235 }