0d8e58878479cf5a7736308508f547454868800f
[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.Optional;
37 import java.util.UUID;
38 import javax.servlet.http.HttpServletRequest;
39 import javax.ws.rs.core.Response;
40 import org.apache.commons.io.IOUtils;
41 import org.apache.commons.lang3.StringUtils;
42 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
43 import org.onap.portalsdk.core.util.SystemProperties;
44 import org.onap.vid.exceptions.GenericUncheckedException;
45 import org.springframework.http.HttpMethod;
46 import org.springframework.stereotype.Service;
47 import org.springframework.web.context.request.RequestContextHolder;
48 import org.springframework.web.context.request.ServletRequestAttributes;
49
50 @Service
51 public class Logging {
52
53     public static final String HTTP_REQUESTS_OUTGOING = "http.requests.outgoing.";
54
55     public static final String REQUEST_ID_HEADER_KEY = SystemProperties.ECOMP_REQUEST_ID;
56     public static final String ONAP_REQUEST_ID_HEADER_KEY = "X-ONAP-RequestID";
57
58
59     private static ObjectMapper objectMapper = new ObjectMapper();
60
61     public static String getMethodName() {
62         return getMethodName(0);
63     }
64
65     public static String getMethodCallerName() {
66         return getMethodName(1);
67     }
68
69     private static String getMethodName(int depth) {
70         final StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
71         String thisClassName = stackTrace[1].getClassName();
72         final Optional<String> caller =
73                 Arrays.stream(stackTrace)
74                         .skip(1)
75                         .filter(not(frame -> frame.getClassName().equals(thisClassName)))
76                         .skip(depth)
77                         .map(StackTraceElement::getMethodName)
78                         .findFirst();
79         return caller.orElse("<unknonwn method name>");
80     }
81
82     public static EELFLogger getRequestsLogger(String serverName) {
83         return EELFLoggerDelegate.getLogger(HTTP_REQUESTS_OUTGOING +serverName);
84     }
85
86     public void logRequest(final EELFLogger logger, final HttpMethod method, final String url, final Object body) {
87         if (!logger.isDebugEnabled()) {
88             return;
89         }
90
91         if (body == null) {
92             logRequest(logger, method, url);
93             return;
94         }
95
96         try {
97             String bodyAsJson = objectMapper.writeValueAsString(body);
98             logger.debug("Sending  {} {} Body: {}", method.name(), url, bodyAsJson);
99         } catch (JsonProcessingException e) {
100             logRequest(logger, method, url);
101             logger.debug("Failed to parse object in logRequest. {}", body);
102         }
103     }
104
105     public void logRequest(final EELFLogger logger, final HttpMethod method, final String url) {
106         logger.debug("Sending  {} {}", method.name(), url);
107     }
108
109     public <T> void logResponse(final EELFLogger logger, final HttpMethod method, final String url, final Response response, final Class<T> entityClass) {
110         if (!logger.isDebugEnabled()) {
111             return;
112         }
113         if (response == null) {
114             logger.debug("Received {} {} response: null", method.name(), url);
115             return;
116         }
117         try {
118             response.bufferEntity();
119             logger.debug("Received {} {} Status: {} . Body: {}", method.name(), url, response.getStatus(), response.readEntity(entityClass));
120         }
121         catch (Exception e) {
122             logger.debug("Received {} {} Status: {} . Failed to read response as {}", method.name(), url, response.getStatus(), entityClass.getName());
123         }
124     }
125
126     public <T> void logResponse(final EELFLogger logger, final HttpMethod method, final String url, final HttpResponse<T> response) {
127         try {
128             logger.debug("Received {} {} Status: {} . Body: {}", method.name(),
129                 url, response.getStatus(), IOUtils.toString(response.getRawBody(), StandardCharsets.UTF_8));
130             response.getRawBody().reset();
131         }
132         catch (Exception e) {
133             logger.debug("Received {} {} Status: {} . Failed to read response", method.name(), url, response.getStatus());
134         }
135     }
136
137     public void logResponse(final EELFLogger logger, final HttpMethod method, final String url, final Response response) {
138         logResponse(logger, method, url, response, String.class);
139     }
140
141     public static HttpServletRequest getHttpServletRequest(){
142         return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
143     }
144
145     public static String extractOrGenerateRequestId() {
146         try {
147             return getHttpServletRequest().getHeader(REQUEST_ID_HEADER_KEY);
148         }
149         catch (IllegalStateException e) {
150             //in async jobs we don't have any HttpServletRequest
151             return UUID.randomUUID().toString();
152         }
153     }
154
155     public static void debugRequestDetails(Object requestDetails, final EELFLogger logger) {
156         if (logger.isDebugEnabled()) {
157             String requestDetailsAsString;
158             try {
159                 requestDetailsAsString = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT).writeValueAsString(requestDetails);
160             } catch (JsonProcessingException e) {
161                 requestDetailsAsString = "error: cannot stringify RequestDetails";
162             }
163             logger.debug("requestDetailsAsString: {}", requestDetailsAsString);
164         }
165     }
166
167     public static String exceptionToDescription(Throwable exceptionToDescribe) {
168         // Ignore top-most GenericUnchecked or Runtime exceptions that has no added message
169         final Throwable top = getThrowableList(exceptionToDescribe).stream()
170                 .filter(not(e -> ImmutableList.of(GenericUncheckedException.class, RuntimeException.class).contains(e.getClass())
171                         && StringUtils.equals(e.getMessage(), e.getCause() == null ? null : e.getCause().toString())))
172                 .findFirst().orElse(exceptionToDescribe);
173
174         final Throwable root = defaultIfNull(getRootCause(top), top);
175
176         String rootToString = root.toString();
177
178         // nullPointer description will include some context
179         if (root.getClass().equals(NullPointerException.class) && root.getStackTrace().length > 0) {
180             rootToString = String.format("NullPointerException at %s:%d",
181                     root.getStackTrace()[0].getFileName(),
182                     root.getStackTrace()[0].getLineNumber());
183         }
184
185         // if input is a single exception, without cause: top.toString
186         // else: return top.toString + root.toString
187         //       but not if root is already described in top.toString
188         if (top.equals(root)) {
189             return rootToString;
190         } else {
191             final String topToString = top.toString();
192             if (topToString.contains(root.getClass().getName()) && topToString.contains(root.getLocalizedMessage())) {
193                 return topToString;
194             } else {
195                 return topToString + ": " + rootToString;
196             }
197         }
198     }
199
200
201 }