d667ff769cf143afc08b0188ebc4296aed91815a
[sdc.git] /
1 /*
2  * Copyright © 2016-2017 European Support Limited
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.openecomp.sdc.logging.slf4j;
18
19 import java.util.EnumMap;
20 import java.util.Map;
21 import org.openecomp.sdc.logging.slf4j.SLF4JLoggingServiceProvider.ContextField;
22 import org.slf4j.MDC;
23
24 /**
25  * Because we don't know which information should be carried over from MDC, and which shouldn't, copy just the keys that
26  * the logging service uses.
27  *
28  * @author evitaliy
29  * @since 08 Jan 2018
30  */
31 abstract class BaseMDCCopyingWrapper {
32
33     private final Map<ContextField, String> context;
34
35     BaseMDCCopyingWrapper() {
36         this.context = fromMdc();
37     }
38
39     final Map<ContextField, String> replace() {
40         Map<ContextField, String> old = fromMdc();
41         toMdc(this.context);
42         return old;
43     }
44
45     final void revert(Map<ContextField, String> old) {
46         toMdc(old);
47     }
48
49     private Map<ContextField, String> fromMdc() {
50
51         Map<ContextField, String> copy = new EnumMap<>(ContextField.class);
52         for (ContextField k : ContextField.values()) {
53             String v = MDC.get(k.asKey());
54             if (v != null) {
55                 copy.put(k, v);
56             }
57         }
58
59         return copy;
60     }
61
62     private static void toMdc(Map<ContextField, String> context) {
63
64         for (ContextField k : ContextField.values()) {
65             String v = context.get(k);
66             if (v != null) {
67                 MDC.put(k.asKey(), v);
68             } else {
69                 MDC.remove(k.asKey());
70             }
71         }
72     }
73 }