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