71835fa1067cc41ac0e9b98136590bd1d60a7266
[clamp.git] / src / main / java / org / onap / clamp / clds / util / LoggingUtils.java
1 /*-\r
2  * ============LICENSE_START=======================================================\r
3  * ONAP CLAMP\r
4  * ================================================================================\r
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights\r
6  *                             reserved.\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
11  *\r
12  * http://www.apache.org/licenses/LICENSE-2.0\r
13  *\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
21  * \r
22  */\r
23 \r
24 package org.onap.clamp.clds.util;\r
25 \r
26 import java.net.InetAddress;\r
27 import java.net.UnknownHostException;\r
28 import java.text.DateFormat;\r
29 import java.text.SimpleDateFormat;\r
30 import java.util.Date;\r
31 import java.util.TimeZone;\r
32 import java.util.UUID;\r
33 import javax.validation.constraints.NotNull;\r
34 import org.slf4j.MDC;\r
35 \r
36 import com.att.eelf.configuration.EELFLogger;\r
37 import com.att.eelf.configuration.EELFManager;\r
38 \r
39 /**\r
40  * This class handles the special info that appear in the log, like RequestID,\r
41  * time context, ...\r
42  */\r
43 public final class LoggingUtils {\r
44         \r
45         protected static final EELFLogger logger = EELFManager.getInstance().getLogger(LoggingUtils.class);\r
46 \r
47     private static final DateFormat DATE_FORMAT = createDateFormat();\r
48 \r
49     /**\r
50      * Private constructor to avoid creating instances of util class.\r
51      */\r
52     private LoggingUtils() {\r
53     }\r
54 \r
55     /**\r
56      * Set request related logging variables in thread local data via MDC\r
57      *\r
58      * @param service Service Name of API (ex. "PUT template")\r
59      * @param partner Partner name (client or user invoking API)\r
60      */\r
61     public static void setRequestContext(String service, String partner) {\r
62         MDC.put("RequestId", UUID.randomUUID().toString());\r
63         MDC.put("ServiceName", service);\r
64         MDC.put("PartnerName", partner);\r
65         //Defaulting to HTTP/1.1 protocol\r
66         MDC.put("Protocol", "HTTP/1.1");\r
67         try {\r
68                 MDC.put("ServerFQDN", InetAddress.getLocalHost().getCanonicalHostName());\r
69                 MDC.put("ServerIPAddress", InetAddress.getLocalHost().getHostAddress());\r
70         } catch (UnknownHostException e) {\r
71                 logger.error("Failed to initiate setRequestContext", e);\r
72                 }\r
73     }\r
74 \r
75     /**\r
76      * Set time related logging variables in thread local data via MDC.\r
77      *\r
78      * @param beginTimeStamp Start time\r
79      * @param endTimeStamp End time\r
80      */\r
81     public static void setTimeContext(@NotNull Date beginTimeStamp, @NotNull Date endTimeStamp) {\r
82         MDC.put("BeginTimestamp", generateTimestampStr(beginTimeStamp));\r
83         MDC.put("EndTimestamp", generateTimestampStr(endTimeStamp));\r
84         MDC.put("ElapsedTime", String.valueOf(endTimeStamp.getTime() - beginTimeStamp.getTime()));\r
85     }\r
86 \r
87     /**\r
88      * Set response related logging variables in thread local data via MDC.\r
89      *\r
90      * @param code Response code ("0" indicates success)\r
91      * @param description Response description\r
92      * @param className class name of invoking class\r
93      */\r
94     public static void setResponseContext(String code, String description, String className) {\r
95         MDC.put("ResponseCode", code);\r
96         MDC.put("StatusCode", code.equals("0") ? "COMPLETE" : "ERROR");\r
97         MDC.put("ResponseDescription", description != null ? description : "");\r
98         MDC.put("ClassName", className != null ? className : "");\r
99     }\r
100 \r
101     /**\r
102      * Set target related logging variables in thread local data via MDC\r
103      *\r
104      * @param targetEntity Target entity (an external/sub component, for ex. "sdc")\r
105      * @param targetServiceName Target service name (name of API invoked on target)\r
106      */\r
107     public static void setTargetContext(String targetEntity, String targetServiceName) {\r
108         MDC.put("TargetEntity", targetEntity != null ? targetEntity : "");\r
109         MDC.put("TargetServiceName", targetServiceName != null ? targetServiceName : "");\r
110     }\r
111 \r
112     /**\r
113      * Set error related logging variables in thread local data via MDC.\r
114      *\r
115      * @param code Error code\r
116      * @param description Error description\r
117      */\r
118     public static void setErrorContext(String code, String description) {\r
119         MDC.put("ErrorCode", code);\r
120         MDC.put("ErrorDescription", description != null ? description : "");\r
121     }\r
122 \r
123     private static String generateTimestampStr(Date timeStamp) {\r
124         return DATE_FORMAT.format(timeStamp);\r
125     }\r
126 \r
127     /**\r
128      * Get a previously stored RequestID for the thread local data via MDC. If\r
129      * one was not previously stored, generate one, store it, and return that\r
130      * one.\r
131      *\r
132      * @return A string with the request ID\r
133      */\r
134     public static String getRequestId() {\r
135         String requestId;\r
136 \r
137         requestId = (String) MDC.get("RequestID");\r
138         if (requestId == null || requestId.isEmpty()) {\r
139             requestId = UUID.randomUUID().toString();\r
140             MDC.put("RequestId", requestId);\r
141         }\r
142         return requestId;\r
143     }\r
144 \r
145     private static DateFormat createDateFormat() {\r
146         DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");\r
147         dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));\r
148         return dateFormat;\r
149     }\r
150 \r
151 }\r