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