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