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