2 * ============LICENSE_START====================================
3 * DCAEGEN2-SERVICES-SDK
4 * =========================================================
5 * Copyright (C) 2019 Nokia. 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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=====================================
21 package org.onap.dcaegen2.services.sdk.rest.services.model.logging;
23 import io.vavr.collection.HashMap;
24 import io.vavr.collection.Map;
25 import java.util.UUID;
26 import org.immutables.value.Value;
27 import org.jetbrains.annotations.Nullable;
31 * @author <a href="mailto:piotr.jaszczyk@nokia.com">Piotr Jaszczyk</a>
35 public interface RequestDiagnosticContext {
39 @Nullable UUID invocationId();
42 default GlobalDiagnosticContext global() {
43 return GlobalDiagnosticContext.instance();
47 default Map<String, String> remoteCallHttpHeaders() {
48 java.util.Map<String, String> result = new java.util.HashMap<>();
50 result.put(MdcVariables.httpHeader(MdcVariables.REQUEST_ID), requestId().toString());
52 if (invocationId() != null) {
53 result.put(MdcVariables.httpHeader(MdcVariables.INVOCATION_ID), invocationId().toString());
56 return HashMap.ofAll(result);
60 default Map<String, String> asMap() {
61 java.util.Map<String, String> result = new java.util.HashMap<>();
63 if (requestId() != null) {
64 result.put(MdcVariables.REQUEST_ID, requestId().toString());
67 if (invocationId() != null) {
68 result.put(MdcVariables.INVOCATION_ID, invocationId().toString());
71 return global().asMap().merge(HashMap.ofAll(result));
74 default void withSlf4jMdc(Runnable runnable) {
75 withSlf4jMdc(true, runnable);
78 default void withSlf4jMdc(boolean loglevelEnabled, Runnable runnable) {
79 if (loglevelEnabled) {
80 final java.util.Map<String, String> ctxBefore = MDC.getCopyOfContextMap();
82 MDC.setContextMap(asMap().toJavaMap());
85 if (ctxBefore == null) {
88 MDC.setContextMap(ctxBefore);
94 static ImmutableRequestDiagnosticContext create() {
95 return ImmutableRequestDiagnosticContext.builder()
96 .requestId(UUID.randomUUID())
97 .invocationId(UUID.randomUUID())