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 */ 017package org.apache.logging.log4j.core.lookup; 018 019import java.util.HashMap; 020import java.util.List; 021import java.util.Locale; 022import java.util.Map; 023 024import org.apache.logging.log4j.Logger; 025import org.apache.logging.log4j.core.LogEvent; 026import org.apache.logging.log4j.core.config.ConfigurationAware; 027import org.apache.logging.log4j.core.config.plugins.util.PluginManager; 028import org.apache.logging.log4j.core.config.plugins.util.PluginType; 029import org.apache.logging.log4j.core.net.JndiManager; 030import org.apache.logging.log4j.core.util.Loader; 031import org.apache.logging.log4j.core.util.ReflectionUtil; 032import org.apache.logging.log4j.status.StatusLogger; 033import org.apache.logging.log4j.util.Constants; 034 035/** 036 * Proxies all the other {@link StrLookup}s. 037 */ 038public class Interpolator extends AbstractConfigurationAwareLookup { 039 040 private static final String LOOKUP_KEY_WEB = "web"; 041 042 private static final String LOOKUP_KEY_DOCKER = "docker"; 043 044 private static final String LOOKUP_KEY_JNDI = "jndi"; 045 046 private static final String LOOKUP_KEY_JVMRUNARGS = "jvmrunargs"; 047 048 private static final Logger LOGGER = StatusLogger.getLogger(); 049 050 /** Constant for the prefix separator. */ 051 static final char PREFIX_SEPARATOR = ':'; 052 053 private final Map<String, StrLookup> strLookupMap = new HashMap<>(); 054 055 private final StrLookup defaultLookup; 056 057 public Interpolator(final StrLookup defaultLookup) { 058 this(defaultLookup, null); 059 } 060 061 /** 062 * Constructs an Interpolator using a given StrLookup and a list of packages to find Lookup plugins in. 063 * 064 * @param defaultLookup the default StrLookup to use as a fallback 065 * @param pluginPackages a list of packages to scan for Lookup plugins 066 * @since 2.1 067 */ 068 public Interpolator(final StrLookup defaultLookup, final List<String> pluginPackages) { 069 this.defaultLookup = defaultLookup == null ? new MapLookup(new HashMap<String, String>()) : defaultLookup; 070 final PluginManager manager = new PluginManager(CATEGORY); 071 manager.collectPlugins(pluginPackages); 072 final Map<String, PluginType<?>> plugins = manager.getPlugins(); 073 074 for (final Map.Entry<String, PluginType<?>> entry : plugins.entrySet()) { 075 try { 076 final Class<? extends StrLookup> clazz = entry.getValue().getPluginClass().asSubclass(StrLookup.class); 077 if (!clazz.getName().equals("org.apache.logging.log4j.core.lookup.JndiLookup") || JndiManager.isJndiLookupEnabled()) { 078 strLookupMap.put(entry.getKey().toLowerCase(), ReflectionUtil.instantiate(clazz)); 079 } 080 } catch (final Throwable t) { 081 handleError(entry.getKey(), t); 082 } 083 } 084 } 085 086 /** 087 * Create the default Interpolator using only Lookups that work without an event. 088 */ 089 public Interpolator() { 090 this((Map<String, String>) null); 091 } 092 093 /** 094 * Creates the Interpolator using only Lookups that work without an event and initial properties. 095 */ 096 public Interpolator(final Map<String, String> properties) { 097 this.defaultLookup = new MapLookup(properties == null ? new HashMap<String, String>() : properties); 098 // TODO: this ought to use the PluginManager 099 strLookupMap.put("log4j", new Log4jLookup()); 100 strLookupMap.put("sys", new SystemPropertiesLookup()); 101 strLookupMap.put("env", new EnvironmentLookup()); 102 strLookupMap.put("main", MainMapLookup.MAIN_SINGLETON); 103 strLookupMap.put("marker", new MarkerLookup()); 104 strLookupMap.put("java", new JavaLookup()); 105 // JNDI 106 if (JndiManager.isJndiLookupEnabled()) { 107 try { 108 // [LOG4J2-703] We might be on Android 109 strLookupMap.put(LOOKUP_KEY_JNDI, 110 Loader.newCheckedInstanceOf("org.apache.logging.log4j.core.lookup.JndiLookup", StrLookup.class)); 111 } catch (final LinkageError | Exception e) { 112 handleError(LOOKUP_KEY_JNDI, e); 113 } 114 } 115 // JMX input args 116 try { 117 // We might be on Android 118 strLookupMap.put(LOOKUP_KEY_JVMRUNARGS, 119 Loader.newCheckedInstanceOf("org.apache.logging.log4j.core.lookup.JmxRuntimeInputArgumentsLookup", 120 StrLookup.class)); 121 } catch (final LinkageError | Exception e) { 122 handleError(LOOKUP_KEY_JVMRUNARGS, e); 123 } 124 strLookupMap.put("date", new DateLookup()); 125 strLookupMap.put("ctx", new ContextMapLookup()); 126 if (Constants.IS_WEB_APP) { 127 try { 128 strLookupMap.put(LOOKUP_KEY_WEB, 129 Loader.newCheckedInstanceOf("org.apache.logging.log4j.web.WebLookup", StrLookup.class)); 130 } catch (final Exception ignored) { 131 handleError(LOOKUP_KEY_WEB, ignored); 132 } 133 } else { 134 LOGGER.debug("Not in a ServletContext environment, thus not loading WebLookup plugin."); 135 } 136 try { 137 strLookupMap.put(LOOKUP_KEY_DOCKER, 138 Loader.newCheckedInstanceOf("org.apache.logging.log4j.docker.DockerLookup", StrLookup.class)); 139 } catch (final Exception ignored) { 140 handleError(LOOKUP_KEY_DOCKER, ignored); 141 } 142 } 143 144 public Map<String, StrLookup> getStrLookupMap() { 145 return strLookupMap; 146 } 147 148 private void handleError(final String lookupKey, final Throwable t) { 149 switch (lookupKey) { 150 case LOOKUP_KEY_JNDI: 151 // java.lang.VerifyError: org/apache/logging/log4j/core/lookup/JndiLookup 152 LOGGER.warn( // LOG4J2-1582 don't print the whole stack trace (it is just a warning...) 153 "JNDI lookup class is not available because this JRE does not support JNDI." + 154 " JNDI string lookups will not be available, continuing configuration. Ignoring " + t); 155 break; 156 case LOOKUP_KEY_JVMRUNARGS: 157 // java.lang.VerifyError: org/apache/logging/log4j/core/lookup/JmxRuntimeInputArgumentsLookup 158 LOGGER.warn( 159 "JMX runtime input lookup class is not available because this JRE does not support JMX. " + 160 "JMX lookups will not be available, continuing configuration. Ignoring " + t); 161 break; 162 case LOOKUP_KEY_WEB: 163 LOGGER.info("Log4j appears to be running in a Servlet environment, but there's no log4j-web module " + 164 "available. If you want better web container support, please add the log4j-web JAR to your " + 165 "web archive or server lib directory."); 166 break; 167 case LOOKUP_KEY_DOCKER: 168 break; 169 default: 170 LOGGER.error("Unable to create Lookup for {}", lookupKey, t); 171 } 172 } 173 174 /** 175 * Resolves the specified variable. This implementation will try to extract 176 * a variable prefix from the given variable name (the first colon (':') is 177 * used as prefix separator). It then passes the name of the variable with 178 * the prefix stripped to the lookup object registered for this prefix. If 179 * no prefix can be found or if the associated lookup object cannot resolve 180 * this variable, the default lookup object will be used. 181 * 182 * @param event The current LogEvent or null. 183 * @param var the name of the variable whose value is to be looked up 184 * @return the value of this variable or <b>null</b> if it cannot be 185 * resolved 186 */ 187 @Override 188 public String lookup(final LogEvent event, String var) { 189 if (var == null) { 190 return null; 191 } 192 193 final int prefixPos = var.indexOf(PREFIX_SEPARATOR); 194 if (prefixPos >= 0) { 195 final String prefix = var.substring(0, prefixPos).toLowerCase(Locale.US); 196 final String name = var.substring(prefixPos + 1); 197 final StrLookup lookup = strLookupMap.get(prefix); 198 if (lookup instanceof ConfigurationAware) { 199 ((ConfigurationAware) lookup).setConfiguration(configuration); 200 } 201 String value = null; 202 if (lookup != null) { 203 value = event == null ? lookup.lookup(name) : lookup.lookup(event, name); 204 } 205 206 if (value != null) { 207 return value; 208 } 209 var = var.substring(prefixPos + 1); 210 } 211 if (defaultLookup != null) { 212 return event == null ? defaultLookup.lookup(var) : defaultLookup.lookup(event, var); 213 } 214 return null; 215 } 216 217 @Override 218 public String toString() { 219 final StringBuilder sb = new StringBuilder(); 220 for (final String name : strLookupMap.keySet()) { 221 if (sb.length() == 0) { 222 sb.append('{'); 223 } else { 224 sb.append(", "); 225 } 226 227 sb.append(name); 228 } 229 if (sb.length() > 0) { 230 sb.append('}'); 231 } 232 return sb.toString(); 233 } 234 235}