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 java.net.HttpURLConnection;
27 import java.net.InetAddress;
28 import java.net.URLConnection;
29 import java.net.UnknownHostException;
30 import java.text.DateFormat;
31 import java.text.SimpleDateFormat;
32 import java.time.ZoneOffset;
33 import java.time.ZonedDateTime;
34 import java.time.format.DateTimeFormatter;
35 import java.time.temporal.ChronoUnit;
36 import java.util.Date;
37 import java.util.TimeZone;
38 import java.util.UUID;
39 import javax.net.ssl.HttpsURLConnection;
40 import javax.servlet.http.HttpServletRequest;
41 import javax.validation.constraints.NotNull;
42 import org.onap.clamp.authorization.AuthorizationController;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
46 import org.slf4j.event.Level;
47 import org.springframework.security.core.context.SecurityContextHolder;
50 * This class handles the special info that appear in the log, like RequestID,
53 public class LoggingUtils {
55 protected static final Logger logger = LoggerFactory.getLogger(LoggingUtils.class);
57 private static final DateFormat DATE_FORMAT = createDateFormat();
59 private static final String DATE_FORMATTER_ISO = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
61 /** String constant for messages <tt>ENTERING</tt>, <tt>EXITING</tt>, etc. */
62 private static final String EMPTY_MESSAGE = "";
64 /** Logger delegate. */
65 private Logger mlogger;
67 /** Automatic UUID, overrideable per adapter or per invocation. */
68 private static UUID sInstanceUUID = UUID.randomUUID();
73 public LoggingUtils(final Logger 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 =
186 defaultToUuid(request.getHeader(OnapLogConstants.Headers.REQUEST_ID));
187 final String invocationId =
188 defaultToUuid(request.getHeader(OnapLogConstants.Headers.INVOCATION_ID));
189 final String partnerName =
190 defaultToEmpty(request.getHeader(OnapLogConstants.Headers.PARTNER_NAME));
192 // Default the partner name to the user name used to login to clamp
193 if (partnerName.equalsIgnoreCase(EMPTY_MESSAGE)) {
194 MDC.put(OnapLogConstants.Mdcs.PARTNER_NAME,
195 AuthorizationController.getPrincipalName(SecurityContextHolder.getContext()));
198 // Set standard MDCs. Override this entire method if you want to set
199 // others, OR set them BEFORE or AFTER the invocation of #entering,
200 // depending on where you need them to appear, OR extend the
201 // ServiceDescriptor to add them.
202 MDC.put(OnapLogConstants.Mdcs.ENTRY_TIMESTAMP, ZonedDateTime.now(ZoneOffset.UTC)
203 .format(DateTimeFormatter.ofPattern(DATE_FORMATTER_ISO)));
204 MDC.put(OnapLogConstants.Mdcs.REQUEST_ID, requestId);
205 MDC.put(OnapLogConstants.Mdcs.INVOCATION_ID, invocationId);
206 MDC.put(OnapLogConstants.Mdcs.CLIENT_IP_ADDRESS, defaultToEmpty(request.getRemoteAddr()));
207 MDC.put(OnapLogConstants.Mdcs.SERVER_FQDN, defaultToEmpty(request.getServerName()));
208 MDC.put(OnapLogConstants.Mdcs.INSTANCE_UUID, defaultToEmpty(sInstanceUUID));
210 // Default the service name to the requestURI, in the event that
211 // no value has been provided.
212 if (serviceName == null || serviceName.equalsIgnoreCase(EMPTY_MESSAGE)) {
213 MDC.put(OnapLogConstants.Mdcs.SERVICE_NAME, request.getRequestURI());
215 MDC.put(OnapLogConstants.Mdcs.SERVICE_NAME, serviceName);
218 // Set the Response Status code to in progress
219 MDC.put(OnapLogConstants.Mdcs.RESPONSE_STATUS_CODE,
220 OnapLogConstants.ResponseStatus.INPROGRESS.toString());
223 this.mlogger.info(OnapLogConstants.Markers.ENTRY, "Entering");
227 * Report <tt>EXITING</tt> marker.
230 * @param code response code
231 * @param descrption response description
232 * @param severity response severity
233 * @param status response status code
235 public void exiting(int code, String descrption, Level severity,
236 OnapLogConstants.ResponseStatus status) {
239 MDC.put(OnapLogConstants.Mdcs.RESPONSE_CODE, defaultToEmpty(code));
240 MDC.put(OnapLogConstants.Mdcs.RESPONSE_DESCRIPTION, defaultToEmpty(descrption));
241 MDC.put(OnapLogConstants.Mdcs.RESPONSE_SEVERITY, defaultToEmpty(severity));
242 MDC.put(OnapLogConstants.Mdcs.RESPONSE_STATUS_CODE, defaultToEmpty(status));
245 this.mlogger.info(OnapLogConstants.Markers.EXIT, "Exiting");
251 private void setElapsedTime() {
252 ZonedDateTime startTime =
253 ZonedDateTime.parse(MDC.get(OnapLogConstants.Mdcs.ENTRY_TIMESTAMP),
254 DateTimeFormatter.ISO_DATE_TIME.withZone(ZoneOffset.UTC));
255 ZonedDateTime endTime = ZonedDateTime.now(ZoneOffset.UTC);
256 long duration = ChronoUnit.MILLIS.between(startTime, endTime);
257 MDC.put(OnapLogConstants.Mdcs.ELAPSED_TIME, String.valueOf(duration));
261 * Get the property value.
263 * @param name The name of the property
264 * @return The value of the property
266 public String getProperties(String name) {
267 return MDC.get(name);
271 * Report pending invocation with <tt>INVOKE</tt> marker,
272 * setting standard ONAP logging headers automatically.
274 * @param con The HTTP url connection
275 * @param targetEntity The target entity
276 * @param targetServiceName The target service name
277 * @return The HTTP url connection
279 public HttpURLConnection invoke(final HttpURLConnection con, String targetEntity,
280 String targetServiceName) {
281 return this.invokeGeneric(con, targetEntity, targetServiceName);
285 * Report pending invocation with <tt>INVOKE</tt> marker,
286 * setting standard ONAP logging headers automatically.
288 * @param targetEntity The target entity
289 * @param targetServiceName The target service name
291 public void invoke(String targetEntity, String targetServiceName) {
292 final String invocationId = UUID.randomUUID().toString();
294 invokeContext(targetEntity, targetServiceName, invocationId);
296 // Log INVOKE*, with the invocationID as the message body.
297 // (We didn't really want this kind of behavior in the standard,
298 // but is it worse than new, single-message MDC?)
299 this.mlogger.info(OnapLogConstants.Markers.INVOKE, "INVOKE");
300 this.mlogger.info(OnapLogConstants.Markers.INVOKE_SYNCHRONOUS + "{" + invocationId + "}");
304 * Report pending invocation with <tt>INVOKE</tt> marker,
305 * setting standard ONAP logging headers automatically.
307 * @param con The HTTPS url connection
308 * @param targetEntity The target entity
309 * @param targetServiceName The target service name
310 * @return The HTTPS url connection
312 public HttpsURLConnection invokeHttps(final HttpsURLConnection con, String targetEntity,
313 String targetServiceName) {
314 return this.invokeGeneric(con, targetEntity, targetServiceName);
318 * Report pending invocation with <tt>INVOKE-RETURN</tt> marker.
320 public void invokeReturn() {
321 MDC.put(OnapLogConstants.Mdcs.RESPONSE_STATUS_CODE,
322 OnapLogConstants.ResponseStatus.COMPLETE.toString());
323 // Add the Invoke-return marker and clear the needed MDC
324 this.mlogger.info(OnapLogConstants.Markers.INVOKE_RETURN, "INVOKE-RETURN");
325 invokeReturnContext();
329 * Dependency-free nullcheck.
331 * @param in to be checked
332 * @param <T> argument (and return) type
335 private static <T> T checkNotNull(final T in) {
337 throw new NullPointerException();
343 * Dependency-free string default.
345 * @param in to be filtered
346 * @return input string or null
348 private static String defaultToEmpty(final Object in) {
352 return in.toString();
356 * Dependency-free string default.
358 * @param in to be filtered
359 * @return input string or null
361 private static String defaultToUuid(final String in) {
363 return UUID.randomUUID().toString();
369 * Set target related logging variables in thread local data via MDC.
371 * @param targetEntity Target entity (an external/sub component, for ex. "sdc")
372 * @param targetServiceName Target service name (name of API invoked on target)
373 * @param invocationId The invocation ID
375 private void invokeContext(String targetEntity, String targetServiceName, String invocationId) {
376 MDC.put(OnapLogConstants.Mdcs.TARGET_ENTITY, defaultToEmpty(targetEntity));
377 MDC.put(OnapLogConstants.Mdcs.TARGET_SERVICE_NAME, defaultToEmpty(targetServiceName));
378 MDC.put(OnapLogConstants.Mdcs.INVOCATIONID_OUT, invocationId);
379 MDC.put(OnapLogConstants.Mdcs.INVOKE_TIMESTAMP, ZonedDateTime.now(ZoneOffset.UTC)
380 .format(DateTimeFormatter.ofPattern(DATE_FORMATTER_ISO)));
384 * Clear target related logging variables in thread local data via MDC.
386 private void invokeReturnContext() {
387 MDC.remove(OnapLogConstants.Mdcs.TARGET_ENTITY);
388 MDC.remove(OnapLogConstants.Mdcs.TARGET_SERVICE_NAME);
389 MDC.remove(OnapLogConstants.Mdcs.INVOCATIONID_OUT);
390 MDC.remove(OnapLogConstants.Mdcs.INVOKE_TIMESTAMP);
391 MDC.remove(OnapLogConstants.Mdcs.RESPONSE_STATUS_CODE);
394 private <T extends URLConnection> T invokeGeneric(final T con, String targetEntity,
395 String targetServiceName) {
396 final String invocationId = UUID.randomUUID().toString();
398 // Set standard HTTP headers on (southbound request) builder.
399 con.setRequestProperty(OnapLogConstants.Headers.REQUEST_ID,
400 defaultToEmpty(MDC.get(OnapLogConstants.Mdcs.REQUEST_ID)));
401 con.setRequestProperty(OnapLogConstants.Headers.INVOCATION_ID, invocationId);
402 con.setRequestProperty(OnapLogConstants.Headers.PARTNER_NAME,
403 defaultToEmpty(MDC.get(OnapLogConstants.Mdcs.PARTNER_NAME)));
405 invokeContext(targetEntity, targetServiceName, invocationId);
407 // Log INVOKE*, with the invocationID as the message body.
408 // (We didn't really want this kind of behavior in the standard,
409 // but is it worse than new, single-message MDC?)
410 this.mlogger.info(OnapLogConstants.Markers.INVOKE, "");
411 this.mlogger.info(OnapLogConstants.Markers.INVOKE_SYNCHRONOUS + "{" + invocationId + "}");