[SDC-29] Amdocs OnBoard 1707 initial commit.
[sdc.git] / common / openecomp-logging-lib / openecomp-logging-core / src / main / java / org / openecomp / core / logging / context / MdcPropagationService.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.core.logging.context;
22
23 import org.openecomp.core.logging.api.context.ContextPropagationService;
24 import org.slf4j.MDC;
25
26 import java.util.Map;
27
28 /**
29  * Propagates the <a href="http://www.slf4j.org/manual.html#mdc">SLF4J Mapped Diagnostic Context
30  * (MDC)</a> of a thread onto a runnable created by that thread, so that the context is available
31  * when the runnable is executed in a new thread.
32  */
33 public class MdcPropagationService implements ContextPropagationService {
34
35   public Runnable create(Runnable task) {
36     return new MdcCopyingWrapper(task);
37   }
38
39   private static class MdcCopyingWrapper implements Runnable {
40
41     private final Runnable task;
42     private final Map<String, String> context;
43
44     private MdcCopyingWrapper(Runnable task) {
45       this.task = task;
46       this.context = MDC.getCopyOfContextMap();
47     }
48
49     private static void replaceMdc(Map<String, String> context) {
50
51       if (context == null) {
52         MDC.clear();
53       } else {
54         MDC.setContextMap(context);
55       }
56     }
57
58     @Override
59     public void run() {
60
61       Map<String, String> oldContext = MDC.getCopyOfContextMap();
62       replaceMdc(this.context);
63
64       try {
65         task.run();
66       } finally {
67         replaceMdc(oldContext);
68       }
69     }
70   }
71 }