fix - when retrieve topology we are using threadPool and the MDC values are not updated
[vid.git] / vid-app-common / src / main / java / org / onap / vid / utils / Logging.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * VID
4  * ================================================================================
5  * Copyright (C) 2017 - 2019 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.onap.vid.utils;
22
23 import static org.apache.commons.lang3.ObjectUtils.defaultIfNull;
24 import static org.apache.commons.lang3.exception.ExceptionUtils.getRootCause;
25 import static org.apache.commons.lang3.exception.ExceptionUtils.getThrowableList;
26 import static org.onap.vid.utils.Streams.not;
27
28 import com.att.eelf.configuration.EELFLogger;
29 import com.fasterxml.jackson.core.JsonProcessingException;
30 import com.fasterxml.jackson.databind.ObjectMapper;
31 import com.fasterxml.jackson.databind.SerializationFeature;
32 import com.google.common.collect.ImmutableList;
33 import io.joshworks.restclient.http.HttpResponse;
34 import java.nio.charset.StandardCharsets;
35 import java.util.Arrays;
36 import java.util.Map;
37 import java.util.Optional;
38 import java.util.UUID;
39 import java.util.concurrent.Callable;
40 import java.util.function.Function;
41 import javax.servlet.http.HttpServletRequest;
42 import javax.ws.rs.core.Response;
43 import org.apache.commons.io.IOUtils;
44 import org.apache.commons.lang3.StringUtils;
45 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
46 import org.onap.portalsdk.core.util.SystemProperties;
47 import org.onap.vid.exceptions.GenericUncheckedException;
48 import org.onap.vid.utils.Unchecked.UncheckedThrowingSupplier;
49 import org.slf4j.MDC;
50 import org.springframework.http.HttpMethod;
51 import org.springframework.stereotype.Service;
52 import org.springframework.web.context.request.RequestContextHolder;
53 import org.springframework.web.context.request.ServletRequestAttributes;
54
55 @Service
56 public class Logging {
57
58     public static final String HTTP_REQUESTS_OUTGOING = "http.requests.outgoing.";
59
60     public static final String REQUEST_ID_HEADER_KEY = SystemProperties.ECOMP_REQUEST_ID;
61     public static final String ONAP_REQUEST_ID_HEADER_KEY = "X-ONAP-RequestID";
62
63
64     private static ObjectMapper objectMapper = new ObjectMapper();
65
66     public static String getMethodName() {
67         return getMethodName(0);
68     }
69
70     public static String getMethodCallerName() {
71         return getMethodName(1);
72     }
73
74     private static String getMethodName(int depth) {
75         final StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
76         String thisClassName = stackTrace[1].getClassName();
77         final Optional<String> caller =
78                 Arrays.stream(stackTrace)
79                         .skip(1)
80                         .filter(not(frame -> frame.getClassName().equals(thisClassName)))
81                         .skip(depth)
82                         .map(StackTraceElement::getMethodName)
83                         .findFirst();
84         return caller.orElse("<unknonwn method name>");
85     }
86
87     public static EELFLogger getRequestsLogger(String serverName) {
88         return EELFLoggerDelegate.getLogger(HTTP_REQUESTS_OUTGOING +serverName);
89     }
90
91     public void logRequest(final EELFLogger logger, final HttpMethod method, final String url, final Object body) {
92         if (!logger.isDebugEnabled()) {
93             return;
94         }
95
96         if (body == null) {
97             logRequest(logger, method, url);
98             return;
99         }
100
101         try {
102             String bodyAsJson = objectMapper.writeValueAsString(body);
103             logger.debug("Sending  {} {} Body: {}", method.name(), url, bodyAsJson);
104         } catch (JsonProcessingException e) {
105             logRequest(logger, method, url);
106             logger.debug("Failed to parse object in logRequest. {}", body);
107         }
108     }
109
110     public void logRequest(final EELFLogger logger, final HttpMethod method, final String url) {
111         logger.debug("Sending  {} {}", method.name(), url);
112     }
113
114     public <T> void logResponse(final EELFLogger logger, final HttpMethod method, final String url, final Response response, final Class<T> entityClass) {
115         if (!logger.isDebugEnabled()) {
116             return;
117         }
118         if (response == null) {
119             logger.debug("Received {} {} response: null", method.name(), url);
120             return;
121         }
122         try {
123             response.bufferEntity();
124             logger.debug("Received {} {} Status: {} . Body: {}", method.name(), url, response.getStatus(), response.readEntity(entityClass));
125         }
126         catch (Exception e) {
127             logger.debug("Received {} {} Status: {} . Failed to read response as {}", method.name(), url, response.getStatus(), entityClass.getName());
128         }
129     }
130
131     public <T> void logResponse(final EELFLogger logger, final HttpMethod method, final String url, final HttpResponse<T> response) {
132         try {
133             logger.debug("Received {} {} Status: {} . Body: {}", method.name(),
134                 url, response.getStatus(), IOUtils.toString(response.getRawBody(), StandardCharsets.UTF_8));
135             response.getRawBody().reset();
136         }
137         catch (Exception e) {
138             logger.debug("Received {} {} Status: {} . Failed to read response", method.name(), url, response.getStatus());
139         }
140     }
141
142     public void logResponse(final EELFLogger logger, final HttpMethod method, final String url, final Response response) {
143         logResponse(logger, method, url, response, String.class);
144     }
145
146     public static HttpServletRequest getHttpServletRequest(){
147         return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
148     }
149
150     public static String extractOrGenerateRequestId() {
151         try {
152             return getHttpServletRequest().getHeader(REQUEST_ID_HEADER_KEY);
153         }
154         catch (IllegalStateException e) {
155             //in async jobs we don't have any HttpServletRequest
156             return UUID.randomUUID().toString();
157         }
158     }
159
160     public static void debugRequestDetails(Object requestDetails, final EELFLogger logger) {
161         if (logger.isDebugEnabled()) {
162             String requestDetailsAsString;
163             try {
164                 requestDetailsAsString = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT).writeValueAsString(requestDetails);
165             } catch (JsonProcessingException e) {
166                 requestDetailsAsString = "error: cannot stringify RequestDetails";
167             }
168             logger.debug("requestDetailsAsString: {}", requestDetailsAsString);
169         }
170     }
171
172     public static String exceptionToDescription(Throwable exceptionToDescribe) {
173         // Ignore top-most GenericUnchecked or Runtime exceptions that has no added message
174         final Throwable top = getThrowableList(exceptionToDescribe).stream()
175                 .filter(not(e -> ImmutableList.of(GenericUncheckedException.class, RuntimeException.class).contains(e.getClass())
176                         && StringUtils.equals(e.getMessage(), e.getCause() == null ? null : e.getCause().toString())))
177                 .findFirst().orElse(exceptionToDescribe);
178
179         final Throwable root = defaultIfNull(getRootCause(top), top);
180
181         String rootToString = root.toString();
182
183         // nullPointer description will include some context
184         if (root.getClass().equals(NullPointerException.class) && root.getStackTrace().length > 0) {
185             rootToString = String.format("NullPointerException at %s:%d",
186                     root.getStackTrace()[0].getFileName(),
187                     root.getStackTrace()[0].getLineNumber());
188         }
189
190         // if input is a single exception, without cause: top.toString
191         // else: return top.toString + root.toString
192         //       but not if root is already described in top.toString
193         if (top.equals(root)) {
194             return rootToString;
195         } else {
196             final String topToString = top.toString();
197             if (topToString.contains(root.getClass().getName()) && topToString.contains(root.getLocalizedMessage())) {
198                 return topToString;
199             } else {
200                 return topToString + ": " + rootToString;
201             }
202         }
203     }
204
205     /**
206      * in order to be able to write the correct data while creating the node on a new thread save a copy of the current
207      * thread's context map, with keys and values of type String.
208      */
209     public <T> Callable<T> withMDC(Map<String, String> copyOfParentMDC, Callable<T> callable) {
210         return () -> withMDCInternal(copyOfParentMDC, callable::call);
211     }
212
213     /**
214      * in order to be able to write the correct data while creating the node on a new thread save a copy of the current
215      * thread's context map, with keys and values of type String.
216      */
217     public <T, U> Function<T, U> withMDC(Map<String, String> copyOfParentMDC, Function<T, U> function) {
218         return t -> withMDCInternal(copyOfParentMDC, () -> function.apply(t));
219     }
220
221     <T> T withMDCInternal(Map<String, String> copyOfParentMDC, UncheckedThrowingSupplier<T> supplier) {
222         try {
223             MDC.setContextMap(copyOfParentMDC);
224             return supplier.get();
225         } finally {
226             MDC.clear();
227         }
228     }
229
230 }