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