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.log4j;
18  
19  import java.util.HashMap;
20  import java.util.Hashtable;
21  import java.util.Map;
22  
23  import org.apache.logging.log4j.ThreadContext;
24  
25  /**
26   * This class behaves just like Log4j's MDC would - and so can cause issues with the redeployment of web
27   * applications if the Objects stored in the threads Map cannot be garbage collected.
28   */
29  public final class MDC {
30  
31  
32      private static ThreadLocal<Map<String, Object>> localMap =
33          new InheritableThreadLocal<Map<String, Object>>() {
34              @Override
35              protected Map<String, Object> initialValue() {
36                  return new HashMap<String, Object>();
37              }
38  
39              @Override
40              protected Map<String, Object> childValue(final Map<String, Object> parentValue) {
41                  return parentValue == null ? new HashMap<String, Object>() : new HashMap<String, Object>(parentValue);
42              }
43          };
44  
45      private MDC() {
46      }
47  
48  
49      public static void put(final String key, final String value) {
50          localMap.get().put(key, value);
51          ThreadContext.put(key, value);
52      }
53  
54  
55      public static void put(final String key, final Object value) {
56          localMap.get().put(key, value);
57          ThreadContext.put(key, value.toString());
58      }
59  
60      public static Object get(final String key) {
61          return localMap.get().get(key);
62      }
63  
64      public static void remove(final String key) {
65          localMap.get().remove(key);
66          ThreadContext.remove(key);
67      }
68  
69      public static void clear() {
70          localMap.get().clear();
71          ThreadContext.clearMap();
72      }
73  
74      public static Hashtable<String, Object> getContext() {
75          return new Hashtable<String, Object>(localMap.get());
76      }
77  }