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.NotNull;
28 import org.jetbrains.annotations.Nullable;
32 * @author <a href="mailto:piotr.jaszczyk@nokia.com">Piotr Jaszczyk</a>
36 public interface RequestDiagnosticContext {
40 @Nullable UUID invocationId();
43 default GlobalDiagnosticContext global() {
44 return GlobalDiagnosticContext.instance();
48 default Map<String, String> remoteCallHttpHeaders() {
49 java.util.Map<String, String> result = new java.util.HashMap<>();
51 result.put(MdcVariables.httpHeader(MdcVariables.REQUEST_ID), requestId().toString());
53 if (invocationId() != null) {
54 result.put(MdcVariables.httpHeader(MdcVariables.INVOCATION_ID), invocationId().toString());
57 return HashMap.ofAll(result);
61 default Map<String, String> asMap() {
62 java.util.Map<String, String> result = new java.util.HashMap<>();
64 if (requestId() != null) {
65 result.put(MdcVariables.REQUEST_ID, requestId().toString());
68 if (invocationId() != null) {
69 result.put(MdcVariables.INVOCATION_ID, invocationId().toString());
72 return global().asMap().merge(HashMap.ofAll(result));
75 default void withSlf4jMdc(Runnable runnable) {
76 withSlf4jMdc(true, runnable);
79 default void withSlf4jMdc(boolean loglevelEnabled, Runnable runnable) {
80 if (loglevelEnabled) {
81 final java.util.Map<String, String> ctxBefore = MDC.getCopyOfContextMap();
83 MDC.setContextMap(asMap().toJavaMap());
86 if (ctxBefore == null) {
89 MDC.setContextMap(ctxBefore);
95 default @NotNull RequestDiagnosticContext withNewInvocationId() {
96 return ImmutableRequestDiagnosticContext.copyOf(this)
97 .withInvocationId(UUID.randomUUID());
100 static ImmutableRequestDiagnosticContext create() {
101 return ImmutableRequestDiagnosticContext.builder()
102 .requestId(UUID.randomUUID())
103 .invocationId(UUID.randomUUID())