2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END============================================
20 * ===================================================================
24 package org.onap.clamp.clds.util;
26 import com.att.eelf.configuration.EELFLogger;
27 import com.att.eelf.configuration.EELFManager;
29 import java.net.HttpURLConnection;
30 import java.net.InetAddress;
31 import java.net.URLConnection;
32 import java.net.UnknownHostException;
33 import java.text.DateFormat;
34 import java.text.SimpleDateFormat;
35 import java.time.ZoneOffset;
36 import java.time.ZonedDateTime;
37 import java.time.format.DateTimeFormatter;
38 import java.time.temporal.ChronoUnit;
39 import java.util.Date;
40 import java.util.TimeZone;
41 import java.util.UUID;
43 import javax.net.ssl.HttpsURLConnection;
44 import javax.servlet.http.HttpServletRequest;
45 import javax.validation.constraints.NotNull;
47 import org.onap.clamp.clds.service.DefaultUserNameHandler;
49 import org.slf4j.event.Level;
50 import org.springframework.security.core.context.SecurityContextHolder;
53 * This class handles the special info that appear in the log, like RequestID,
56 public class LoggingUtils {
57 protected static final EELFLogger logger = EELFManager.getInstance().getLogger(LoggingUtils.class);
59 private static final DateFormat DATE_FORMAT = createDateFormat();
61 /** String constant for messages <tt>ENTERING</tt>, <tt>EXITING</tt>, etc. */
62 private static final String EMPTY_MESSAGE = "";
64 /** Logger delegate. */
65 private EELFLogger mlogger;
67 /** Automatic UUID, overrideable per adapter or per invocation. */
68 private static UUID sInstanceUUID = UUID.randomUUID();
73 public LoggingUtils(final EELFLogger loggerP) {
74 this.mlogger = checkNotNull(loggerP);
78 * Set request related logging variables in thread local data via MDC.
80 * @param service Service Name of API (ex. "PUT template")
81 * @param partner Partner name (client or user invoking API)
83 public static void setRequestContext(String service, String partner) {
84 MDC.put("RequestId", UUID.randomUUID().toString());
85 MDC.put("ServiceName", service);
86 MDC.put("PartnerName", partner);
87 //Defaulting to HTTP/1.1 protocol
88 MDC.put("Protocol", "HTTP/1.1");
90 MDC.put("ServerFQDN", InetAddress.getLocalHost().getCanonicalHostName());
91 MDC.put("ServerIPAddress", InetAddress.getLocalHost().getHostAddress());
92 } catch (UnknownHostException e) {
93 logger.error("Failed to initiate setRequestContext", e);
98 * Set time related logging variables in thread local data via MDC.
100 * @param beginTimeStamp Start time
101 * @param endTimeStamp End time
103 public static void setTimeContext(@NotNull Date beginTimeStamp, @NotNull Date endTimeStamp) {
104 MDC.put("EntryTimestamp", generateTimestampStr(beginTimeStamp));
105 MDC.put("EndTimestamp", generateTimestampStr(endTimeStamp));
106 MDC.put("ElapsedTime", String.valueOf(endTimeStamp.getTime() - beginTimeStamp.getTime()));
110 * Set response related logging variables in thread local data via MDC.
112 * @param code Response code ("0" indicates success)
113 * @param description Response description
114 * @param className class name of invoking class
116 public static void setResponseContext(String code, String description, String className) {
117 MDC.put("ResponseCode", code);
118 MDC.put("StatusCode", "0".equals(code) ? "COMPLETE" : "ERROR");
119 MDC.put("ResponseDescription", description != null ? description : "");
120 MDC.put("ClassName", className != null ? className : "");
124 * Set target related logging variables in thread local data via MDC.
126 * @param targetEntity Target entity (an external/sub component, for ex. "sdc")
127 * @param targetServiceName Target service name (name of API invoked on target)
129 public static void setTargetContext(String targetEntity, String targetServiceName) {
130 MDC.put("TargetEntity", targetEntity != null ? targetEntity : "");
131 MDC.put("TargetServiceName", targetServiceName != null ? targetServiceName : "");
135 * Set error related logging variables in thread local data via MDC.
137 * @param code Error code
138 * @param description Error description
140 public static void setErrorContext(String code, String description) {
141 MDC.put("ErrorCode", code);
142 MDC.put("ErrorDescription", description != null ? description : "");
145 private static String generateTimestampStr(Date timeStamp) {
146 return DATE_FORMAT.format(timeStamp);
150 * Get a previously stored RequestID for the thread local data via MDC. If
151 * one was not previously stored, generate one, store it, and return that
154 * @return A string with the request ID
156 public static String getRequestId() {
157 String requestId = MDC.get(OnapLogConstants.Mdcs.REQUEST_ID);
158 if (requestId == null || requestId.isEmpty()) {
159 requestId = UUID.randomUUID().toString();
160 MDC.put(OnapLogConstants.Mdcs.REQUEST_ID, requestId);
165 private static DateFormat createDateFormat() {
166 DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
167 dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
171 /*********************************************************************************************
172 * Method for ONAP Application Logging Specification v1.2
173 ********************************************************************************************/
176 * Report <tt>ENTERING</tt> marker.
178 * @param request non-null incoming request (wrapper)
179 * @param serviceName service name
181 public void entering(HttpServletRequest request, String serviceName) {
183 checkNotNull(request);
184 // Extract MDC values from standard HTTP headers.
185 final String requestId = defaultToUuid(request.getHeader(OnapLogConstants.Headers.REQUEST_ID));
186 final String invocationId = defaultToUuid(request.getHeader(OnapLogConstants.Headers.INVOCATION_ID));
187 final String partnerName = defaultToEmpty(request.getHeader(OnapLogConstants.Headers.PARTNER_NAME));
189 // Default the partner name to the user name used to login to clamp
190 if (partnerName.equalsIgnoreCase(EMPTY_MESSAGE)) {
191 MDC.put(OnapLogConstants.Mdcs.PARTNER_NAME, new DefaultUserNameHandler()
192 .retrieveUserName(SecurityContextHolder.getContext()));
195 // Set standard MDCs. Override this entire method if you want to set
196 // others, OR set them BEFORE or AFTER the invocation of #entering,
197 // depending on where you need them to appear, OR extend the
198 // ServiceDescriptor to add them.
199 MDC.put(OnapLogConstants.Mdcs.ENTRY_TIMESTAMP,
200 ZonedDateTime.now(ZoneOffset.UTC)
201 .format(DateTimeFormatter.ISO_INSTANT));
202 MDC.put(OnapLogConstants.Mdcs.REQUEST_ID, requestId);
203 MDC.put(OnapLogConstants.Mdcs.INVOCATION_ID, invocationId);
204 MDC.put(OnapLogConstants.Mdcs.CLIENT_IP_ADDRESS, defaultToEmpty(request.getRemoteAddr()));
205 MDC.put(OnapLogConstants.Mdcs.SERVER_FQDN, defaultToEmpty(request.getServerName()));
206 MDC.put(OnapLogConstants.Mdcs.INSTANCE_UUID, defaultToEmpty(sInstanceUUID));
208 // Default the service name to the requestURI, in the event that
209 // no value has been provided.
210 if (serviceName == null
211 || serviceName.equalsIgnoreCase(EMPTY_MESSAGE)) {
212 MDC.put(OnapLogConstants.Mdcs.SERVICE_NAME, request.getRequestURI());
214 MDC.put(OnapLogConstants.Mdcs.SERVICE_NAME, serviceName);
217 this.mlogger.info(OnapLogConstants.Markers.ENTRY);
221 * Report <tt>EXITING</tt> marker.
224 * @param code response code
225 * @param descrption response description
226 * @param severity response severity
227 * @param status response status code
229 public void exiting(String code, String descrption, Level severity, OnapLogConstants.ResponseStatus status) {
231 MDC.put(OnapLogConstants.Mdcs.RESPONSE_CODE, defaultToEmpty(code));
232 MDC.put(OnapLogConstants.Mdcs.RESPONSE_DESCRIPTION, defaultToEmpty(descrption));
233 MDC.put(OnapLogConstants.Mdcs.RESPONSE_SEVERITY, defaultToEmpty(severity));
234 MDC.put(OnapLogConstants.Mdcs.RESPONSE_STATUS_CODE, defaultToEmpty(status));
236 ZonedDateTime startTime = ZonedDateTime.parse(MDC.get(OnapLogConstants.Mdcs.ENTRY_TIMESTAMP),
237 DateTimeFormatter.ISO_INSTANT.withZone(ZoneOffset.UTC));
238 ZonedDateTime endTime = ZonedDateTime.now(ZoneOffset.UTC);
239 MDC.put(OnapLogConstants.Mdcs.END_TIMESTAMP, endTime.format(DateTimeFormatter.ISO_INSTANT));
240 long duration = ChronoUnit.MILLIS.between(startTime, endTime);
241 MDC.put(OnapLogConstants.Mdcs.ELAPSED_TIMESTAMP, String.valueOf(duration));
242 this.mlogger.info(OnapLogConstants.Markers.EXIT);
250 * Get the property value.
252 * @param name The name of the property
253 * @return The value of the property
255 public String getProperties(String name) {
256 return MDC.get(name);
260 * Report pending invocation with <tt>INVOKE</tt> marker,
261 * setting standard ONAP logging headers automatically.
263 * @param con The HTTP url connection
264 * @param targetEntity The target entity
265 * @param targetServiceName The target service name
266 * @return The HTTP url connection
268 public HttpURLConnection invoke(final HttpURLConnection con, String targetEntity, String targetServiceName) {
269 return this.invokeGeneric(con, targetEntity, targetServiceName);
273 * Report pending invocation with <tt>INVOKE</tt> marker,
274 * setting standard ONAP logging headers automatically.
276 * @param targetEntity The target entity
277 * @param targetServiceName The target service name
279 public void invoke(String targetEntity, String targetServiceName) {
280 final String invocationId = UUID.randomUUID().toString();
282 invokeContext(targetEntity, targetServiceName, invocationId);
284 // Log INVOKE*, with the invocationID as the message body.
285 // (We didn't really want this kind of behavior in the standard,
286 // but is it worse than new, single-message MDC?)
287 this.mlogger.info(OnapLogConstants.Markers.INVOKE);
288 this.mlogger.info(OnapLogConstants.Markers.INVOKE_SYNC + "{" + invocationId + "}");
292 * Report pending invocation with <tt>INVOKE</tt> marker,
293 * setting standard ONAP logging headers automatically.
295 * @param con The HTTPS url connection
296 * @param targetEntity The target entity
297 * @param targetServiceName The target service name
298 * @return The HTTPS url connection
300 public HttpsURLConnection invokeHttps(final HttpsURLConnection con, String targetEntity, String targetServiceName) {
301 return this.invokeGeneric(con, targetEntity, targetServiceName);
305 * Report pending invocation with <tt>INVOKE-RETURN</tt> marker.
307 public void invokeReturn() {
308 // Add the Invoke-return marker and clear the needed MDC
309 this.mlogger.info(OnapLogConstants.Markers.INVOKE_RETURN);
310 invokeReturnContext();
314 * Dependency-free nullcheck.
316 * @param in to be checked
317 * @param <T> argument (and return) type
320 private static <T> T checkNotNull(final T in) {
322 throw new NullPointerException();
328 * Dependency-free string default.
330 * @param in to be filtered
331 * @return input string or null
333 private static String defaultToEmpty(final Object in) {
337 return in.toString();
341 * Dependency-free string default.
343 * @param in to be filtered
344 * @return input string or null
346 private static String defaultToUuid(final String in) {
348 return UUID.randomUUID().toString();
354 * Set target related logging variables in thread local data via MDC.
356 * @param targetEntity Target entity (an external/sub component, for ex. "sdc")
357 * @param targetServiceName Target service name (name of API invoked on target)
358 * @param invocationId The invocation ID
360 private void invokeContext(String targetEntity, String targetServiceName, String invocationId) {
361 MDC.put(OnapLogConstants.Mdcs.TARGET_ENTITY, defaultToEmpty(targetEntity));
362 MDC.put(OnapLogConstants.Mdcs.TARGET_SERVICE_NAME, defaultToEmpty(targetServiceName));
363 MDC.put(OnapLogConstants.Mdcs.INVOCATIONID_OUT, invocationId);
364 MDC.put(OnapLogConstants.Mdcs.INVOKE_TIMESTAMP,
365 ZonedDateTime.now(ZoneOffset.UTC)
366 .format(DateTimeFormatter.ISO_INSTANT));
370 * Clear target related logging variables in thread local data via MDC.
372 private void invokeReturnContext() {
373 MDC.remove(OnapLogConstants.Mdcs.TARGET_ENTITY);
374 MDC.remove(OnapLogConstants.Mdcs.TARGET_SERVICE_NAME);
375 MDC.remove(OnapLogConstants.Mdcs.INVOCATIONID_OUT);
376 MDC.remove(OnapLogConstants.Mdcs.INVOKE_TIMESTAMP);
379 private <T extends URLConnection> T invokeGeneric(final T con, String targetEntity, String targetServiceName) {
380 final String invocationId = UUID.randomUUID().toString();
382 // Set standard HTTP headers on (southbound request) builder.
383 con.setRequestProperty(OnapLogConstants.Headers.REQUEST_ID,
384 defaultToEmpty(MDC.get(OnapLogConstants.Mdcs.REQUEST_ID)));
385 con.setRequestProperty(OnapLogConstants.Headers.INVOCATION_ID,
387 con.setRequestProperty(OnapLogConstants.Headers.PARTNER_NAME,
388 defaultToEmpty(MDC.get(OnapLogConstants.Mdcs.PARTNER_NAME)));
390 invokeContext(targetEntity, targetServiceName, invocationId);
392 // Log INVOKE*, with the invocationID as the message body.
393 // (We didn't really want this kind of behavior in the standard,
394 // but is it worse than new, single-message MDC?)
395 this.mlogger.info(OnapLogConstants.Markers.INVOKE);
396 this.mlogger.info(OnapLogConstants.Markers.INVOKE_SYNC + "{" + invocationId + "}");