001 /*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache license, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the license for the specific language governing permissions and
015 * limitations under the license.
016 */
017 package org.apache.logging.log4j.core.lookup;
018
019 import java.util.HashMap;
020 import java.util.List;
021 import java.util.Map;
022
023 import org.apache.logging.log4j.Logger;
024 import org.apache.logging.log4j.core.LogEvent;
025 import org.apache.logging.log4j.core.config.plugins.util.PluginManager;
026 import org.apache.logging.log4j.core.config.plugins.util.PluginType;
027 import org.apache.logging.log4j.core.util.Loader;
028 import org.apache.logging.log4j.core.util.ReflectionUtil;
029 import org.apache.logging.log4j.status.StatusLogger;
030
031 /**
032 * Proxies all the other {@link StrLookup}s.
033 */
034 public class Interpolator extends AbstractLookup {
035
036 private static final Logger LOGGER = StatusLogger.getLogger();
037
038 /** Constant for the prefix separator. */
039 private static final char PREFIX_SEPARATOR = ':';
040
041 private final Map<String, StrLookup> lookups = new HashMap<String, StrLookup>();
042
043 private final StrLookup defaultLookup;
044
045 public Interpolator(final StrLookup defaultLookup) {
046 this(defaultLookup, null);
047 }
048
049 /**
050 * Constructs an Interpolator using a given StrLookup and a list of packages to find Lookup plugins in.
051 *
052 * @param defaultLookup the default StrLookup to use as a fallback
053 * @param pluginPackages a list of packages to scan for Lookup plugins
054 * @since 2.1
055 */
056 public Interpolator(final StrLookup defaultLookup, final List<String> pluginPackages) {
057 this.defaultLookup = defaultLookup == null ? new MapLookup(new HashMap<String, String>()) : defaultLookup;
058 final PluginManager manager = new PluginManager(CATEGORY);
059 manager.collectPlugins(pluginPackages);
060 final Map<String, PluginType<?>> plugins = manager.getPlugins();
061
062 for (final Map.Entry<String, PluginType<?>> entry : plugins.entrySet()) {
063 try {
064 final Class<? extends StrLookup> clazz = entry.getValue().getPluginClass().asSubclass(StrLookup.class);
065 lookups.put(entry.getKey(), ReflectionUtil.instantiate(clazz));
066 } catch (final Exception ex) {
067 LOGGER.error("Unable to create Lookup for {}", entry.getKey(), ex);
068 }
069 }
070 }
071
072 /**
073 * Create the default Interpolator using only Lookups that work without an event.
074 */
075 public Interpolator() {
076 this((Map<String, String>) null);
077 }
078
079 /**
080 * Creates the Interpolator using only Lookups that work without an event and initial properties.
081 */
082 public Interpolator(final Map<String, String> properties) {
083 this.defaultLookup = new MapLookup(properties == null ? new HashMap<String, String>() : properties);
084 // TODO: this ought to use the PluginManager
085 lookups.put("sys", new SystemPropertiesLookup());
086 lookups.put("env", new EnvironmentLookup());
087 lookups.put("main", MapLookup.MAIN_SINGLETON);
088 lookups.put("java", new JavaLookup());
089 // JNDI
090 try {
091 // [LOG4J2-703] We might be on Android
092 lookups.put("jndi",
093 Loader.newCheckedInstanceOf("org.apache.logging.log4j.core.lookup.JndiLookup", StrLookup.class));
094 } catch (final Throwable e) {
095 // java.lang.VerifyError: org/apache/logging/log4j/core/lookup/JndiLookup
096 LOGGER.warn(
097 "JNDI lookup class is not available because this JRE does not support JNDI. JNDI string lookups will not be available, continuing configuration.",
098 e);
099 }
100 // JMX input args
101 try {
102 // We might be on Android
103 lookups.put("jvmrunargs",
104 Loader.newCheckedInstanceOf("org.apache.logging.log4j.core.lookup.JmxRuntimeInputArgumentsLookup", StrLookup.class));
105 } catch (final Throwable e) {
106 // java.lang.VerifyError: org/apache/logging/log4j/core/lookup/JmxRuntimeInputArgumentsLookup
107 LOGGER.warn(
108 "JMX runtime input lookup class is not available because this JRE does not support JMX. JMX lookups will not be available, continuing configuration.",
109 e);
110 }
111 lookups.put("date", new DateLookup());
112 lookups.put("ctx", new ContextMapLookup());
113 if (Loader.isClassAvailable("javax.servlet.ServletContext")) {
114 try {
115 lookups.put("web",
116 Loader.newCheckedInstanceOf("org.apache.logging.log4j.web.WebLookup", StrLookup.class));
117 } catch (final Exception ignored) {
118 LOGGER.info("Log4j appears to be running in a Servlet environment, but there's no log4j-web module " +
119 "available. If you want better web container support, please add the log4j-web JAR to your " +
120 "web archive or server lib directory.");
121 }
122 } else {
123 LOGGER.debug("Not in a ServletContext environment, thus not loading WebLookup plugin.");
124 }
125 }
126
127 /**
128 * Resolves the specified variable. This implementation will try to extract
129 * a variable prefix from the given variable name (the first colon (':') is
130 * used as prefix separator). It then passes the name of the variable with
131 * the prefix stripped to the lookup object registered for this prefix. If
132 * no prefix can be found or if the associated lookup object cannot resolve
133 * this variable, the default lookup object will be used.
134 *
135 * @param event The current LogEvent or null.
136 * @param var the name of the variable whose value is to be looked up
137 * @return the value of this variable or <b>null</b> if it cannot be
138 * resolved
139 */
140 @Override
141 public String lookup(final LogEvent event, String var) {
142 if (var == null) {
143 return null;
144 }
145
146 final int prefixPos = var.indexOf(PREFIX_SEPARATOR);
147 if (prefixPos >= 0) {
148 final String prefix = var.substring(0, prefixPos);
149 final String name = var.substring(prefixPos + 1);
150 final StrLookup lookup = lookups.get(prefix);
151 String value = null;
152 if (lookup != null) {
153 value = event == null ? lookup.lookup(name) : lookup.lookup(event, name);
154 }
155
156 if (value != null) {
157 return value;
158 }
159 var = var.substring(prefixPos + 1);
160 }
161 if (defaultLookup != null) {
162 return event == null ? defaultLookup.lookup(var) : defaultLookup.lookup(event, var);
163 }
164 return null;
165 }
166
167 @Override
168 public String toString() {
169 final StringBuilder sb = new StringBuilder();
170 for (final String name : lookups.keySet()) {
171 if (sb.length() == 0) {
172 sb.append('{');
173 } else {
174 sb.append(", ");
175 }
176
177 sb.append(name);
178 }
179 if (sb.length() > 0) {
180 sb.append('}');
181 }
182 return sb.toString();
183 }
184 }