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