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       * Users may use this system property to specify the fully qualified class name of a class that implements the
52       * {@code ContextDataInjector} interface.
53       * </p><p>
54       * When providing a custom {@code ContextDataInjector}, be aware that this method may be invoked multiple times by
55       * the various components in Log4j that need access to context data.
56       * This includes the object(s) that populate log events, but also various lookups and filters that look at
57       * context data to determine whether an event should be logged.
58       * </p>
59       *
60       * @return a ContextDataInjector that populates the {@code ReadOnlyStringMap} of all {@code LogEvent} objects
61       * @see LogEvent#getContextData()
62       * @see ContextDataInjector
63       */
64      public static ContextDataInjector createInjector() {
65          final String className = PropertiesUtil.getProperties().getStringProperty("log4j2.ContextDataInjector");
66          if (className == null) {
67              return createDefaultInjector();
68          }
69          try {
70              final Class<? extends ContextDataInjector> cls = Loader.loadClass(className).asSubclass(
71                      ContextDataInjector.class);
72              return cls.newInstance();
73          } catch (final Exception dynamicFailed) {
74              final ContextDataInjector result = createDefaultInjector();
75              StatusLogger.getLogger().warn(
76                      "Could not create ContextDataInjector for '{}', using default {}: {}",
77                      className, result.getClass().getName(), dynamicFailed);
78              return result;
79          }
80      }
81  
82      private static ContextDataInjector createDefaultInjector() {
83          final ReadOnlyThreadContextMap threadContextMap = ThreadContext.getThreadContextMap();
84  
85          // note: map may be null (if legacy custom ThreadContextMap was installed by user)
86          if (threadContextMap instanceof DefaultThreadContextMap || threadContextMap == null) {
87              return new ThreadContextDataInjector.ForDefaultThreadContextMap(); // for non StringMap-based context maps
88          }
89          if (threadContextMap instanceof CopyOnWrite) {
90              return new ThreadContextDataInjector.ForCopyOnWriteThreadContextMap();
91          }
92          return new ThreadContextDataInjector.ForGarbageFreeThreadContextMap();
93      }
94  }