Fix it if the transaction id is missing
[aai/aai-common.git] / aai-core / src / main / java / org / onap / aai / logging / LoggingContext.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *    http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  *
20  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
21  */
22 package org.onap.aai.logging;
23
24 import java.net.InetAddress;
25 import java.net.UnknownHostException;
26 import java.util.HashMap;
27 import java.util.Iterator;
28 import java.util.Map;
29 import java.util.UUID;
30 import java.util.concurrent.TimeUnit;
31
32 import org.json.JSONArray;
33 import org.json.JSONException;
34 import org.json.JSONObject;
35 import org.onap.aai.exceptions.AAIException;
36 import org.slf4j.MDC;
37
38 import com.att.eelf.configuration.EELFLogger;
39 import com.att.eelf.configuration.EELFManager;
40
41 public class LoggingContext {
42
43         public enum StatusCode {
44                 COMPLETE,
45                 ERROR
46         }
47
48         private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(LoggingContext.class);
49
50         private static final String PREVIOUS_CONTEXTS_KEY = "_PREVIOUS_CONTEXTS";
51
52         //ECOMP Specific Log Event Fields
53         public static enum LoggingField {
54                 START_TIME("startTime"),
55                 REQUEST_ID("requestId"),
56                 SERVICE_INSTANCE_ID("serviceInstanceId"),
57                 SERVER_NAME("serverName"),
58                 SERVICE_NAME("serviceName"),
59                 PARTNER_NAME("partnerName"),
60                 STATUS_CODE("statusCode"),
61                 RESPONSE_CODE("responseCode"),
62                 RESPONSE_DESCRIPTION("responseDescription"),
63                 INSTANCE_UUID("instanceUUID"),
64                 SEVERITY("severity"),
65                 SERVER_IP_ADDRESS("serverIpAddress"),
66                 ELAPSED_TIME("elapsedTime"),
67                 SERVER("server"),
68                 CLIENT_IP_ADDRESS("clientIpAddress"),
69                 UNUSED("unused"),
70                 PROCESS_KEY("processKey"),
71                 CUSTOM_FIELD_1("customField1"),
72                 CUSTOM_FIELD_2("customField2"),
73                 CUSTOM_FIELD_3("customField3"),
74                 CUSTOM_FIELD_4("customField4"),
75                 
76                 //ECOMP Specific Metric Log Event Fields
77                 TARGET_ENTITY("targetEntity"),
78
79                 //A&AI Specific Log Event Fields
80                 COMPONENT("component"),
81                 STOP_WATCH_START("stopWatchStart");
82
83                 private final String text;
84
85                 private LoggingField(final String text) {
86                         this.text = text;
87                 }
88
89                 public String toString() {
90                         return text;
91                 }
92         }
93
94
95         public static void init() {
96                 LoggingContext.clear();
97                 LoggingContext.startTime();
98                 LoggingContext.server();
99                 LoggingContext.serverIpAddress();
100         }
101
102         private static void startTime() {
103                 MDC.put(LoggingField.START_TIME.toString(), LogFormatTools.getCurrentDateTime());
104         }
105
106         public static UUID requestId() {
107                 final String sUuid = MDC.get(LoggingField.REQUEST_ID.toString());
108
109                 if (sUuid == null) return null;
110
111                 return UUID.fromString(sUuid);
112         }
113
114         public static void requestId(UUID requestId) {
115                 MDC.put(LoggingField.REQUEST_ID.toString(), requestId.toString());
116         }
117
118         public static void requestId(String requestId) throws AAIException {
119
120                 if(requestId == null){
121                         throw new AAIException("AAI_4010");
122                 }
123
124                 try {
125                         if (requestId.contains(":")) {
126                                 String[] uuidParts = requestId.split(":");
127                                 requestId = uuidParts[0];
128                         }
129                         MDC.put(LoggingField.REQUEST_ID.toString(), UUID.fromString(requestId).toString());
130                 } catch (IllegalArgumentException e) {
131                         final UUID generatedRequestUuid = UUID.randomUUID();
132                         MDC.put(LoggingField.REQUEST_ID.toString(), generatedRequestUuid.toString());
133                         LOGGER.warn("Unable to use UUID " + requestId + " (Not formatted properly). Using generated UUID=" + generatedRequestUuid);
134                 }
135         }
136
137         public static void serviceInstanceId(String serviceInstanceId) {
138                 MDC.put(LoggingField.SERVICE_INSTANCE_ID.toString(), serviceInstanceId);
139         }
140
141         public static void serverName(String serverName) {
142                 MDC.put(LoggingField.SERVER_NAME.toString(), serverName);
143         }
144
145         public static void serviceName(String serviceName) {
146                 MDC.put(LoggingField.SERVICE_NAME.toString(), serviceName);
147         }
148
149         public static void partnerName(String partnerName) {
150                 MDC.put(LoggingField.PARTNER_NAME.toString(), partnerName);
151         }
152
153         public static void statusCode(LoggingContext.StatusCode statusCode) {
154                 MDC.put(LoggingField.STATUS_CODE.toString(), statusCode.toString());
155         }
156
157         public static String responseCode() {
158                 return (String) MDC.get(LoggingField.RESPONSE_CODE.toString());
159         }
160
161         public static void responseCode(String responseCode) {
162                 MDC.put(LoggingField.RESPONSE_CODE.toString(), responseCode);
163         }
164
165         public static void responseDescription(String responseDescription) {
166                 MDC.put(LoggingField.RESPONSE_DESCRIPTION.toString(), responseDescription);
167         }
168
169         public static Object instanceUuid() {
170                 return UUID.fromString(MDC.get(LoggingField.INSTANCE_UUID.toString()));
171         }
172
173         public static void instanceUuid(UUID instanceUuid) {
174                 MDC.put(LoggingField.INSTANCE_UUID.toString(), instanceUuid.toString());
175         }
176
177         public static void severity(int severity) {
178                 MDC.put(LoggingField.SEVERITY.toString(), String.valueOf(severity));
179         }
180
181         private static void serverIpAddress() {
182                 try {
183                         MDC.put(LoggingField.SERVER_IP_ADDRESS.toString(), InetAddress.getLocalHost().getHostAddress());
184                 } catch (UnknownHostException e) {
185                         LOGGER.warn("Unable to resolve server IP address - will not be displayed in logged events");
186                 }
187         }
188
189         public static void elapsedTime(long elapsedTime, TimeUnit timeUnit) {
190                 MDC.put(LoggingField.ELAPSED_TIME.toString(), String.valueOf(TimeUnit.MILLISECONDS.convert(elapsedTime, timeUnit)));
191         }
192
193         private static void server() {
194                 try {
195                         MDC.put(LoggingField.SERVER.toString(),  InetAddress.getLocalHost().getCanonicalHostName());
196                 } catch (UnknownHostException e) {
197                         LOGGER.warn("Unable to resolve server IP address - hostname will not be displayed in logged events");
198                 }
199         }
200
201         public static void clientIpAddress(InetAddress clientIpAddress) {
202                 MDC.put(LoggingField.CLIENT_IP_ADDRESS.toString(), clientIpAddress.getHostAddress());
203         }
204
205         public static void clientIpAddress(String clientIpAddress) {
206                 try {
207                         MDC.put(LoggingField.CLIENT_IP_ADDRESS.toString(), InetAddress.getByName(clientIpAddress).getHostAddress());
208                 } catch (UnknownHostException e) {
209                         //Ignore, will not be thrown since InetAddress.getByName(String) only
210                         //checks the validity of the passed in string
211                 }
212         }
213
214         public static void unused(String unused) {
215                 LOGGER.warn("Using field '" + LoggingField.UNUSED + "' (seems like this should go unused...)");
216                 MDC.put(LoggingField.UNUSED.toString(), unused);
217         }
218
219         public static void processKey(String processKey) {
220                 MDC.put(LoggingField.PROCESS_KEY.toString(), processKey);
221         }
222
223         public static String customField1() {
224                 return MDC.get(LoggingField.CUSTOM_FIELD_1.toString());
225         }
226
227         public static void customField1(String customField1) {
228                 MDC.put(LoggingField.CUSTOM_FIELD_1.toString(), customField1);
229         }
230
231         public static void customField2(String customField2) {
232                 MDC.put(LoggingField.CUSTOM_FIELD_2.toString(), customField2);
233         }
234
235         public static void customField3(String customField3) {
236                 MDC.put(LoggingField.CUSTOM_FIELD_3.toString(), customField3);
237         }
238
239         public static void customField4(String customField4) {
240                 MDC.put(LoggingField.CUSTOM_FIELD_4.toString(), customField4);
241         }
242
243         public static void component(String component) {
244                 MDC.put(LoggingField.COMPONENT.toString(), component);
245         }
246
247         public static void targetEntity(String targetEntity) {
248                 MDC.put(LoggingField.TARGET_ENTITY.toString(), targetEntity);
249         }
250
251         public static void stopWatchStart() {
252                 MDC.put(LoggingField.STOP_WATCH_START.toString(), String.valueOf(System.nanoTime()));
253         }
254
255         public static double stopWatchStop() {
256                 final long stopWatchEnd = System.nanoTime();
257                 final String rawStopWatchStart = MDC.get(LoggingField.STOP_WATCH_START.toString());
258
259                 if (rawStopWatchStart == null) throw new StopWatchNotStartedException();
260
261                 final Long stopWatchStart = Long.valueOf(rawStopWatchStart);
262
263                 MDC.remove(LoggingField.STOP_WATCH_START.toString());
264
265                 final double elapsedTimeMillis = (stopWatchEnd - stopWatchStart) / 1000.0 / 1000.0;
266
267                 LoggingContext.elapsedTime((long) elapsedTimeMillis, TimeUnit.MILLISECONDS);
268
269                 return elapsedTimeMillis;
270         }
271
272         public static void put(String key, String value) {
273                 MDC.put(key, value);
274         }
275
276         public static void clear() {
277                 MDC.clear();
278         }
279
280         public static void remove(String key) {
281                 MDC.remove(key);
282         }
283
284         public static void save() {
285                 final JSONObject context = new JSONObject();
286
287                 for (LoggingField field : LoggingField.values()) {
288                         if (field == LoggingField.ELAPSED_TIME) continue;
289
290                         try {
291                                 context.put(field.toString(), MDC.get(field.toString()));
292                         } catch (JSONException e) {
293                                 //Ignore - only occurs when the key is null (which can't happen)
294                                 //                      or the value is invalid (everything is converted to a string
295                                 //                      before it get put() to the MDC)
296                         }
297                 }
298
299                 final String rawJsonArray = MDC.get(PREVIOUS_CONTEXTS_KEY);
300
301                 if (rawJsonArray == null) {
302                         final JSONArray stack = new JSONArray()
303                                                                                         .put(context);
304
305                         MDC.put(PREVIOUS_CONTEXTS_KEY, stack.toString());
306                 } else {
307                         try {
308                                 final JSONArray stack = new JSONArray(rawJsonArray)
309                                                                                                 .put(context);
310
311                                 MDC.put(PREVIOUS_CONTEXTS_KEY, stack.toString());
312                         } catch (JSONException e) {
313                                 //Ignore
314                         }
315                 }
316         }
317
318         public static void restore() {
319                 
320                 final String rawPreviousContexts = MDC.get(PREVIOUS_CONTEXTS_KEY);
321         
322                 if (rawPreviousContexts == null) {
323                         throw new LoggingContextNotExistsException();
324                 }
325
326                 try {
327                         final JSONArray previousContexts = new JSONArray(rawPreviousContexts);
328                         final JSONObject previousContext = previousContexts.getJSONObject(previousContexts.length() - 1);
329
330                         @SuppressWarnings("unchecked")
331                         final Iterator<String> keys = previousContext.keys();
332         
333                         while (keys.hasNext()) {
334                                 final String key = keys.next();
335
336                                 try {
337                                         MDC.put(key, previousContext.getString(key));
338                                 } catch (JSONException e) {
339                                         //Ignore, only occurs when the key is null (cannot happen)
340                                         //                      or the value is invalid (they are all strings)
341                                 }
342                         }
343
344                         MDC.put(PREVIOUS_CONTEXTS_KEY, removeLast(previousContexts).toString());
345                 } catch (JSONException e) {
346                         //Ignore, the previousContext is serialized from a JSONObject
347                 }
348         }
349
350         /**
351          * AJSC declares an ancient version of org.json:json in one of the parent POMs of this project.
352          * I tried to update our version of that library in our POM, but it's ignored because of the way
353          * AJSC has organized their <dependencies>.  Had they put it into the <dependencyManagement> section,
354          * this method would not be necessary.
355          */
356         private static JSONArray removeLast(JSONArray previousContexts) {
357                 final JSONArray result = new JSONArray();
358
359                 for (int i = 0; i < previousContexts.length() - 1; i++) {
360                         try {
361                                 result.put(previousContexts.getJSONObject(i));
362                         } catch (JSONException e) {
363                                 //Ignore - not possible
364                         }
365                 }
366
367                 return result;
368         }
369
370         public static Map<String, String> getCopy() {
371                 final Map<String, String> copy = new HashMap<String, String> ();
372
373                 for (LoggingField field : LoggingField.values()) {
374                         final String value = MDC.get(field.toString());
375
376                         if (value != null) copy.put(field.toString(), value);
377                 }
378
379                 return copy;
380         }
381 }