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