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;
28 import java.net.HttpURLConnection;
29 import java.net.InetAddress;
30 import java.net.URLConnection;
31 import java.net.UnknownHostException;
32 import java.text.DateFormat;
33 import java.text.SimpleDateFormat;
34 import java.time.ZoneOffset;
35 import java.time.ZonedDateTime;
36 import java.time.format.DateTimeFormatter;
37 import java.time.temporal.ChronoUnit;
38 import java.util.Date;
39 import java.util.TimeZone;
40 import java.util.UUID;
41 import javax.net.ssl.HttpsURLConnection;
42 import javax.servlet.http.HttpServletRequest;
43 import javax.validation.constraints.NotNull;
44 import org.onap.clamp.authorization.AuthorizationController;
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 {
54 protected static final EELFLogger logger = EELFManager.getInstance().getLogger(LoggingUtils.class);
56 private static final DateFormat DATE_FORMAT = createDateFormat();
58 /** String constant for messages <tt>ENTERING</tt>, <tt>EXITING</tt>, etc. */
59 private static final String EMPTY_MESSAGE = "";
61 /** Logger delegate. */
62 private EELFLogger mlogger;
64 /** Automatic UUID, overrideable per adapter or per invocation. */
65 private static UUID sInstanceUUID = UUID.randomUUID();
70 public LoggingUtils(final EELFLogger loggerP) {
71 this.mlogger = checkNotNull(loggerP);
75 * Set request related logging variables in thread local data via MDC.
77 * @param service Service Name of API (ex. "PUT template")
78 * @param partner Partner name (client or user invoking API)
80 public static void setRequestContext(String service, String partner) {
81 MDC.put("RequestId", UUID.randomUUID().toString());
82 MDC.put("ServiceName", service);
83 MDC.put("PartnerName", partner);
84 //Defaulting to HTTP/1.1 protocol
85 MDC.put("Protocol", "HTTP/1.1");
87 MDC.put("ServerFQDN", InetAddress.getLocalHost().getCanonicalHostName());
88 MDC.put("ServerIPAddress", InetAddress.getLocalHost().getHostAddress());
89 } catch (UnknownHostException e) {
90 logger.error("Failed to initiate setRequestContext", e);
95 * Set time related logging variables in thread local data via MDC.
97 * @param beginTimeStamp Start time
98 * @param endTimeStamp End time
100 public static void setTimeContext(@NotNull Date beginTimeStamp, @NotNull Date endTimeStamp) {
101 MDC.put("EntryTimestamp", generateTimestampStr(beginTimeStamp));
102 MDC.put("EndTimestamp", generateTimestampStr(endTimeStamp));
103 MDC.put("ElapsedTime", String.valueOf(endTimeStamp.getTime() - beginTimeStamp.getTime()));
107 * Set response related logging variables in thread local data via MDC.
109 * @param code Response code ("0" indicates success)
110 * @param description Response description
111 * @param className class name of invoking class
113 public static void setResponseContext(String code, String description, String className) {
114 MDC.put("ResponseCode", code);
115 MDC.put("StatusCode", "0".equals(code) ? "COMPLETE" : "ERROR");
116 MDC.put("ResponseDescription", description != null ? description : "");
117 MDC.put("ClassName", className != null ? className : "");
121 * Set target related logging variables in thread local data via MDC.
123 * @param targetEntity Target entity (an external/sub component, for ex. "sdc")
124 * @param targetServiceName Target service name (name of API invoked on target)
126 public static void setTargetContext(String targetEntity, String targetServiceName) {
127 MDC.put("TargetEntity", targetEntity != null ? targetEntity : "");
128 MDC.put("TargetServiceName", targetServiceName != null ? targetServiceName : "");
132 * Set error related logging variables in thread local data via MDC.
134 * @param code Error code
135 * @param description Error description
137 public static void setErrorContext(String code, String description) {
138 MDC.put("ErrorCode", code);
139 MDC.put("ErrorDescription", description != null ? description : "");
142 private static String generateTimestampStr(Date timeStamp) {
143 return DATE_FORMAT.format(timeStamp);
147 * Get a previously stored RequestID for the thread local data via MDC. If
148 * one was not previously stored, generate one, store it, and return that
151 * @return A string with the request ID
153 public static String getRequestId() {
154 String requestId = MDC.get(OnapLogConstants.Mdcs.REQUEST_ID);
155 if (requestId == null || requestId.isEmpty()) {
156 requestId = UUID.randomUUID().toString();
157 MDC.put(OnapLogConstants.Mdcs.REQUEST_ID, requestId);
162 private static DateFormat createDateFormat() {
163 DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
164 dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
168 /*********************************************************************************************
169 * Method for ONAP Application Logging Specification v1.2
170 ********************************************************************************************/
173 * Report <tt>ENTERING</tt> marker.
175 * @param request non-null incoming request (wrapper)
176 * @param serviceName service name
178 public void entering(HttpServletRequest request, String serviceName) {
180 checkNotNull(request);
181 // Extract MDC values from standard HTTP headers.
182 final String requestId = defaultToUuid(request.getHeader(OnapLogConstants.Headers.REQUEST_ID));
183 final String invocationId = defaultToUuid(request.getHeader(OnapLogConstants.Headers.INVOCATION_ID));
184 final String partnerName = defaultToEmpty(request.getHeader(OnapLogConstants.Headers.PARTNER_NAME));
186 // Default the partner name to the user name used to login to clamp
187 if (partnerName.equalsIgnoreCase(EMPTY_MESSAGE)) {
188 MDC.put(OnapLogConstants.Mdcs.PARTNER_NAME,
189 AuthorizationController.getPrincipalName(SecurityContextHolder.getContext()));
192 // Set standard MDCs. Override this entire method if you want to set
193 // others, OR set them BEFORE or AFTER the invocation of #entering,
194 // depending on where you need them to appear, OR extend the
195 // ServiceDescriptor to add them.
196 MDC.put(OnapLogConstants.Mdcs.ENTRY_TIMESTAMP,
197 ZonedDateTime.now(ZoneOffset.UTC)
198 .format(DateTimeFormatter.ISO_INSTANT));
199 MDC.put(OnapLogConstants.Mdcs.REQUEST_ID, requestId);
200 MDC.put(OnapLogConstants.Mdcs.INVOCATION_ID, invocationId);
201 MDC.put(OnapLogConstants.Mdcs.CLIENT_IP_ADDRESS, defaultToEmpty(request.getRemoteAddr()));
202 MDC.put(OnapLogConstants.Mdcs.SERVER_FQDN, defaultToEmpty(request.getServerName()));
203 MDC.put(OnapLogConstants.Mdcs.INSTANCE_UUID, defaultToEmpty(sInstanceUUID));
205 // Default the service name to the requestURI, in the event that
206 // no value has been provided.
207 if (serviceName == null
208 || serviceName.equalsIgnoreCase(EMPTY_MESSAGE)) {
209 MDC.put(OnapLogConstants.Mdcs.SERVICE_NAME, request.getRequestURI());
211 MDC.put(OnapLogConstants.Mdcs.SERVICE_NAME, serviceName);
214 this.mlogger.info(OnapLogConstants.Markers.ENTRY);
218 * Report <tt>EXITING</tt> marker.
221 * @param code response code
222 * @param descrption response description
223 * @param severity response severity
224 * @param status response status code
226 public void exiting(String code, String descrption, Level severity, OnapLogConstants.ResponseStatus status) {
228 MDC.put(OnapLogConstants.Mdcs.RESPONSE_CODE, defaultToEmpty(code));
229 MDC.put(OnapLogConstants.Mdcs.RESPONSE_DESCRIPTION, defaultToEmpty(descrption));
230 MDC.put(OnapLogConstants.Mdcs.RESPONSE_SEVERITY, defaultToEmpty(severity));
231 MDC.put(OnapLogConstants.Mdcs.RESPONSE_STATUS_CODE, defaultToEmpty(status));
233 ZonedDateTime startTime = ZonedDateTime.parse(MDC.get(OnapLogConstants.Mdcs.ENTRY_TIMESTAMP),
234 DateTimeFormatter.ISO_INSTANT.withZone(ZoneOffset.UTC));
235 ZonedDateTime endTime = ZonedDateTime.now(ZoneOffset.UTC);
236 MDC.put(OnapLogConstants.Mdcs.END_TIMESTAMP, endTime.format(DateTimeFormatter.ISO_INSTANT));
237 long duration = ChronoUnit.MILLIS.between(startTime, endTime);
238 MDC.put(OnapLogConstants.Mdcs.ELAPSED_TIMESTAMP, String.valueOf(duration));
239 this.mlogger.info(OnapLogConstants.Markers.EXIT);
247 * Get the property value.
249 * @param name The name of the property
250 * @return The value of the property
252 public String getProperties(String name) {
253 return MDC.get(name);
257 * Report pending invocation with <tt>INVOKE</tt> marker,
258 * setting standard ONAP logging headers automatically.
260 * @param con The HTTP url connection
261 * @param targetEntity The target entity
262 * @param targetServiceName The target service name
263 * @return The HTTP url connection
265 public HttpURLConnection invoke(final HttpURLConnection con, String targetEntity, String targetServiceName) {
266 return this.invokeGeneric(con, targetEntity, targetServiceName);
270 * Report pending invocation with <tt>INVOKE</tt> marker,
271 * setting standard ONAP logging headers automatically.
273 * @param targetEntity The target entity
274 * @param targetServiceName The target service name
276 public void invoke(String targetEntity, String targetServiceName) {
277 final String invocationId = UUID.randomUUID().toString();
279 invokeContext(targetEntity, targetServiceName, invocationId);
281 // Log INVOKE*, with the invocationID as the message body.
282 // (We didn't really want this kind of behavior in the standard,
283 // but is it worse than new, single-message MDC?)
284 this.mlogger.info(OnapLogConstants.Markers.INVOKE);
285 this.mlogger.info(OnapLogConstants.Markers.INVOKE_SYNC + "{" + invocationId + "}");
289 * Report pending invocation with <tt>INVOKE</tt> marker,
290 * setting standard ONAP logging headers automatically.
292 * @param con The HTTPS url connection
293 * @param targetEntity The target entity
294 * @param targetServiceName The target service name
295 * @return The HTTPS url connection
297 public HttpsURLConnection invokeHttps(final HttpsURLConnection con, String targetEntity, String targetServiceName) {
298 return this.invokeGeneric(con, targetEntity, targetServiceName);
302 * Report pending invocation with <tt>INVOKE-RETURN</tt> marker.
304 public void invokeReturn() {
305 // Add the Invoke-return marker and clear the needed MDC
306 this.mlogger.info(OnapLogConstants.Markers.INVOKE_RETURN);
307 invokeReturnContext();
311 * Dependency-free nullcheck.
313 * @param in to be checked
314 * @param <T> argument (and return) type
317 private static <T> T checkNotNull(final T in) {
319 throw new NullPointerException();
325 * Dependency-free string default.
327 * @param in to be filtered
328 * @return input string or null
330 private static String defaultToEmpty(final Object in) {
334 return in.toString();
338 * Dependency-free string default.
340 * @param in to be filtered
341 * @return input string or null
343 private static String defaultToUuid(final String in) {
345 return UUID.randomUUID().toString();
351 * Set target related logging variables in thread local data via MDC.
353 * @param targetEntity Target entity (an external/sub component, for ex. "sdc")
354 * @param targetServiceName Target service name (name of API invoked on target)
355 * @param invocationId The invocation ID
357 private void invokeContext(String targetEntity, String targetServiceName, String invocationId) {
358 MDC.put(OnapLogConstants.Mdcs.TARGET_ENTITY, defaultToEmpty(targetEntity));
359 MDC.put(OnapLogConstants.Mdcs.TARGET_SERVICE_NAME, defaultToEmpty(targetServiceName));
360 MDC.put(OnapLogConstants.Mdcs.INVOCATIONID_OUT, invocationId);
361 MDC.put(OnapLogConstants.Mdcs.INVOKE_TIMESTAMP,
362 ZonedDateTime.now(ZoneOffset.UTC)
363 .format(DateTimeFormatter.ISO_INSTANT));
367 * Clear target related logging variables in thread local data via MDC.
369 private void invokeReturnContext() {
370 MDC.remove(OnapLogConstants.Mdcs.TARGET_ENTITY);
371 MDC.remove(OnapLogConstants.Mdcs.TARGET_SERVICE_NAME);
372 MDC.remove(OnapLogConstants.Mdcs.INVOCATIONID_OUT);
373 MDC.remove(OnapLogConstants.Mdcs.INVOKE_TIMESTAMP);
376 private <T extends URLConnection> T invokeGeneric(final T con, String targetEntity, String targetServiceName) {
377 final String invocationId = UUID.randomUUID().toString();
379 // Set standard HTTP headers on (southbound request) builder.
380 con.setRequestProperty(OnapLogConstants.Headers.REQUEST_ID,
381 defaultToEmpty(MDC.get(OnapLogConstants.Mdcs.REQUEST_ID)));
382 con.setRequestProperty(OnapLogConstants.Headers.INVOCATION_ID,
384 con.setRequestProperty(OnapLogConstants.Headers.PARTNER_NAME,
385 defaultToEmpty(MDC.get(OnapLogConstants.Mdcs.PARTNER_NAME)));
387 invokeContext(targetEntity, targetServiceName, invocationId);
389 // Log INVOKE*, with the invocationID as the message body.
390 // (We didn't really want this kind of behavior in the standard,
391 // but is it worse than new, single-message MDC?)
392 this.mlogger.info(OnapLogConstants.Markers.INVOKE);
393 this.mlogger.info(OnapLogConstants.Markers.INVOKE_SYNC + "{" + invocationId + "}");