View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements. See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache license, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License. You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the license for the specific language governing permissions and
15   * limitations under the license.
16   */
17  package org.apache.logging.log4j.core.impl;
18  
19  import org.apache.logging.log4j.ThreadContext;
20  import org.apache.logging.log4j.core.ContextDataInjector;
21  import org.apache.logging.log4j.core.LogEvent;
22  import org.apache.logging.log4j.core.util.Loader;
23  import org.apache.logging.log4j.spi.CopyOnWrite;
24  import org.apache.logging.log4j.spi.DefaultThreadContextMap;
25  import org.apache.logging.log4j.spi.ReadOnlyThreadContextMap;
26  import org.apache.logging.log4j.status.StatusLogger;
27  import org.apache.logging.log4j.util.PropertiesUtil;
28  import org.apache.logging.log4j.util.ReadOnlyStringMap;
29  
30  /**
31   * Factory for ContextDataInjectors. Returns a new {@code ContextDataInjector} instance based on the value of system
32   * property {@code log4j2.ContextDataInjector}. Users may use this system property to specify the fully qualified class
33   * name of a class that implements the {@code ContextDataInjector} interface.
34   * If no value was specified this factory method returns one of the injectors defined in
35   * {@code ThreadContextDataInjector}.
36   *
37   * @see ContextDataInjector
38   * @see ReadOnlyStringMap
39   * @see ThreadContextDataInjector
40   * @see LogEvent#getContextData()
41   * @since 2.7
42   */
43  public class ContextDataInjectorFactory {
44  
45      /**
46       * Returns a new {@code ContextDataInjector} instance based on the value of system property
47       * {@code log4j2.ContextDataInjector}. If no value was specified this factory method returns one of the
48       * {@code ContextDataInjector} classes defined in {@link ThreadContextDataInjector} which is most appropriate for
49       * the ThreadContext implementation.
50       * <p>
51       * <b>Note:</b> It is no longer recommended that users provide a custom implementation of the ContextDataInjector.
52       * Instead, provide a {@code ContextDataProvider}.
53       * </p>
54       * <p>
55       * Users may use this system property to specify the fully qualified class name of a class that implements the
56       * {@code ContextDataInjector} interface.
57       * </p><p>
58       * When providing a custom {@code ContextDataInjector}, be aware that this method may be invoked multiple times by
59       * the various components in Log4j that need access to context data.
60       * This includes the object(s) that populate log events, but also various lookups and filters that look at
61       * context data to determine whether an event should be logged.
62       * </p>
63       *
64       * @return a ContextDataInjector that populates the {@code ReadOnlyStringMap} of all {@code LogEvent} objects
65       * @see LogEvent#getContextData()
66       * @see ContextDataInjector
67       */
68      public static ContextDataInjector createInjector() {
69          final String className = PropertiesUtil.getProperties().getStringProperty("log4j2.ContextDataInjector");
70          if (className == null) {
71              return createDefaultInjector();
72          }
73          try {
74              final Class<? extends ContextDataInjector> cls = Loader.loadClass(className).asSubclass(
75                      ContextDataInjector.class);
76              return cls.newInstance();
77          } catch (final Exception dynamicFailed) {
78              final ContextDataInjector result = createDefaultInjector();
79              StatusLogger.getLogger().warn(
80                      "Could not create ContextDataInjector for '{}', using default {}: {}",
81                      className, result.getClass().getName(), dynamicFailed);
82              return result;
83          }
84      }
85  
86      private static ContextDataInjector createDefaultInjector() {
87          final ReadOnlyThreadContextMap threadContextMap = ThreadContext.getThreadContextMap();
88  
89          // note: map may be null (if legacy custom ThreadContextMap was installed by user)
90          if (threadContextMap instanceof DefaultThreadContextMap || threadContextMap == null) {
91              return new ThreadContextDataInjector.ForDefaultThreadContextMap(); // for non StringMap-based context maps
92          }
93          if (threadContextMap instanceof CopyOnWrite) {
94              return new ThreadContextDataInjector.ForCopyOnWriteThreadContextMap();
95          }
96          return new ThreadContextDataInjector.ForGarbageFreeThreadContextMap();
97      }
98  }