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     * Users may use this system property to specify the fully qualified class name of a class that implements the
052     * {@code ContextDataInjector} interface.
053     * </p><p>
054     * When providing a custom {@code ContextDataInjector}, be aware that this method may be invoked multiple times by
055     * the various components in Log4j that need access to context data.
056     * This includes the object(s) that populate log events, but also various lookups and filters that look at
057     * context data to determine whether an event should be logged.
058     * </p>
059     *
060     * @return a ContextDataInjector that populates the {@code ReadOnlyStringMap} of all {@code LogEvent} objects
061     * @see LogEvent#getContextData()
062     * @see ContextDataInjector
063     */
064    public static ContextDataInjector createInjector() {
065        final String className = PropertiesUtil.getProperties().getStringProperty("log4j2.ContextDataInjector");
066        if (className == null) {
067            return createDefaultInjector();
068        }
069        try {
070            final Class<? extends ContextDataInjector> cls = Loader.loadClass(className).asSubclass(
071                    ContextDataInjector.class);
072            return cls.newInstance();
073        } catch (final Exception dynamicFailed) {
074            final ContextDataInjector result = createDefaultInjector();
075            StatusLogger.getLogger().warn(
076                    "Could not create ContextDataInjector for '{}', using default {}: {}",
077                    className, result.getClass().getName(), dynamicFailed);
078            return result;
079        }
080    }
081
082    private static ContextDataInjector createDefaultInjector() {
083        final ReadOnlyThreadContextMap threadContextMap = ThreadContext.getThreadContextMap();
084
085        // note: map may be null (if legacy custom ThreadContextMap was installed by user)
086        if (threadContextMap instanceof DefaultThreadContextMap || threadContextMap == null) {
087            return new ThreadContextDataInjector.ForDefaultThreadContextMap(); // for non StringMap-based context maps
088        }
089        if (threadContextMap instanceof CopyOnWrite) {
090            return new ThreadContextDataInjector.ForCopyOnWriteThreadContextMap();
091        }
092        return new ThreadContextDataInjector.ForGarbageFreeThreadContextMap();
093    }
094}