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.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;
42 import javax.net.ssl.HttpsURLConnection;
43 import javax.servlet.http.HttpServletRequest;
44 import javax.validation.constraints.NotNull;
46 import org.onap.clamp.clds.service.DefaultUserNameHandler;
48 import org.slf4j.event.Level;
49 import org.springframework.security.core.context.SecurityContextHolder;
52 * This class handles the special info that appear in the log, like RequestID,
55 public class LoggingUtils {
56 protected static final EELFLogger logger = EELFManager.getInstance().getLogger(LoggingUtils.class);
58 private static final DateFormat DATE_FORMAT = createDateFormat();
60 /** String constant for messages <tt>ENTERING</tt>, <tt>EXITING</tt>, etc. */
61 private static final String EMPTY_MESSAGE = "";
63 /** Logger delegate. */
64 private EELFLogger mlogger;
66 /** Automatic UUID, overrideable per adapter or per invocation. */
67 private static UUID sInstanceUUID = UUID.randomUUID();
72 public LoggingUtils(final EELFLogger loggerP) {
73 this.mlogger = checkNotNull(loggerP);
77 * Set request related logging variables in thread local data via MDC.
79 * @param service Service Name of API (ex. "PUT template")
80 * @param partner Partner name (client or user invoking API)
82 public static void setRequestContext(String service, String partner) {
83 MDC.put("RequestId", UUID.randomUUID().toString());
84 MDC.put("ServiceName", service);
85 MDC.put("PartnerName", partner);
86 //Defaulting to HTTP/1.1 protocol
87 MDC.put("Protocol", "HTTP/1.1");
89 MDC.put("ServerFQDN", InetAddress.getLocalHost().getCanonicalHostName());
90 MDC.put("ServerIPAddress", InetAddress.getLocalHost().getHostAddress());
91 } catch (UnknownHostException e) {
92 logger.error("Failed to initiate setRequestContext", e);
97 * Set time related logging variables in thread local data via MDC.
99 * @param beginTimeStamp Start time
100 * @param endTimeStamp End time
102 public static void setTimeContext(@NotNull Date beginTimeStamp, @NotNull Date endTimeStamp) {
103 MDC.put("EntryTimestamp", generateTimestampStr(beginTimeStamp));
104 MDC.put("EndTimestamp", generateTimestampStr(endTimeStamp));
105 MDC.put("ElapsedTime", String.valueOf(endTimeStamp.getTime() - beginTimeStamp.getTime()));
109 * Set response related logging variables in thread local data via MDC.
111 * @param code Response code ("0" indicates success)
112 * @param description Response description
113 * @param className class name of invoking class
115 public static void setResponseContext(String code, String description, String className) {
116 MDC.put("ResponseCode", code);
117 MDC.put("StatusCode", code.equals("0") ? "COMPLETE" : "ERROR");
118 MDC.put("ResponseDescription", description != null ? description : "");
119 MDC.put("ClassName", className != null ? className : "");
123 * Set target related logging variables in thread local data via MDC.
125 * @param targetEntity Target entity (an external/sub component, for ex. "sdc")
126 * @param targetServiceName Target service name (name of API invoked on target)
128 public static void setTargetContext(String targetEntity, String targetServiceName) {
129 MDC.put("TargetEntity", targetEntity != null ? targetEntity : "");
130 MDC.put("TargetServiceName", targetServiceName != null ? targetServiceName : "");
134 * Set error related logging variables in thread local data via MDC.
136 * @param code Error code
137 * @param description Error description
139 public static void setErrorContext(String code, String description) {
140 MDC.put("ErrorCode", code);
141 MDC.put("ErrorDescription", description != null ? description : "");
144 private static String generateTimestampStr(Date timeStamp) {
145 return DATE_FORMAT.format(timeStamp);
149 * Get a previously stored RequestID for the thread local data via MDC. If
150 * one was not previously stored, generate one, store it, and return that
153 * @return A string with the request ID
155 public static String getRequestId() {
156 String requestId = MDC.get(ONAPLogConstants.MDCs.REQUEST_ID);
157 if (requestId == null || requestId.isEmpty()) {
158 requestId = UUID.randomUUID().toString();
159 MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, requestId);
164 private static DateFormat createDateFormat() {
165 DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
166 dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
172 /*********************************************************************************************
173 * Method for ONAP Application Logging Specification v1.2
174 ********************************************************************************************/
177 * Report <tt>ENTERING</tt> marker.
179 * @param request non-null incoming request (wrapper)
180 * @param serviceName service name
182 public void entering(HttpServletRequest request, String serviceName) {
184 checkNotNull(request);
185 // Extract MDC values from standard HTTP headers.
186 final String requestId = defaultToUUID(request.getHeader(ONAPLogConstants.Headers.REQUEST_ID));
187 final String invocationId = defaultToUUID(request.getHeader(ONAPLogConstants.Headers.INVOCATION_ID));
188 final String partnerName = defaultToEmpty(request.getHeader(ONAPLogConstants.Headers.PARTNER_NAME));
190 // Default the partner name to the user name used to login to clamp
191 if (partnerName.equalsIgnoreCase(EMPTY_MESSAGE)) {
192 MDC.put(ONAPLogConstants.MDCs.PARTNER_NAME, new DefaultUserNameHandler()
193 .retrieveUserName(SecurityContextHolder.getContext()));
196 // Set standard MDCs. Override this entire method if you want to set
197 // others, OR set them BEFORE or AFTER the invocation of #entering,
198 // depending on where you need them to appear, OR extend the
199 // ServiceDescriptor to add them.
200 MDC.put(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP,
201 ZonedDateTime.now(ZoneOffset.UTC)
202 .format(DateTimeFormatter.ISO_INSTANT));
203 MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, requestId);
204 MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, invocationId);
205 MDC.put(ONAPLogConstants.MDCs.CLIENT_IP_ADDRESS, defaultToEmpty(request.getRemoteAddr()));
206 MDC.put(ONAPLogConstants.MDCs.SERVER_FQDN, defaultToEmpty(request.getServerName()));
207 MDC.put(ONAPLogConstants.MDCs.INSTANCE_UUID, defaultToEmpty(sInstanceUUID));
209 // Default the service name to the requestURI, in the event that
210 // no value has been provided.
211 if (serviceName == null
212 || serviceName.equalsIgnoreCase(EMPTY_MESSAGE)) {
213 MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, request.getRequestURI());
215 MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, serviceName);
218 this.mlogger.info(ONAPLogConstants.Markers.ENTRY);
222 * Report <tt>EXITING</tt> marker.
225 * @param code response code
226 * @param descrption response description
227 * @param severity response severity
228 * @param status response status code
230 public void exiting(String code, String descrption, Level severity, ONAPLogConstants.ResponseStatus status) {
232 MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE, defaultToEmpty(code));
233 MDC.put(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION, defaultToEmpty(descrption));
234 MDC.put(ONAPLogConstants.MDCs.RESPONSE_SEVERITY, defaultToEmpty(severity));
235 MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, defaultToEmpty(status));
237 ZonedDateTime startTime = ZonedDateTime.parse(MDC.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP),
238 DateTimeFormatter.ISO_INSTANT.withZone(ZoneOffset.UTC));
239 ZonedDateTime endTime = ZonedDateTime.now(ZoneOffset.UTC);
240 MDC.put(ONAPLogConstants.MDCs.END_TIMESTAMP, endTime.format(DateTimeFormatter.ISO_INSTANT));
241 long duration = ChronoUnit.MILLIS.between(startTime, endTime);
242 MDC.put(ONAPLogConstants.MDCs.ELAPSED_TIMESTAMP, String.valueOf(duration));
243 this.mlogger.info(ONAPLogConstants.Markers.EXIT);
251 * Get the property value.
253 * @param name The name of the property
254 * @return The value of the property
256 public String getProperties(String name) {
257 return MDC.get(name);
261 * Report pending invocation with <tt>INVOKE</tt> marker,
262 * setting standard ONAP logging headers automatically.
264 * @param con The HTTP url connection
265 * @param targetEntity The target entity
266 * @param targetServiceName The target service name
267 * @return The HTTP url connection
269 public HttpURLConnection invoke(final HttpURLConnection con, String targetEntity, String targetServiceName) {
270 final String invocationId = UUID.randomUUID().toString();
272 // Set standard HTTP headers on (southbound request) builder.
273 con.setRequestProperty(ONAPLogConstants.Headers.REQUEST_ID,
274 defaultToEmpty(MDC.get(ONAPLogConstants.MDCs.REQUEST_ID)));
275 con.setRequestProperty(ONAPLogConstants.Headers.INVOCATION_ID,
277 con.setRequestProperty(ONAPLogConstants.Headers.PARTNER_NAME,
278 defaultToEmpty(MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME)));
280 invokeContext(targetEntity, targetServiceName, invocationId);
282 // Log INVOKE*, with the invocationID as the message body.
283 // (We didn't really want this kind of behavior in the standard,
284 // but is it worse than new, single-message MDC?)
285 this.mlogger.info(ONAPLogConstants.Markers.INVOKE);
286 this.mlogger.info(ONAPLogConstants.Markers.INVOKE_SYNC + "{" + invocationId + "}");
291 * Report pending invocation with <tt>INVOKE</tt> marker,
292 * setting standard ONAP logging headers automatically.
294 * @param targetEntity The target entity
295 * @param targetServiceName The target service name
297 public void invoke(String targetEntity, String targetServiceName) {
298 final String invocationId = UUID.randomUUID().toString();
300 invokeContext(targetEntity, targetServiceName, invocationId);
302 // Log INVOKE*, with the invocationID as the message body.
303 // (We didn't really want this kind of behavior in the standard,
304 // but is it worse than new, single-message MDC?)
305 this.mlogger.info(ONAPLogConstants.Markers.INVOKE);
306 this.mlogger.info(ONAPLogConstants.Markers.INVOKE_SYNC + "{" + invocationId + "}");
310 * Report pending invocation with <tt>INVOKE</tt> marker,
311 * setting standard ONAP logging headers automatically.
313 * @param con The HTTPS url connection
314 * @param targetEntity The target entity
315 * @param targetServiceName The target service name
316 * @return The HTTPS url connection
318 public HttpsURLConnection invokeHttps(final HttpsURLConnection con, String targetEntity, String targetServiceName) {
319 final String invocationId = UUID.randomUUID().toString();
321 // Set standard HTTP headers on (southbound request) builder.
322 con.setRequestProperty(ONAPLogConstants.Headers.REQUEST_ID,
323 defaultToEmpty(MDC.get(ONAPLogConstants.MDCs.REQUEST_ID)));
324 con.setRequestProperty(ONAPLogConstants.Headers.INVOCATION_ID,
326 con.setRequestProperty(ONAPLogConstants.Headers.PARTNER_NAME,
327 defaultToEmpty(MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME)));
329 invokeContext(targetEntity, targetServiceName, invocationId);
331 // Log INVOKE*, with the invocationID as the message body.
332 // (We didn't really want this kind of behavior in the standard,
333 // but is it worse than new, single-message MDC?)
334 this.mlogger.info(ONAPLogConstants.Markers.INVOKE);
335 this.mlogger.info(ONAPLogConstants.Markers.INVOKE_SYNC + "{" + invocationId + "}");
340 * Report pending invocation with <tt>INVOKE-RETURN</tt> marker.
342 public void invokeReturn() {
343 // Add the Invoke-return marker and clear the needed MDC
344 this.mlogger.info(ONAPLogConstants.Markers.INVOKE_RETURN);
345 invokeReturnContext();
349 * Dependency-free nullcheck.
351 * @param in to be checked
352 * @param <T> argument (and return) type
355 private static <T> T checkNotNull(final T in) {
357 throw new NullPointerException();
363 * Dependency-free string default.
365 * @param in to be filtered
366 * @return input string or null
368 private static String defaultToEmpty(final Object in) {
372 return in.toString();
376 * Dependency-free string default.
378 * @param in to be filtered
379 * @return input string or null
381 private static String defaultToUUID(final String in) {
383 return UUID.randomUUID().toString();
389 * Set target related logging variables in thread local data via MDC.
391 * @param targetEntity Target entity (an external/sub component, for ex. "sdc")
392 * @param targetServiceName Target service name (name of API invoked on target)
393 * @param invocationID The invocation ID
395 private void invokeContext(String targetEntity, String targetServiceName, String invocationID) {
396 MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY, defaultToEmpty(targetEntity));
397 MDC.put(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME, defaultToEmpty(targetServiceName));
398 MDC.put(ONAPLogConstants.MDCs.INVOCATIONID_OUT, invocationID);
399 MDC.put(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP,
400 ZonedDateTime.now(ZoneOffset.UTC)
401 .format(DateTimeFormatter.ISO_INSTANT));
405 * Clear target related logging variables in thread local data via MDC.
407 private void invokeReturnContext() {
408 MDC.remove(ONAPLogConstants.MDCs.TARGET_ENTITY);
409 MDC.remove(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME);
410 MDC.remove(ONAPLogConstants.MDCs.INVOCATIONID_OUT);
411 MDC.remove(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP);