1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 package org.slf4j.log4j12;
26
27 import java.util.Deque;
28 import java.util.HashMap;
29 import java.util.Map;
30
31 import org.apache.log4j.MDCFriend;
32 import org.slf4j.helpers.ThreadLocalMapOfStacks;
33 import org.slf4j.spi.MDCAdapter;
34
35 public class Log4jMDCAdapter implements MDCAdapter {
36
37 private final ThreadLocalMapOfStacks threadLocalMapOfDeques = new ThreadLocalMapOfStacks();
38
39 static {
40 if (VersionUtil.getJavaMajorVersion() >= 9) {
41 MDCFriend.fixForJava9();
42 }
43 }
44
45 @Override
46 public void clear() {
47 @SuppressWarnings("rawtypes")
48 Map map = org.apache.log4j.MDC.getContext();
49 if (map != null) {
50 map.clear();
51 }
52 }
53
54 @Override
55 public String get(String key) {
56 return (String) org.apache.log4j.MDC.get(key);
57 }
58
59
60
61
62
63
64
65
66
67
68
69
70
71 @Override
72 public void put(String key, String val) {
73 org.apache.log4j.MDC.put(key, val);
74 }
75
76 @Override
77 public void remove(String key) {
78 org.apache.log4j.MDC.remove(key);
79 }
80
81 @SuppressWarnings({ "rawtypes", "unchecked" })
82 public Map getCopyOfContextMap() {
83 Map old = org.apache.log4j.MDC.getContext();
84 if (old != null) {
85 return new HashMap(old);
86 } else {
87 return null;
88 }
89 }
90
91 @SuppressWarnings({ "rawtypes", "unchecked" })
92 @Override
93 public void setContextMap(Map<String, String> contextMap) {
94 Map old = org.apache.log4j.MDC.getContext();
95
96
97 if (contextMap == null) {
98 if (old != null) {
99 old.clear();
100 }
101 return;
102 }
103
104 if (old == null) {
105 for (Map.Entry<String, String> mapEntry : contextMap.entrySet()) {
106 org.apache.log4j.MDC.put(mapEntry.getKey(), mapEntry);
107 }
108 } else {
109 old.clear();
110 old.putAll(contextMap);
111 }
112 }
113
114 @Override
115 public void pushByKey(String key, String value) {
116 threadLocalMapOfDeques.pushByKey(key, value);
117 }
118
119 @Override
120 public String popByKey(String key) {
121 return threadLocalMapOfDeques.popByKey(key);
122 }
123
124 @Override
125 public Deque<String> getCopyOfDequeByKey(String key) {
126 return threadLocalMapOfDeques.getCopyOfDequeByKey(key);
127 }
128
129 @Override
130 public void clearDequeByKey(String key) {
131 threadLocalMapOfDeques.clearDequeByKey(key);
132 }
133 }