2 * ============LICENSE_START=======================================================
\r
4 * ================================================================================
\r
5 * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights
\r
7 * ================================================================================
\r
8 * Licensed under the Apache License, Version 2.0 (the "License");
\r
9 * you may not use this file except in compliance with the License.
\r
10 * You may obtain a copy of the License at
\r
12 * http://www.apache.org/licenses/LICENSE-2.0
\r
14 * Unless required by applicable law or agreed to in writing, software
\r
15 * distributed under the License is distributed on an "AS IS" BASIS,
\r
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
\r
17 * See the License for the specific language governing permissions and
\r
18 * limitations under the License.
\r
19 * ============LICENSE_END============================================
\r
20 * ===================================================================
\r
24 package org.onap.clamp.clds.util;
\r
26 import com.att.eelf.configuration.EELFLogger;
\r
27 import com.att.eelf.configuration.EELFManager;
\r
29 import java.net.HttpURLConnection;
\r
30 import java.net.InetAddress;
\r
31 import java.net.UnknownHostException;
\r
32 import java.text.DateFormat;
\r
33 import java.text.SimpleDateFormat;
\r
34 import java.time.ZoneOffset;
\r
35 import java.time.ZonedDateTime;
\r
36 import java.time.format.DateTimeFormatter;
\r
37 import java.util.Date;
\r
38 import java.util.TimeZone;
\r
39 import java.util.UUID;
\r
41 import javax.servlet.http.HttpServletRequest;
\r
42 import javax.validation.constraints.NotNull;
\r
44 import org.onap.clamp.clds.service.DefaultUserNameHandler;
\r
45 import org.slf4j.MDC;
\r
46 import org.slf4j.event.Level;
\r
47 import org.springframework.security.core.context.SecurityContextHolder;
\r
50 * This class handles the special info that appear in the log, like RequestID,
\r
53 public class LoggingUtils {
\r
54 protected static final EELFLogger logger = EELFManager.getInstance().getLogger(LoggingUtils.class);
\r
56 private static final DateFormat DATE_FORMAT = createDateFormat();
\r
58 /** String constant for messages <tt>ENTERING</tt>, <tt>EXITING</tt>, etc. */
\r
59 private static final String EMPTY_MESSAGE = "";
\r
61 /** Logger delegate. */
\r
62 private EELFLogger mLogger;
\r
63 /** Automatic UUID, overrideable per adapter or per invocation. */
\r
64 private static UUID sInstanceUUID = UUID.randomUUID();
\r
68 public LoggingUtils(final EELFLogger loggerP) {
\r
69 this.mLogger = checkNotNull(loggerP);
\r
73 * Set request related logging variables in thread local data via MDC
\r
75 * @param service Service Name of API (ex. "PUT template")
\r
76 * @param partner Partner name (client or user invoking API)
\r
78 public static void setRequestContext(String service, String partner) {
\r
79 MDC.put("RequestId", UUID.randomUUID().toString());
\r
80 MDC.put("ServiceName", service);
\r
81 MDC.put("PartnerName", partner);
\r
82 //Defaulting to HTTP/1.1 protocol
\r
83 MDC.put("Protocol", "HTTP/1.1");
\r
85 MDC.put("ServerFQDN", InetAddress.getLocalHost().getCanonicalHostName());
\r
86 MDC.put("ServerIPAddress", InetAddress.getLocalHost().getHostAddress());
\r
87 } catch (UnknownHostException e) {
\r
88 logger.error("Failed to initiate setRequestContext", e);
\r
93 * Set time related logging variables in thread local data via MDC.
\r
95 * @param beginTimeStamp Start time
\r
96 * @param endTimeStamp End time
\r
98 public static void setTimeContext(@NotNull Date beginTimeStamp, @NotNull Date endTimeStamp) {
\r
99 MDC.put("BeginTimestamp", generateTimestampStr(beginTimeStamp));
\r
100 MDC.put("EndTimestamp", generateTimestampStr(endTimeStamp));
\r
101 MDC.put("ElapsedTime", String.valueOf(endTimeStamp.getTime() - beginTimeStamp.getTime()));
\r
105 * Set response related logging variables in thread local data via MDC.
\r
107 * @param code Response code ("0" indicates success)
\r
108 * @param description Response description
\r
109 * @param className class name of invoking class
\r
111 public static void setResponseContext(String code, String description, String className) {
\r
112 MDC.put("ResponseCode", code);
\r
113 MDC.put("StatusCode", code.equals("0") ? "COMPLETE" : "ERROR");
\r
114 MDC.put("ResponseDescription", description != null ? description : "");
\r
115 MDC.put("ClassName", className != null ? className : "");
\r
119 * Set target related logging variables in thread local data via MDC
\r
121 * @param targetEntity Target entity (an external/sub component, for ex. "sdc")
\r
122 * @param targetServiceName Target service name (name of API invoked on target)
\r
124 public static void setTargetContext(String targetEntity, String targetServiceName) {
\r
125 MDC.put("TargetEntity", targetEntity != null ? targetEntity : "");
\r
126 MDC.put("TargetServiceName", targetServiceName != null ? targetServiceName : "");
\r
130 * Set error related logging variables in thread local data via MDC.
\r
132 * @param code Error code
\r
133 * @param description Error description
\r
135 public static void setErrorContext(String code, String description) {
\r
136 MDC.put("ErrorCode", code);
\r
137 MDC.put("ErrorDescription", description != null ? description : "");
\r
140 private static String generateTimestampStr(Date timeStamp) {
\r
141 return DATE_FORMAT.format(timeStamp);
\r
145 * Get a previously stored RequestID for the thread local data via MDC. If
\r
146 * one was not previously stored, generate one, store it, and return that
\r
149 * @return A string with the request ID
\r
151 public static String getRequestId() {
\r
152 String requestId = MDC.get(ONAPLogConstants.MDCs.REQUEST_ID);
\r
153 if (requestId == null || requestId.isEmpty()) {
\r
154 requestId = UUID.randomUUID().toString();
\r
155 MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, requestId);
\r
160 private static DateFormat createDateFormat() {
\r
161 DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
\r
162 dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
\r
168 /*********************************************************************************************
\r
169 * Method for ONAP Application Logging Specification v1.2
\r
170 ********************************************************************************************/
\r
173 * Report <tt>ENTERING</tt> marker.
\r
175 * @param request non-null incoming request (wrapper).
\r
178 public void entering(HttpServletRequest request, String serviceName) {
\r
180 checkNotNull(request);
\r
181 // Extract MDC values from standard HTTP headers.
\r
182 final String requestID = defaultToUUID(request.getHeader(ONAPLogConstants.Headers.REQUEST_ID));
\r
183 final String invocationID = defaultToUUID(request.getHeader(ONAPLogConstants.Headers.INVOCATION_ID));
\r
184 final String partnerName = defaultToEmpty(request.getHeader(ONAPLogConstants.Headers.PARTNER_NAME));
\r
186 // Default the partner name to the user name used to login to clamp
\r
187 if (partnerName.equalsIgnoreCase(EMPTY_MESSAGE)) {
\r
188 MDC.put(ONAPLogConstants.MDCs.PARTNER_NAME, new DefaultUserNameHandler().retrieveUserName(SecurityContextHolder.getContext()));
\r
191 // Set standard MDCs. Override this entire method if you want to set
\r
192 // others, OR set them BEFORE or AFTER the invocation of #entering,
\r
193 // depending on where you need them to appear, OR extend the
\r
194 // ServiceDescriptor to add them.
\r
195 MDC.put(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP,
\r
196 ZonedDateTime.now(ZoneOffset.UTC)
\r
197 .format(DateTimeFormatter.ISO_INSTANT));
\r
198 MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, requestID);
\r
199 MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, invocationID);
\r
200 MDC.put(ONAPLogConstants.MDCs.CLIENT_IP_ADDRESS, defaultToEmpty(request.getRemoteAddr()));
\r
201 MDC.put(ONAPLogConstants.MDCs.SERVER_FQDN, defaultToEmpty(request.getServerName()));
\r
202 MDC.put(ONAPLogConstants.MDCs.INSTANCE_UUID, defaultToEmpty(sInstanceUUID));
\r
204 // Default the service name to the requestURI, in the event that
\r
205 // no value has been provided.
\r
206 if (serviceName == null ||
\r
207 serviceName.equalsIgnoreCase(EMPTY_MESSAGE)) {
\r
208 MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, request.getRequestURI());
\r
210 MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, serviceName);
\r
213 this.mLogger.info(ONAPLogConstants.Markers.ENTRY);
\r
217 * Report <tt>EXITING</tt> marker.
\r
221 public void exiting(String code, String descrption, Level severity, ONAPLogConstants.ResponseStatus status) {
\r
223 MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE, defaultToEmpty(code));
\r
224 MDC.put(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION, defaultToEmpty(descrption));
\r
225 MDC.put(ONAPLogConstants.MDCs.RESPONSE_SEVERITY, defaultToEmpty(severity));
\r
226 MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, defaultToEmpty(status));
\r
227 this.mLogger.info(ONAPLogConstants.Markers.EXIT);
\r
235 * Report pending invocation with <tt>INVOKE</tt> marker,
\r
236 * setting standard ONAP logging headers automatically.
\r
238 * @param builder request builder, for setting headers.
\r
239 * @param sync whether synchronous, nullable.
\r
240 * @return invocation ID to be passed with invocation.
\r
242 public HttpURLConnection invoke(final HttpURLConnection con, String targetEntity, String targetServiceName) {
\r
243 final String invocationID = UUID.randomUUID().toString();
\r
245 // Set standard HTTP headers on (southbound request) builder.
\r
246 con.setRequestProperty(ONAPLogConstants.Headers.REQUEST_ID,
\r
247 defaultToEmpty(MDC.get(ONAPLogConstants.MDCs.REQUEST_ID)));
\r
248 con.setRequestProperty(ONAPLogConstants.Headers.INVOCATION_ID,
\r
250 con.setRequestProperty(ONAPLogConstants.Headers.PARTNER_NAME,
\r
251 defaultToEmpty(MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME)));
\r
253 invokeContext(targetEntity, targetServiceName, invocationID);
\r
255 // Log INVOKE*, with the invocationID as the message body.
\r
256 // (We didn't really want this kind of behavior in the standard,
\r
257 // but is it worse than new, single-message MDC?)
\r
258 this.mLogger.info(ONAPLogConstants.Markers.INVOKE);
\r
259 this.mLogger.info(ONAPLogConstants.Markers.INVOKE_SYNC + "{"+ invocationID +"}");
\r
262 public void invokeReturn() {
\r
263 // Add the Invoke-return marker and clear the needed MDC
\r
264 this.mLogger.info(ONAPLogConstants.Markers.INVOKE_RETURN);
\r
265 invokeReturnContext();
\r
269 * Dependency-free nullcheck.
\r
271 * @param in to be checked.
\r
272 * @param <T> argument (and return) type.
\r
273 * @return input arg.
\r
275 private static <T> T checkNotNull(final T in) {
\r
277 throw new NullPointerException();
\r
283 * Dependency-free string default.
\r
285 * @param in to be filtered.
\r
286 * @return input string or null.
\r
288 private static String defaultToEmpty(final Object in) {
\r
292 return in.toString();
\r
296 * Dependency-free string default.
\r
298 * @param in to be filtered.
\r
299 * @return input string or null.
\r
301 private static String defaultToUUID(final String in) {
\r
303 return UUID.randomUUID().toString();
\r
309 * Set target related logging variables in thread local data via MDC
\r
311 * @param targetEntity Target entity (an external/sub component, for ex. "sdc")
\r
312 * @param targetServiceName Target service name (name of API invoked on target)
\r
313 * @param invocationId The invocation ID
\r
315 private void invokeContext (String targetEntity, String targetServiceName, String invocationID) {
\r
316 MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY, defaultToEmpty(targetEntity));
\r
317 MDC.put(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME, defaultToEmpty(targetServiceName));
\r
318 MDC.put(ONAPLogConstants.MDCs.INVOCATIONID_OUT, invocationID);
\r
319 MDC.put(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP,
\r
320 ZonedDateTime.now(ZoneOffset.UTC)
\r
321 .format(DateTimeFormatter.ISO_INSTANT));
\r
325 * Clear target related logging variables in thread local data via MDC
\r
328 private void invokeReturnContext () {
\r
329 MDC.remove(ONAPLogConstants.MDCs.TARGET_ENTITY);
\r
330 MDC.remove(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME);
\r
331 MDC.remove(ONAPLogConstants.MDCs.INVOCATIONID_OUT);
\r