1 /**
2 * Copyright (c) 2004-2011 QOS.ch
3 * All rights reserved.
4 *
5 * Permission is hereby granted, free of charge, to any person obtaining
6 * a copy of this software and associated documentation files (the
7 * "Software"), to deal in the Software without restriction, including
8 * without limitation the rights to use, copy, modify, merge, publish,
9 * distribute, sublicense, and/or sell copies of the Software, and to
10 * permit persons to whom the Software is furnished to do so, subject to
11 * the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be
14 * included in all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23 *
24 */
25 package org.slf4j.impl;
26
27 import java.util.HashMap;
28 import java.util.Iterator;
29 import java.util.Map;
30
31 import org.slf4j.spi.MDCAdapter;
32
33 public class Log4jMDCAdapter implements MDCAdapter {
34
35 public void clear() {
36 Map map = org.apache.log4j.MDC.getContext();
37 if (map != null) {
38 map.clear();
39 }
40 }
41
42 public String get(String key) {
43 return (String) org.apache.log4j.MDC.get(key);
44 }
45
46 /**
47 * Put a context value (the <code>val</code> parameter) as identified with
48 * the <code>key</code> parameter into the current thread's context map. The
49 * <code>key</code> parameter cannot be null. Log4j does <em>not</em>
50 * support null for the <code>val</code> parameter.
51 *
52 * <p>
53 * This method delegates all work to log4j's MDC.
54 *
55 * @throws IllegalArgumentException
56 * in case the "key" or <b>"val"</b> parameter is null
57 */
58 public void put(String key, String val) {
59 org.apache.log4j.MDC.put(key, val);
60 }
61
62 public void remove(String key) {
63 org.apache.log4j.MDC.remove(key);
64 }
65
66 public Map getCopyOfContextMap() {
67 Map old = org.apache.log4j.MDC.getContext();
68 if(old != null) {
69 return new HashMap(old);
70 } else {
71 return null;
72 }
73 }
74
75 public void setContextMap(Map contextMap) {
76 Map old = org.apache.log4j.MDC.getContext();
77 if(old == null) {
78 Iterator entrySetIterator = contextMap.entrySet().iterator();
79 while(entrySetIterator.hasNext()) {
80 Map.Entry mapEntry = (Map.Entry) entrySetIterator.next();
81 org.apache.log4j.MDC.put((String) mapEntry.getKey(), mapEntry.getValue());
82 }
83 } else {
84 old.clear();
85 old.putAll(contextMap);
86 }
87 }
88 }