a471b411b66cd592b1615a55188afc970630f8cd
[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 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;
45 import org.slf4j.MDC;
46 import org.slf4j.event.Level;
47 import org.springframework.security.core.context.SecurityContextHolder;
48
49 /**
50  * This class handles the special info that appear in the log, like RequestID,
51  * time context, ...
52  */
53 public class LoggingUtils {
54     protected static final EELFLogger logger = EELFManager.getInstance().getLogger(LoggingUtils.class);
55
56     private static final DateFormat DATE_FORMAT = createDateFormat();
57
58     /** String constant for messages <tt>ENTERING</tt>, <tt>EXITING</tt>, etc. */
59     private static final String EMPTY_MESSAGE = "";
60
61     /** Logger delegate. */
62     private EELFLogger mlogger;
63
64     /** Automatic UUID, overrideable per adapter or per invocation. */
65     private static UUID sInstanceUUID = UUID.randomUUID();
66
67     /**
68      * Constructor.
69      */
70     public LoggingUtils(final EELFLogger loggerP) {
71         this.mlogger = checkNotNull(loggerP);
72     }
73
74     /**
75      * Set request related logging variables in thread local data via MDC.
76      *
77      * @param service Service Name of API (ex. "PUT template")
78      * @param partner Partner name (client or user invoking API)
79      */
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");
86         try {
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);
91         }
92     }
93
94     /**
95      * Set time related logging variables in thread local data via MDC.
96      *
97      * @param beginTimeStamp Start time
98      * @param endTimeStamp End time
99      */
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()));
104     }
105
106     /**
107      * Set response related logging variables in thread local data via MDC.
108      *
109      * @param code Response code ("0" indicates success)
110      * @param description Response description
111      * @param className class name of invoking class
112      */
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 : "");
118     }
119
120     /**
121      * Set target related logging variables in thread local data via MDC.
122      *
123      * @param targetEntity Target entity (an external/sub component, for ex. "sdc")
124      * @param targetServiceName Target service name (name of API invoked on target)
125      */
126     public static void setTargetContext(String targetEntity, String targetServiceName) {
127         MDC.put("TargetEntity", targetEntity != null ? targetEntity : "");
128         MDC.put("TargetServiceName", targetServiceName != null ? targetServiceName : "");
129     }
130
131     /**
132      * Set error related logging variables in thread local data via MDC.
133      *
134      * @param code Error code
135      * @param description Error description
136      */
137     public static void setErrorContext(String code, String description) {
138         MDC.put("ErrorCode", code);
139         MDC.put("ErrorDescription", description != null ? description : "");
140     }
141
142     private static String generateTimestampStr(Date timeStamp) {
143         return DATE_FORMAT.format(timeStamp);
144     }
145
146     /**
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
149      * one.
150      *
151      * @return A string with the request ID
152      */
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);
158         }
159         return requestId;
160     }
161
162     private static DateFormat createDateFormat() {
163         DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
164         dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
165         return dateFormat;
166     }
167
168     /*********************************************************************************************
169      * Method for ONAP Application Logging Specification v1.2
170      ********************************************************************************************/
171
172     /**
173      * Report <tt>ENTERING</tt> marker.
174      *
175      * @param request non-null incoming request (wrapper)
176      * @param serviceName service name
177      */
178     public void entering(HttpServletRequest request, String serviceName) {
179         MDC.clear();
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));
185
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()));
190         }
191
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));
204
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());
210         } else {
211             MDC.put(OnapLogConstants.Mdcs.SERVICE_NAME, serviceName);
212         }
213
214         this.mlogger.info(OnapLogConstants.Markers.ENTRY);
215     }
216
217     /**
218      * Report <tt>EXITING</tt> marker.
219      *
220
221      * @param code response code
222      * @param descrption response description
223      * @param severity response severity
224      * @param status response status code
225      */
226     public void exiting(String code, String descrption, Level severity, OnapLogConstants.ResponseStatus status) {
227         try {
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));
232
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);
240         }
241         finally {
242             MDC.clear();
243         }
244     }
245
246     /**
247      * Get the property value.
248      *
249      * @param name The name of the property
250      * @return The value of the property
251      */
252     public String getProperties(String name) {
253         return MDC.get(name);
254     }
255
256     /**
257      * Report pending invocation with <tt>INVOKE</tt> marker,
258      * setting standard ONAP logging headers automatically.
259      *
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
264      */
265     public HttpURLConnection invoke(final HttpURLConnection con, String targetEntity, String targetServiceName) {
266         return this.invokeGeneric(con, targetEntity, targetServiceName);
267     }
268
269     /**
270      * Report pending invocation with <tt>INVOKE</tt> marker,
271      * setting standard ONAP logging headers automatically.
272      *
273      * @param targetEntity The target entity
274      * @param targetServiceName The target service name
275      */
276     public void invoke(String targetEntity, String targetServiceName) {
277         final String invocationId = UUID.randomUUID().toString();
278
279         invokeContext(targetEntity, targetServiceName, invocationId);
280
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 + "}");
286     }
287
288     /**
289      * Report pending invocation with <tt>INVOKE</tt> marker,
290      * setting standard ONAP logging headers automatically.
291      *
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
296      */
297     public HttpsURLConnection invokeHttps(final HttpsURLConnection con, String targetEntity, String targetServiceName) {
298         return this.invokeGeneric(con, targetEntity, targetServiceName);
299     }
300
301     /**
302      * Report pending invocation with <tt>INVOKE-RETURN</tt> marker.
303      */
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();
308     }
309
310     /**
311      * Dependency-free nullcheck.
312      *
313      * @param in to be checked
314      * @param <T> argument (and return) type
315      * @return input arg
316      */
317     private static <T> T checkNotNull(final T in) {
318         if (in == null) {
319             throw new NullPointerException();
320         }
321         return in;
322     }
323
324     /**
325      * Dependency-free string default.
326      *
327      * @param in to be filtered
328      * @return input string or null
329      */
330     private static String defaultToEmpty(final Object in) {
331         if (in == null) {
332             return "";
333         }
334         return in.toString();
335     }
336
337     /**
338      * Dependency-free string default.
339      *
340      * @param in to be filtered
341      * @return input string or null
342      */
343     private static String defaultToUuid(final String in) {
344         if (in == null) {
345             return UUID.randomUUID().toString();
346         }
347         return in;
348     }
349
350     /**
351      * Set target related logging variables in thread local data via MDC.
352      *
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
356      */
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));
364     }
365
366     /**
367      * Clear target related logging variables in thread local data via MDC.
368      */
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);
374     }
375
376     private <T extends URLConnection> T invokeGeneric(final T con, String targetEntity, String targetServiceName) {
377         final String invocationId = UUID.randomUUID().toString();
378
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,
383                 invocationId);
384         con.setRequestProperty(OnapLogConstants.Headers.PARTNER_NAME,
385                 defaultToEmpty(MDC.get(OnapLogConstants.Mdcs.PARTNER_NAME)));
386
387         invokeContext(targetEntity, targetServiceName, invocationId);
388
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 + "}");
394         return con;
395     }
396 }