131b8db263a494811da541dc605e4b31598e95d8
[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.context;
18
19 import org.openecomp.sdc.logging.api.context.ContextPropagationService;
20 import org.slf4j.MDC;
21
22 import java.util.Map;
23
24 /**
25  * Propagates the <a href="http://www.slf4j.org/manual.html#mdc">SLF4J Mapped Diagnostic Context (MDC)</a>
26  * of a thread onto a runnable created by that thread, so that the context is available when the runnable is executed
27  * in a new thread.
28  *
29  * @author evitaliy
30  * @since 12/09/2016.
31  */
32 public class MDCPropagationService implements ContextPropagationService {
33
34     public Runnable create(Runnable task) {
35         return new MDCCopyingWrapper(task);
36     }
37
38     private static class MDCCopyingWrapper implements Runnable {
39
40         private final Runnable task;
41         private final Map<String, String> context;
42
43         private MDCCopyingWrapper(Runnable task) {
44             this.task = task;
45             this.context = MDC.getCopyOfContextMap();
46         }
47
48         @Override
49         public void run() {
50
51             Map<String, String> oldContext = MDC.getCopyOfContextMap();
52             replaceMDC(this.context);
53
54             try {
55                 task.run();
56             } finally {
57                 replaceMDC(oldContext);
58             }
59         }
60
61         private static void replaceMDC(Map<String, String> context) {
62
63             if (context == null) {
64                 MDC.clear();
65             } else  {
66                 MDC.setContextMap(context);
67             }
68         }
69     }
70 }