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.log4j; 018 019import java.util.HashMap; 020import java.util.Hashtable; 021import java.util.Map; 022 023import org.apache.logging.log4j.ThreadContext; 024 025/** 026 * This class behaves just like Log4j's MDC would - and so can cause issues with the redeployment of web 027 * applications if the Objects stored in the threads Map cannot be garbage collected. 028 */ 029public final class MDC { 030 031 private static ThreadLocal<Map<String, Object>> localMap = 032 new InheritableThreadLocal<Map<String, Object>>() { 033 @Override 034 protected Map<String, Object> initialValue() { 035 return new HashMap<>(); 036 } 037 038 @Override 039 protected Map<String, Object> childValue(final Map<String, Object> parentValue) { 040 return parentValue == null ? new HashMap<>() : new HashMap<>(parentValue); 041 } 042 }; 043 044 private MDC() { 045 } 046 047 048 public static void put(final String key, final String value) { 049 localMap.get().put(key, value); 050 ThreadContext.put(key, value); 051 } 052 053 054 public static void put(final String key, final Object value) { 055 localMap.get().put(key, value); 056 ThreadContext.put(key, value.toString()); 057 } 058 059 public static Object get(final String key) { 060 return localMap.get().get(key); 061 } 062 063 public static void remove(final String key) { 064 localMap.get().remove(key); 065 ThreadContext.remove(key); 066 } 067 068 public static void clear() { 069 localMap.get().clear(); 070 ThreadContext.clearMap(); 071 } 072 073 public static Hashtable<String, Object> getContext() { 074 return new Hashtable<>(localMap.get()); 075 } 076}