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.impl;
018
019import org.apache.logging.log4j.ThreadContext;
020import org.apache.logging.log4j.core.ContextDataInjector;
021import org.apache.logging.log4j.core.LogEvent;
022import org.apache.logging.log4j.core.util.Loader;
023import org.apache.logging.log4j.spi.CopyOnWrite;
024import org.apache.logging.log4j.spi.DefaultThreadContextMap;
025import org.apache.logging.log4j.spi.ReadOnlyThreadContextMap;
026import org.apache.logging.log4j.status.StatusLogger;
027import org.apache.logging.log4j.util.PropertiesUtil;
028import org.apache.logging.log4j.util.ReadOnlyStringMap;
029
030/**
031 * Factory for ContextDataInjectors. Returns a new {@code ContextDataInjector} instance based on the value of system
032 * property {@code log4j2.ContextDataInjector}. Users may use this system property to specify the fully qualified class
033 * name of a class that implements the {@code ContextDataInjector} interface.
034 * If no value was specified this factory method returns one of the injectors defined in
035 * {@code ThreadContextDataInjector}.
036 *
037 * @see ContextDataInjector
038 * @see ReadOnlyStringMap
039 * @see ThreadContextDataInjector
040 * @see LogEvent#getContextData()
041 * @since 2.7
042 */
043public class ContextDataInjectorFactory {
044
045    /**
046     * Returns a new {@code ContextDataInjector} instance based on the value of system property
047     * {@code log4j2.ContextDataInjector}. If no value was specified this factory method returns one of the
048     * {@code ContextDataInjector} classes defined in {@link ThreadContextDataInjector} which is most appropriate for
049     * the ThreadContext implementation.
050     * <p>
051     * <b>Note:</b> It is no longer recommended that users provide a custom implementation of the ContextDataInjector.
052     * Instead, provide a {@code ContextDataProvider}.
053     * </p>
054     * <p>
055     * Users may use this system property to specify the fully qualified class name of a class that implements the
056     * {@code ContextDataInjector} interface.
057     * </p><p>
058     * When providing a custom {@code ContextDataInjector}, be aware that this method may be invoked multiple times by
059     * the various components in Log4j that need access to context data.
060     * This includes the object(s) that populate log events, but also various lookups and filters that look at
061     * context data to determine whether an event should be logged.
062     * </p>
063     *
064     * @return a ContextDataInjector that populates the {@code ReadOnlyStringMap} of all {@code LogEvent} objects
065     * @see LogEvent#getContextData()
066     * @see ContextDataInjector
067     */
068    public static ContextDataInjector createInjector() {
069        final String className = PropertiesUtil.getProperties().getStringProperty("log4j2.ContextDataInjector");
070        if (className == null) {
071            return createDefaultInjector();
072        }
073        try {
074            final Class<? extends ContextDataInjector> cls = Loader.loadClass(className).asSubclass(
075                    ContextDataInjector.class);
076            return cls.newInstance();
077        } catch (final Exception dynamicFailed) {
078            final ContextDataInjector result = createDefaultInjector();
079            StatusLogger.getLogger().warn(
080                    "Could not create ContextDataInjector for '{}', using default {}: {}",
081                    className, result.getClass().getName(), dynamicFailed);
082            return result;
083        }
084    }
085
086    private static ContextDataInjector createDefaultInjector() {
087        final ReadOnlyThreadContextMap threadContextMap = ThreadContext.getThreadContextMap();
088
089        // note: map may be null (if legacy custom ThreadContextMap was installed by user)
090        if (threadContextMap instanceof DefaultThreadContextMap || threadContextMap == null) {
091            return new ThreadContextDataInjector.ForDefaultThreadContextMap(); // for non StringMap-based context maps
092        }
093        if (threadContextMap instanceof CopyOnWrite) {
094            return new ThreadContextDataInjector.ForCopyOnWriteThreadContextMap();
095        }
096        return new ThreadContextDataInjector.ForGarbageFreeThreadContextMap();
097    }
098}