2 * ============LICENSE_START=======================================================
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
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.vid.utils;
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;
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;
49 public class Logging {
51 public static final String HTTP_REQUESTS_OUTGOING = "http.requests.outgoing.";
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";
57 private static ObjectMapper objectMapper = new ObjectMapper();
59 public static String getMethodName() {
60 return getMethodName(0);
63 public static String getMethodCallerName() {
64 return getMethodName(1);
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)
73 .filter(not(frame -> frame.getClassName().equals(thisClassName)))
75 .map(StackTraceElement::getMethodName)
77 return caller.orElse("<unknonwn method name>");
80 public static EELFLogger getRequestsLogger(String serverName) {
81 return EELFLoggerDelegate.getLogger(HTTP_REQUESTS_OUTGOING +serverName);
84 public void logRequest(final EELFLogger logger, final HttpMethod method, final String url, final Object body) {
85 if (!logger.isDebugEnabled()) {
90 logRequest(logger, method, url);
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);
103 public void logRequest(final EELFLogger logger, final HttpMethod method, final String url) {
104 logger.debug("Sending {} {}", method.name(), url);
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()) {
111 if (response == null) {
112 logger.debug("Received {} {} response: null", method.name(), url);
116 response.bufferEntity();
117 logger.debug("Received {} {} Status: {} . Body: {}", method.name(), url, response.getStatus(), response.readEntity(entityClass));
119 catch (Exception e) {
120 logger.debug("Received {} {} Status: {} . Failed to read response as {}", method.name(), url, response.getStatus(), entityClass.getName());
124 public <T> void logResponse(final EELFLogger logger, final HttpMethod method, final String url, final HttpResponse<T> response) {
126 logger.debug("Received {} {} Status: {} . Body: {}", method.name(), url, response.getStatus(), response.getBody());
128 catch (Exception e) {
129 logger.debug("Received {} {} Status: {} . Failed to read response", method.name(), url, response.getStatus());
133 public void logResponse(final EELFLogger logger, final HttpMethod method, final String url, final Response response) {
134 logResponse(logger, method, url, response, String.class);
137 public static HttpServletRequest getHttpServletRequest(){
138 return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
141 public static String extractOrGenerateRequestId() {
143 return getHttpServletRequest().getHeader(REQUEST_ID_HEADER_KEY);
145 catch (IllegalStateException e) {
146 //in async jobs we don't have any HttpServletRequest
147 return UUID.randomUUID().toString();
151 public static void debugRequestDetails(Object requestDetails, final EELFLogger logger) {
152 if (logger.isDebugEnabled()) {
153 String requestDetailsAsString;
155 requestDetailsAsString = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT).writeValueAsString(requestDetails);
156 } catch (JsonProcessingException e) {
157 requestDetailsAsString = "error: cannot stringify RequestDetails";
159 logger.debug("requestDetailsAsString: {}", requestDetailsAsString);
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);
170 final Throwable root = defaultIfNull(getRootCause(top), top);
172 String rootToString = root.toString();
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());
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)) {
187 final String topToString = top.toString();
188 if (topToString.contains(root.getClass().getName()) && topToString.contains(root.getLocalizedMessage())) {
191 return topToString + ": " + rootToString;