package org.slf4j.helpers; import org.slf4j.spi.MDCAdapter; import java.util.HashMap; import java.util.Set; /** * Basic MDC implementation, that can be used for logging systems that * lack out-of-the-box MDC support */ public class BasicMDCAdapter implements MDCAdapter { private static InheritableThreadLocal inheritableThreadLocal = new InheritableThreadLocal(); public void put(String key, String val) { if (key == null) { throw new IllegalArgumentException("key cannot be null"); } HashMap map = (HashMap) inheritableThreadLocal.get(); if (map == null) { map = new HashMap(); inheritableThreadLocal.set(map); } map.put(key, val); } public String get(String key) { HashMap hashMap = (HashMap) inheritableThreadLocal.get(); if ((hashMap != null) && (key != null)) { return (String) hashMap.get(key); } else { return null; } } public void remove(String key) { HashMap map = (HashMap) inheritableThreadLocal.get(); if (map != null) { map.remove(key); } } public void clear() { HashMap hashMap = (HashMap) inheritableThreadLocal.get(); if (hashMap != null) { hashMap.clear(); inheritableThreadLocal.remove(); } } /** * Returns the keys in the MDC as a {@link Set} of {@link String}s * The returned value can be null. * @return the keys in the MDC */ public Set getKeys() { HashMap hashMap = (HashMap) inheritableThreadLocal.get(); if (hashMap != null) { return hashMap.keySet(); } else { return null; } } }