2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 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.logging.filter.base;
23 import java.net.InetAddress;
24 import java.net.UnknownHostException;
25 import java.time.ZoneOffset;
26 import java.time.ZonedDateTime;
27 import java.time.format.DateTimeFormatter;
28 import java.time.temporal.ChronoUnit;
29 import java.util.UUID;
31 import javax.servlet.http.HttpServletRequest;
32 import javax.ws.rs.core.HttpHeaders;
33 import javax.ws.rs.core.Response;
35 import org.onap.logging.ref.slf4j.ONAPLogConstants;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
40 public class MDCSetup {
42 protected static Logger logger = LoggerFactory.getLogger(MDCSetup.class);
44 private static final String INSTANCE_UUID = UUID.randomUUID().toString();
46 public void setInstanceID() {
47 MDC.put(ONAPLogConstants.MDCs.INSTANCE_UUID, INSTANCE_UUID);
50 public void setServerFQDN() {
51 String serverFQDN = "";
52 InetAddress addr = null;
54 addr = InetAddress.getLocalHost();
55 serverFQDN = addr.getCanonicalHostName();
56 MDC.put(ONAPLogConstants.MDCs.SERVER_IP_ADDRESS, addr.getHostAddress());
57 } catch (UnknownHostException e) {
58 logger.warn("Cannot Resolve Host Name");
61 MDC.put(ONAPLogConstants.MDCs.SERVER_FQDN, serverFQDN);
64 public void setClientIPAddress(HttpServletRequest httpServletRequest) {
65 String clientIpAddress = "";
66 if (httpServletRequest != null) {
67 // This logic is to avoid setting the client ip address to that of the load
68 // balancer in front of the application
69 String getForwadedFor = httpServletRequest.getHeader("X-Forwarded-For");
70 if (getForwadedFor != null) {
71 clientIpAddress = getForwadedFor;
73 clientIpAddress = httpServletRequest.getRemoteAddr();
76 MDC.put(ONAPLogConstants.MDCs.CLIENT_IP_ADDRESS, clientIpAddress);
79 public void setEntryTimeStamp() {
80 MDC.put(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP,
81 ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT));
84 public String getRequestId(SimpleMap headers) {
85 logger.trace("Checking X-ONAP-RequestID header for requestId.");
86 String requestId = headers.get(ONAPLogConstants.Headers.REQUEST_ID);
87 if (requestId != null && !requestId.isEmpty() && isValidUUID(requestId)) {
90 if (requestId != null && !requestId.isEmpty()) {
92 return UUID.randomUUID().toString();
94 logger.trace("No valid X-ONAP-RequestID header value. Checking X-RequestID header for requestId.");
95 requestId = headers.get(Constants.HttpHeaders.HEADER_REQUEST_ID);
96 if (requestId != null && !requestId.isEmpty() && isValidUUID(requestId)) {
99 if (requestId != null && !requestId.isEmpty()) {
101 return UUID.randomUUID().toString();
103 logger.trace("No valid X-RequestID header value. Checking X-TransactionID header for requestId.");
104 requestId = headers.get(Constants.HttpHeaders.TRANSACTION_ID);
105 if (requestId != null && !requestId.isEmpty() && isValidUUID(requestId)) {
108 if (requestId != null && !requestId.isEmpty()) {
110 return UUID.randomUUID().toString();
112 logger.trace("No valid X-TransactionID header value. Checking X-ECOMP-RequestID header for requestId.");
113 requestId = headers.get(Constants.HttpHeaders.ECOMP_REQUEST_ID);
114 if (requestId != null && !requestId.isEmpty() && isValidUUID(requestId)) {
117 if (requestId != null && !requestId.isEmpty()) {
119 return UUID.randomUUID().toString();
124 protected boolean isValidUUID(String transId) {
126 UUID.fromString(transId);
127 } catch (IllegalArgumentException e) {
133 public void setInvocationId(SimpleMap headers) {
134 String invocationId = headers.get(ONAPLogConstants.Headers.INVOCATION_ID);
135 if (invocationId == null || invocationId.isEmpty())
136 invocationId = UUID.randomUUID().toString();
137 MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, invocationId);
140 public void setInvocationIdFromMDC() {
141 String invocationId = MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID);
142 if (invocationId == null || invocationId.isEmpty())
143 invocationId = UUID.randomUUID().toString();
144 MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, invocationId);
147 public void setMDCPartnerName(SimpleMap headers) {
148 logger.trace("Checking X-ONAP-PartnerName header for partnerName.");
149 String partnerName = headers.get(ONAPLogConstants.Headers.PARTNER_NAME);
150 if (partnerName == null || partnerName.isEmpty()) {
151 logger.trace("No valid X-ONAP-PartnerName header value. Checking User-Agent header for partnerName.");
152 partnerName = headers.get(HttpHeaders.USER_AGENT);
153 if (partnerName == null || partnerName.isEmpty()) {
154 logger.trace("No valid User-Agent header value. Checking X-ClientID header for partnerName.");
155 partnerName = headers.get(Constants.HttpHeaders.CLIENT_ID);
156 if (partnerName == null || partnerName.isEmpty()) {
157 logger.trace("No valid partnerName headers. Defaulting partnerName to UNKNOWN.");
158 partnerName = Constants.DefaultValues.UNKNOWN;
162 MDC.put(ONAPLogConstants.MDCs.PARTNER_NAME, partnerName);
165 public void setLogTimestamp() {
166 MDC.put(ONAPLogConstants.MDCs.LOG_TIMESTAMP,
167 ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT));
170 public void setElapsedTime() {
171 DateTimeFormatter timeFormatter = DateTimeFormatter.ISO_ZONED_DATE_TIME;
172 ZonedDateTime entryTimestamp =
173 ZonedDateTime.parse(MDC.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP), timeFormatter);
174 ZonedDateTime endTimestamp = ZonedDateTime.parse(MDC.get(ONAPLogConstants.MDCs.LOG_TIMESTAMP), timeFormatter);
176 MDC.put(ONAPLogConstants.MDCs.ELAPSED_TIME,
177 Long.toString(ChronoUnit.MILLIS.between(entryTimestamp, endTimestamp)));
180 public void setElapsedTimeInvokeTimestamp() {
181 DateTimeFormatter timeFormatter = DateTimeFormatter.ISO_ZONED_DATE_TIME;
182 ZonedDateTime entryTimestamp =
183 ZonedDateTime.parse(MDC.get(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP), timeFormatter);
184 ZonedDateTime endTimestamp = ZonedDateTime.parse(MDC.get(ONAPLogConstants.MDCs.LOG_TIMESTAMP), timeFormatter);
186 MDC.put(ONAPLogConstants.MDCs.ELAPSED_TIME,
187 Long.toString(ChronoUnit.MILLIS.between(entryTimestamp, endTimestamp)));
190 public void setResponseStatusCode(int code) {
192 if (Response.Status.Family.familyOf(code).equals(Response.Status.Family.SUCCESSFUL)) {
193 statusCode = ONAPLogConstants.ResponseStatus.COMPLETE.toString();
195 statusCode = ONAPLogConstants.ResponseStatus.ERROR.toString();
199 MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, statusCode);
202 public void setTargetEntity(ONAPComponentsList targetEntity) {
203 MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY, targetEntity.toString());
206 public void clearClientMDCs() {
207 // MDC.remove(ONAPLogConstants.MDCs.INVOCATION_ID);
208 MDC.remove(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION);
209 MDC.remove(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE);
210 MDC.remove(ONAPLogConstants.MDCs.RESPONSE_CODE);
211 MDC.remove(ONAPLogConstants.MDCs.TARGET_ENTITY);
212 MDC.remove(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME);
213 MDC.remove(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP);
214 MDC.remove(ONAPLogConstants.MDCs.ERROR_CODE);
215 MDC.remove(ONAPLogConstants.MDCs.ERROR_DESC);
218 public void setResponseDescription(int statusCode) {
219 MDC.put(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION, Response.Status.fromStatusCode(statusCode).toString());
222 public void setErrorCode(int statusCode) {
223 MDC.put(ONAPLogConstants.MDCs.ERROR_CODE, String.valueOf(statusCode));
226 public void setErrorDesc(int statusCode) {
227 MDC.put(ONAPLogConstants.MDCs.ERROR_DESC, Response.Status.fromStatusCode(statusCode).toString());
230 public String getProperty(String property) {
231 logger.info("Checking for system property [{}]", property);
232 String propertyValue = System.getProperty(property);
233 if (propertyValue == null || propertyValue.isEmpty()) {
234 logger.info("System property was null or empty. Checking environment variable for: {}", property);
235 propertyValue = System.getenv(property);
236 if (propertyValue == null || propertyValue.isEmpty()) {
237 logger.info("Environment variable: {} was null or empty", property);
240 return propertyValue;