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