2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
20 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22 package org.onap.aai.logging;
24 import java.net.InetAddress;
25 import java.net.UnknownHostException;
26 import java.util.HashMap;
27 import java.util.Iterator;
29 import java.util.UUID;
30 import java.util.concurrent.TimeUnit;
32 import org.json.JSONArray;
33 import org.json.JSONException;
34 import org.json.JSONObject;
35 import org.onap.aai.exceptions.AAIException;
38 import com.att.eelf.configuration.EELFLogger;
39 import com.att.eelf.configuration.EELFManager;
41 public class LoggingContext {
43 public enum StatusCode {
48 private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(LoggingContext.class);
50 private static final String PREVIOUS_CONTEXTS_KEY = "_PREVIOUS_CONTEXTS";
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"),
65 SERVER_IP_ADDRESS("serverIpAddress"),
66 ELAPSED_TIME("elapsedTime"),
68 CLIENT_IP_ADDRESS("clientIpAddress"),
70 PROCESS_KEY("processKey"),
71 CUSTOM_FIELD_1("customField1"),
72 CUSTOM_FIELD_2("customField2"),
73 CUSTOM_FIELD_3("customField3"),
74 CUSTOM_FIELD_4("customField4"),
76 //ECOMP Specific Metric Log Event Fields
77 TARGET_ENTITY("targetEntity"),
79 //A&AI Specific Log Event Fields
80 COMPONENT("component"),
81 STOP_WATCH_START("stopWatchStart");
83 private final String text;
85 private LoggingField(final String text) {
89 public String toString() {
95 public static void init() {
96 LoggingContext.clear();
97 LoggingContext.startTime();
98 LoggingContext.server();
99 LoggingContext.serverIpAddress();
102 private static void startTime() {
103 MDC.put(LoggingField.START_TIME.toString(), LogFormatTools.getCurrentDateTime());
106 public static UUID requestId() {
107 final String sUuid = MDC.get(LoggingField.REQUEST_ID.toString());
109 if (sUuid == null) return null;
111 return UUID.fromString(sUuid);
114 public static void requestId(UUID requestId) {
115 MDC.put(LoggingField.REQUEST_ID.toString(), requestId.toString());
118 public static void requestId(String requestId) throws AAIException {
120 if(requestId == null){
121 throw new AAIException("AAI_4010");
125 if (requestId.contains(":")) {
126 String[] uuidParts = requestId.split(":");
127 requestId = uuidParts[0];
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);
137 public static void serviceInstanceId(String serviceInstanceId) {
138 MDC.put(LoggingField.SERVICE_INSTANCE_ID.toString(), serviceInstanceId);
141 public static void serverName(String serverName) {
142 MDC.put(LoggingField.SERVER_NAME.toString(), serverName);
145 public static void serviceName(String serviceName) {
146 MDC.put(LoggingField.SERVICE_NAME.toString(), serviceName);
149 public static void partnerName(String partnerName) {
150 MDC.put(LoggingField.PARTNER_NAME.toString(), partnerName);
153 public static void statusCode(LoggingContext.StatusCode statusCode) {
154 MDC.put(LoggingField.STATUS_CODE.toString(), statusCode.toString());
157 public static String responseCode() {
158 return (String) MDC.get(LoggingField.RESPONSE_CODE.toString());
161 public static void responseCode(String responseCode) {
162 MDC.put(LoggingField.RESPONSE_CODE.toString(), responseCode);
165 public static void responseDescription(String responseDescription) {
166 MDC.put(LoggingField.RESPONSE_DESCRIPTION.toString(), responseDescription);
169 public static Object instanceUuid() {
170 return UUID.fromString(MDC.get(LoggingField.INSTANCE_UUID.toString()));
173 public static void instanceUuid(UUID instanceUuid) {
174 MDC.put(LoggingField.INSTANCE_UUID.toString(), instanceUuid.toString());
177 public static void severity(int severity) {
178 MDC.put(LoggingField.SEVERITY.toString(), String.valueOf(severity));
181 private static void serverIpAddress() {
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");
189 public static void elapsedTime(long elapsedTime, TimeUnit timeUnit) {
190 MDC.put(LoggingField.ELAPSED_TIME.toString(), String.valueOf(TimeUnit.MILLISECONDS.convert(elapsedTime, timeUnit)));
193 private static void server() {
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");
201 public static void clientIpAddress(InetAddress clientIpAddress) {
202 MDC.put(LoggingField.CLIENT_IP_ADDRESS.toString(), clientIpAddress.getHostAddress());
205 public static void clientIpAddress(String clientIpAddress) {
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
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);
219 public static void processKey(String processKey) {
220 MDC.put(LoggingField.PROCESS_KEY.toString(), processKey);
223 public static String customField1() {
224 return MDC.get(LoggingField.CUSTOM_FIELD_1.toString());
227 public static void customField1(String customField1) {
228 MDC.put(LoggingField.CUSTOM_FIELD_1.toString(), customField1);
231 public static void customField2(String customField2) {
232 MDC.put(LoggingField.CUSTOM_FIELD_2.toString(), customField2);
235 public static void customField3(String customField3) {
236 MDC.put(LoggingField.CUSTOM_FIELD_3.toString(), customField3);
239 public static void customField4(String customField4) {
240 MDC.put(LoggingField.CUSTOM_FIELD_4.toString(), customField4);
243 public static void component(String component) {
244 MDC.put(LoggingField.COMPONENT.toString(), component);
247 public static void targetEntity(String targetEntity) {
248 MDC.put(LoggingField.TARGET_ENTITY.toString(), targetEntity);
251 public static void stopWatchStart() {
252 MDC.put(LoggingField.STOP_WATCH_START.toString(), String.valueOf(System.nanoTime()));
255 public static double stopWatchStop() {
256 final long stopWatchEnd = System.nanoTime();
257 final String rawStopWatchStart = MDC.get(LoggingField.STOP_WATCH_START.toString());
259 if (rawStopWatchStart == null) throw new StopWatchNotStartedException();
261 final Long stopWatchStart = Long.valueOf(rawStopWatchStart);
263 MDC.remove(LoggingField.STOP_WATCH_START.toString());
265 final double elapsedTimeMillis = (stopWatchEnd - stopWatchStart) / 1000.0 / 1000.0;
267 LoggingContext.elapsedTime((long) elapsedTimeMillis, TimeUnit.MILLISECONDS);
269 return elapsedTimeMillis;
272 public static void put(String key, String value) {
276 public static void clear() {
280 public static void remove(String key) {
284 public static void save() {
285 final JSONObject context = new JSONObject();
287 for (LoggingField field : LoggingField.values()) {
288 if (field == LoggingField.ELAPSED_TIME) continue;
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)
299 final String rawJsonArray = MDC.get(PREVIOUS_CONTEXTS_KEY);
301 if (rawJsonArray == null) {
302 final JSONArray stack = new JSONArray()
305 MDC.put(PREVIOUS_CONTEXTS_KEY, stack.toString());
308 final JSONArray stack = new JSONArray(rawJsonArray)
311 MDC.put(PREVIOUS_CONTEXTS_KEY, stack.toString());
312 } catch (JSONException e) {
318 public static void restore() {
320 final String rawPreviousContexts = MDC.get(PREVIOUS_CONTEXTS_KEY);
322 if (rawPreviousContexts == null) {
323 throw new LoggingContextNotExistsException();
327 final JSONArray previousContexts = new JSONArray(rawPreviousContexts);
328 final JSONObject previousContext = previousContexts.getJSONObject(previousContexts.length() - 1);
330 @SuppressWarnings("unchecked")
331 final Iterator<String> keys = previousContext.keys();
333 while (keys.hasNext()) {
334 final String key = keys.next();
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)
344 MDC.put(PREVIOUS_CONTEXTS_KEY, removeLast(previousContexts).toString());
345 } catch (JSONException e) {
346 //Ignore, the previousContext is serialized from a JSONObject
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.
356 private static JSONArray removeLast(JSONArray previousContexts) {
357 final JSONArray result = new JSONArray();
359 for (int i = 0; i < previousContexts.length() - 1; i++) {
361 result.put(previousContexts.getJSONObject(i));
362 } catch (JSONException e) {
363 //Ignore - not possible
370 public static Map<String, String> getCopy() {
371 final Map<String, String> copy = new HashMap<String, String> ();
373 for (LoggingField field : LoggingField.values()) {
374 final String value = MDC.get(field.toString());
376 if (value != null) copy.put(field.toString(), value);