163ab6913679bb7d53875d8e7bbca4f6a773fc93
[clamp.git] / src / main / java / org / onap / clamp / clds / util / LoggingUtils.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP CLAMP
4  * ================================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights
6  *                             reserved.
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
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
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  * ===================================================================
21  *
22  */
23
24 package org.onap.clamp.clds.util;
25
26 import com.att.eelf.configuration.EELFLogger;
27 import com.att.eelf.configuration.EELFManager;
28
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;
42
43 import javax.net.ssl.HttpsURLConnection;
44 import javax.servlet.http.HttpServletRequest;
45 import javax.validation.constraints.NotNull;
46
47 import org.onap.clamp.clds.service.DefaultUserNameHandler;
48 import org.slf4j.MDC;
49 import org.slf4j.event.Level;
50 import org.springframework.security.core.context.SecurityContextHolder;
51
52 /**
53  * This class handles the special info that appear in the log, like RequestID,
54  * time context, ...
55  */
56 public class LoggingUtils {
57     protected static final EELFLogger logger = EELFManager.getInstance().getLogger(LoggingUtils.class);
58
59     private static final DateFormat DATE_FORMAT = createDateFormat();
60
61     /** String constant for messages <tt>ENTERING</tt>, <tt>EXITING</tt>, etc. */
62     private static final String EMPTY_MESSAGE = "";
63
64     /** Logger delegate. */
65     private EELFLogger mlogger;
66
67     /** Automatic UUID, overrideable per adapter or per invocation. */
68     private static UUID sInstanceUUID = UUID.randomUUID();
69
70     /**
71      * Constructor.
72      */
73     public LoggingUtils(final EELFLogger loggerP) {
74         this.mlogger = checkNotNull(loggerP);
75     }
76
77     /**
78      * Set request related logging variables in thread local data via MDC.
79      *
80      * @param service Service Name of API (ex. "PUT template")
81      * @param partner Partner name (client or user invoking API)
82      */
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");
89         try {
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);
94         }
95     }
96
97     /**
98      * Set time related logging variables in thread local data via MDC.
99      *
100      * @param beginTimeStamp Start time
101      * @param endTimeStamp End time
102      */
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()));
107     }
108
109     /**
110      * Set response related logging variables in thread local data via MDC.
111      *
112      * @param code Response code ("0" indicates success)
113      * @param description Response description
114      * @param className class name of invoking class
115      */
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 : "");
121     }
122
123     /**
124      * Set target related logging variables in thread local data via MDC.
125      *
126      * @param targetEntity Target entity (an external/sub component, for ex. "sdc")
127      * @param targetServiceName Target service name (name of API invoked on target)
128      */
129     public static void setTargetContext(String targetEntity, String targetServiceName) {
130         MDC.put("TargetEntity", targetEntity != null ? targetEntity : "");
131         MDC.put("TargetServiceName", targetServiceName != null ? targetServiceName : "");
132     }
133
134     /**
135      * Set error related logging variables in thread local data via MDC.
136      *
137      * @param code Error code
138      * @param description Error description
139      */
140     public static void setErrorContext(String code, String description) {
141         MDC.put("ErrorCode", code);
142         MDC.put("ErrorDescription", description != null ? description : "");
143     }
144
145     private static String generateTimestampStr(Date timeStamp) {
146         return DATE_FORMAT.format(timeStamp);
147     }
148
149     /**
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
152      * one.
153      *
154      * @return A string with the request ID
155      */
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);
161         }
162         return requestId;
163     }
164
165     private static DateFormat createDateFormat() {
166         DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
167         dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
168         return dateFormat;
169     }
170
171     /*********************************************************************************************
172      * Method for ONAP Application Logging Specification v1.2
173      ********************************************************************************************/
174
175     /**
176      * Report <tt>ENTERING</tt> marker.
177      *
178      * @param request non-null incoming request (wrapper)
179      * @param serviceName service name
180      */
181     public void entering(HttpServletRequest request, String serviceName) {
182         MDC.clear();
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));
188
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()));
193         }
194
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));
207
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());
213         } else {
214             MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, serviceName);
215         }
216
217         this.mlogger.info(ONAPLogConstants.Markers.ENTRY);
218     }
219
220     /**
221      * Report <tt>EXITING</tt> marker.
222      *
223
224      * @param code response code
225      * @param descrption response description
226      * @param severity response severity
227      * @param status response status code
228      */
229     public void exiting(String code, String descrption, Level severity, ONAPLogConstants.ResponseStatus status) {
230         try {
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));
235
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);
243         }
244         finally {
245             MDC.clear();
246         }
247     }
248
249     /**
250      * Get the property value.
251      *
252      * @param name The name of the property
253      * @return The value of the property
254      */
255     public String getProperties(String name) {
256         return MDC.get(name);
257     }
258
259     /**
260      * Report pending invocation with <tt>INVOKE</tt> marker,
261      * setting standard ONAP logging headers automatically.
262      *
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
267      */
268     public HttpURLConnection invoke(final HttpURLConnection con, String targetEntity, String targetServiceName) {
269         return this.invokeGeneric(con, targetEntity, targetServiceName);
270     }
271
272     /**
273      * Report pending invocation with <tt>INVOKE</tt> marker,
274      * setting standard ONAP logging headers automatically.
275      *
276      * @param targetEntity The target entity
277      * @param targetServiceName The target service name
278      */
279     public void invoke(String targetEntity, String targetServiceName) {
280         final String invocationId = UUID.randomUUID().toString();
281
282         invokeContext(targetEntity, targetServiceName, invocationId);
283
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 + "}");
289     }
290
291     /**
292      * Report pending invocation with <tt>INVOKE</tt> marker,
293      * setting standard ONAP logging headers automatically.
294      *
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
299      */
300     public HttpsURLConnection invokeHttps(final HttpsURLConnection con, String targetEntity, String targetServiceName) {
301         return this.invokeGeneric(con, targetEntity, targetServiceName);
302     }
303
304     /**
305      * Report pending invocation with <tt>INVOKE-RETURN</tt> marker.
306      */
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();
311     }
312
313     /**
314      * Dependency-free nullcheck.
315      *
316      * @param in to be checked
317      * @param <T> argument (and return) type
318      * @return input arg
319      */
320     private static <T> T checkNotNull(final T in) {
321         if (in == null) {
322             throw new NullPointerException();
323         }
324         return in;
325     }
326
327     /**
328      * Dependency-free string default.
329      *
330      * @param in to be filtered
331      * @return input string or null
332      */
333     private static String defaultToEmpty(final Object in) {
334         if (in == null) {
335             return "";
336         }
337         return in.toString();
338     }
339
340     /**
341      * Dependency-free string default.
342      *
343      * @param in to be filtered
344      * @return input string or null
345      */
346     private static String defaultToUUID(final String in) {
347         if (in == null) {
348             return UUID.randomUUID().toString();
349         }
350         return in;
351     }
352
353     /**
354      * Set target related logging variables in thread local data via MDC.
355      *
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
359      */
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));
367     }
368
369     /**
370      * Clear target related logging variables in thread local data via MDC.
371      */
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);
377     }
378
379     private <T extends URLConnection> T invokeGeneric(final T con, String targetEntity, String targetServiceName) {
380         final String invocationId = UUID.randomUUID().toString();
381
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,
386                 invocationId);
387         con.setRequestProperty(ONAPLogConstants.Headers.PARTNER_NAME,
388                 defaultToEmpty(MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME)));
389
390         invokeContext(targetEntity, targetServiceName, invocationId);
391
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 + "}");
397         return con;
398     }
399 }