Merge "Using Generic client in SchedulerRestInterface"
[vid.git] / vid-app-common / src / main / java / org / onap / vid / utils / Logging.java
1 package org.onap.vid.utils;
2
3 import com.att.eelf.configuration.EELFLogger;
4 import com.fasterxml.jackson.core.JsonProcessingException;
5 import com.fasterxml.jackson.databind.ObjectMapper;
6 import com.fasterxml.jackson.databind.SerializationFeature;
7 import com.google.common.collect.ImmutableList;
8 import io.joshworks.restclient.http.HttpResponse;
9 import org.apache.commons.lang3.StringUtils;
10 import org.onap.vid.exceptions.GenericUncheckedException;
11 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
12 import org.onap.portalsdk.core.util.SystemProperties;
13 import org.springframework.http.HttpMethod;
14 import org.springframework.web.context.request.RequestContextHolder;
15 import org.springframework.web.context.request.ServletRequestAttributes;
16
17 import javax.servlet.http.HttpServletRequest;
18 import javax.ws.rs.ProcessingException;
19 import javax.ws.rs.core.Response;
20 import java.util.Arrays;
21 import java.util.Optional;
22 import java.util.UUID;
23
24 import static org.apache.commons.lang3.ObjectUtils.defaultIfNull;
25 import static org.apache.commons.lang3.exception.ExceptionUtils.getRootCause;
26 import static org.apache.commons.lang3.exception.ExceptionUtils.getThrowableList;
27 import static org.onap.vid.utils.Streams.not;
28
29 public class Logging {
30
31     Logging() {
32     }
33
34     public static final String HTTP_REQUESTS_OUTGOING = "http.requests.outgoing.";
35
36     public static final String REQUEST_ID_HEADER_KEY = SystemProperties.ECOMP_REQUEST_ID;
37
38     private static ObjectMapper objectMapper = new ObjectMapper();
39
40     public static String getMethodName() {
41         return getMethodName(0);
42     }
43
44     public static String getMethodCallerName() {
45         return getMethodName(1);
46     }
47
48     private static String getMethodName(int depth) {
49         final StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
50         String thisClassName = stackTrace[1].getClassName();
51         final Optional<String> caller =
52                 Arrays.stream(stackTrace)
53                         .skip(1)
54                         .filter(not(frame -> frame.getClassName().equals(thisClassName)))
55                         .skip(depth)
56                         .map(StackTraceElement::getMethodName)
57                         .findFirst();
58         return caller.orElse("<unknonwn method name>");
59     }
60
61     public static EELFLogger getRequestsLogger(String serverName) {
62         return EELFLoggerDelegate.getLogger(HTTP_REQUESTS_OUTGOING +serverName);
63     }
64
65     public static void logRequest(final EELFLogger logger, final HttpMethod method, final String url, final Object body) {
66         if (!logger.isDebugEnabled()) {
67             return;
68         }
69
70         if (body == null) {
71             logRequest(logger, method, url);
72             return;
73         }
74
75         try {
76             String bodyAsJson = objectMapper.writeValueAsString(body);
77             logger.debug("Sending  {} {} Body: {}", method.name(), url, bodyAsJson);
78         } catch (JsonProcessingException e) {
79             logRequest(logger, method, url);
80             logger.debug("Failed to parse object in logRequest. {}", body);
81         }
82     }
83
84     public static void logRequest(final EELFLogger logger, final HttpMethod method, final String url) {
85         logger.debug("Sending  {} {}", method.name(), url);
86     }
87
88     public static <T> void logResponse(final EELFLogger logger, final HttpMethod method, final String url, final Response response, final Class<T> entityClass) {
89         if (!logger.isDebugEnabled()) {
90             return;
91         }
92         if (response == null) {
93             logger.debug("Received {} {} response: null", method.name(), url);
94             return;
95         }
96         try {
97             response.bufferEntity();
98             logger.debug("Received {} {} Status: {} . Body: {}", method.name(), url, response.getStatus(), response.readEntity(entityClass));
99         }
100         catch (ProcessingException | IllegalStateException e) {
101             logger.debug("Received {} {} Status: {} . Failed to read response as {}", method.name(), url, response.getStatus(), entityClass.getName());
102         }
103     }
104
105     public static <T> void logResponse(final EELFLogger logger, final HttpMethod method, final String url, final HttpResponse<T> response) {
106         try {
107             logger.debug("Received {} {} Status: {} . Body: {}", method.name(), url, response.getStatus(), response.getBody());
108         }
109         catch (ProcessingException | IllegalStateException e) {
110             logger.debug("Received {} {} Status: {} . Failed to read response", method.name(), url, response.getStatus());
111         }
112     }
113
114     public static void logResponse(final EELFLogger logger, final HttpMethod method, final String url, final Response response) {
115         logResponse(logger, method, url, response, String.class);
116     }
117
118     public static HttpServletRequest getHttpServletRequest(){
119         return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
120     }
121
122     public static String extractOrGenerateRequestId() {
123         try {
124             return getHttpServletRequest().getHeader(REQUEST_ID_HEADER_KEY);
125         }
126         catch (IllegalStateException e) {
127             //in async jobs we don't have any HttpServletRequest
128             return UUID.randomUUID().toString();
129         }
130     }
131
132     public static void debugRequestDetails(Object requestDetails, final EELFLogger logger) {
133         if (logger.isDebugEnabled()) {
134             String requestDetailsAsString;
135             try {
136                 requestDetailsAsString = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT).writeValueAsString(requestDetails);
137             } catch (JsonProcessingException e) {
138                 requestDetailsAsString = "error: cannot stringify RequestDetails";
139             }
140             logger.debug("requestDetailsAsString: {}", requestDetailsAsString);
141         }
142     }
143
144     public static String exceptionToDescription(Throwable exceptionToDescribe) {
145         // Ignore top-most GenericUnchecked or Runtime exceptions that has no added message
146         final Throwable top = getThrowableList(exceptionToDescribe).stream()
147                 .filter(not(e -> ImmutableList.of(GenericUncheckedException.class, RuntimeException.class).contains(e.getClass())
148                         && StringUtils.equals(e.getMessage(), e.getCause() == null ? null : e.getCause().toString())))
149                 .findFirst().orElse(exceptionToDescribe);
150
151         final Throwable root = defaultIfNull(getRootCause(top), top);
152
153         String rootToString = root.toString();
154
155         // nullPointer description will include some context
156         if (root.getClass().equals(NullPointerException.class) && root.getStackTrace().length > 0) {
157             rootToString = String.format("NullPointerException at %s:%d",
158                     root.getStackTrace()[0].getFileName(),
159                     root.getStackTrace()[0].getLineNumber());
160         }
161
162         // if input is a single exception, without cause: top.toString
163         // else: return top.toString + root.toString
164         //       but not if root is already described in top.toString
165         if (top.equals(root)) {
166             return rootToString;
167         } else {
168             final String topToString = top.toString();
169             if (topToString.contains(root.getClass().getName()) && topToString.contains(root.getLocalizedMessage())) {
170                 return topToString;
171             } else {
172                 return topToString + ": " + rootToString;
173             }
174         }
175     }
176
177
178 }