changes done to get stack trace of exception
[portal.git] / ecomp-portal-BE-common / src / main / java / org / onap / portalapp / portal / logging / logic / EPLogUtil.java
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  *
8  * Unless otherwise specified, all software contained herein is licensed
9  * under the Apache License, Version 2.0 (the "License");
10  * you may not use this software except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *             http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  *
21  * Unless otherwise specified, all documentation contained herein is licensed
22  * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
23  * you may not use this documentation except in compliance with the License.
24  * You may obtain a copy of the License at
25  *
26  *             https://creativecommons.org/licenses/by/4.0/
27  *
28  * Unless required by applicable law or agreed to in writing, documentation
29  * distributed under the License is distributed on an "AS IS" BASIS,
30  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31  * See the License for the specific language governing permissions and
32  * limitations under the License.
33  *
34  * ============LICENSE_END============================================
35  *
36  * 
37  */
38 package org.onap.portalapp.portal.logging.logic;
39
40 import static com.att.eelf.configuration.Configuration.MDC_ALERT_SEVERITY;
41 import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME;
42
43 import java.net.InetAddress;
44 import java.text.MessageFormat;
45
46 import org.onap.portalapp.portal.domain.EcompAuditLog;
47 import org.onap.portalapp.portal.logging.aop.EPEELFLoggerAdvice;
48 import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
49 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
50 import org.onap.portalapp.portal.utils.EcompPortalUtils;
51 import org.onap.portalsdk.core.logging.format.AlarmSeverityEnum;
52 import org.onap.portalsdk.core.logging.format.ErrorSeverityEnum;
53 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
54 import org.onap.portalsdk.core.util.SystemProperties;
55 import org.slf4j.MDC;
56 import org.springframework.http.HttpStatus;
57
58 import com.att.eelf.configuration.Configuration;
59 import com.att.eelf.configuration.EELFLogger;
60 import com.att.eelf.configuration.EELFManager;
61 import com.att.eelf.configuration.EELFLogger.Level;
62
63
64 public class EPLogUtil {
65
66         // This class has no logger of its own; it uses loggers passed to it.
67         private static EELFLogger errorLogger = EELFManager.getInstance().getErrorLogger();
68
69         /**
70          * Formats and writes a message to the error log with the class name and the
71          * specified parameters, using log level info, warn or error appropriate for
72          * the specified severity
73          * 
74          * @param classLogger
75          *            Logger for the class where the error occurred; the logger
76          *            carries the class name.
77          * @param epMessageEnum
78          *            Enum carrying alarm and error severity
79          * @param param
80          *            Values used to build the message.
81          */
82         public static void logEcompError(EELFLoggerDelegate classLogger, EPAppMessagesEnum epMessageEnum, String... param) {
83                 logEcompError(classLogger, epMessageEnum, null, param);
84         }
85
86
87
88         /**
89          * Formats and writes a message to the error log with the class name,
90          * throwable and the specified parameters, using log level info, warn or
91          * error appropriate for the specified severity
92          * 
93          * @param classLogger
94          *            Logger for the class where the error occurred; the logger
95          *            carries the class name.
96          * @param epMessageEnum
97          *            Enum carrying alarm and error severity
98          * @param th
99          *            Throwable; ignored if null
100          * @param param
101          *            Array of Strings used to build the message.
102          */
103         @SuppressWarnings("static-access")
104         public static void logEcompError(EELFLoggerDelegate classLogger, EPAppMessagesEnum epMessageEnum, Throwable th,
105                         String... param) {
106                 //INFO, WARN, ERROR, FATAL
107                 AlarmSeverityEnum alarmSeverityEnum = epMessageEnum.getAlarmSeverity();
108                 ErrorSeverityEnum errorSeverityEnum = epMessageEnum.getErrorSeverity();
109
110                 MDC.put("ErrorCategory", errorSeverityEnum.name());
111                 MDC.put("ErrorCode", epMessageEnum.getErrorCode());
112                 MDC.put("ErrorDescription", epMessageEnum.getErrorDescription());
113                 MDC.put(MDC_SERVICE_NAME, EPCommonSystemProperties.ECOMP_PORTAL_BE);
114
115                 final String message = EPLogUtil.formatMessage(epMessageEnum.getDetails() + " " + epMessageEnum.getResolution(),
116                                 (Object[]) param);
117                 if (errorSeverityEnum == ErrorSeverityEnum.INFO) {
118                         if (th == null) {
119                                 classLogger.logWrite(classLogger.errorLogger, Level.INFO, message, null, null);
120                         }
121                         else {
122                                 classLogger.logWrite(classLogger.errorLogger, Level.INFO, message, null, th);
123                         }
124                 } else if (errorSeverityEnum == ErrorSeverityEnum.WARN) {
125                         if (th == null) {
126                                 classLogger.logWrite(classLogger.errorLogger, Level.WARN, message, null, null);
127                         }
128                         else {
129                                 classLogger.logWrite(classLogger.errorLogger, Level.WARN, message, null, th);
130                         }
131                 } else {
132                         if (th == null) {
133                                 classLogger.logWrite(classLogger.errorLogger, Level.ERROR, message, null, null);
134                         }
135                         else {
136                                 classLogger.logWrite(classLogger.errorLogger, Level.ERROR, message, null, th);
137                         }
138                 }
139
140                 // Clean up
141                 MDC.remove(MDC_SERVICE_NAME);
142                 MDC.remove("ErrorCategory");
143                 MDC.remove("ErrorCode");
144                 MDC.remove("ErrorDescription");
145         }
146
147         /**
148          * Builds a string using the format and parameters.
149          * 
150          * @param message
151          * @param args
152          * @return
153          */
154         private static String formatMessage(String message, Object... args) {
155                 StringBuilder sbFormattedMessage = new StringBuilder();
156                 if (args != null && args.length > 0 && message != null && message != "") {
157                         MessageFormat mf = new MessageFormat(message);
158                         sbFormattedMessage.append(mf.format(args));
159                 } else {
160                         sbFormattedMessage.append(message);
161                 }
162                 return sbFormattedMessage.toString();
163         }
164
165         public static void logAuditMessage(EELFLoggerDelegate classLogger, String message) {
166                 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
167                 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
168                 EcompPortalUtils.calculateDateTimeDifferenceForLog(
169                                 MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
170                                 MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
171                 MDC.put("CustomField1", "EXIT");
172                 MDC.put("CustomField2", "InvocationID="+MDC.get(Configuration.MDC_KEY_REQUEST_ID));
173                 try {
174                         MDC.put(Configuration.MDC_SERVER_FQDN, InetAddress.getLocalHost().getCanonicalHostName());
175                 } catch (Exception e) {
176                         classLogger.logWrite(classLogger.errorLogger, Level.WARN, message, null, " exception while setting IP adress.");
177                 }
178                 MDC.put(EPCommonSystemProperties.STATUS_CODE, "COMPLETE");
179                 
180                 classLogger.logWrite(classLogger.auditLogger, Level.INFO, message, null, null);
181                 MDC.remove(Configuration.MDC_SERVER_FQDN);
182                 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
183                 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
184                 MDC.remove(EPCommonSystemProperties.STATUS_CODE);
185                 MDC.remove(SystemProperties.MDC_TIMER);
186                 MDC.remove("CustomField1");
187                 MDC.remove("CustomField2");
188         }
189         
190         
191         /**
192          * Builds a comma-separated string of values to document a user action.
193          * 
194          * @param action
195          *            String
196          * @param activity
197          *            String
198          * @param userId
199          *            String
200          * @param affectedId
201          *            String
202          * @param comment
203          *            String
204          * @return Value suitable for writing to the audit log file.
205          */
206         public static String formatAuditLogMessage(String action, String activity, String userId, String affectedId,
207                         String comment) {
208                 StringBuilder auditLogMsg = new StringBuilder();
209                 auditLogMsg.append("Click_A:[");
210                 if (action != null && !action.equals("")) {
211                         auditLogMsg.append(" Action: ");
212                         auditLogMsg.append(action);
213                 }
214
215                 if (activity != null && !activity.equals("")) {
216                         auditLogMsg.append(",Activity CD: ");
217                         auditLogMsg.append(activity);
218                 }
219
220                 if (userId != null && !userId.equals("")) {
221                         auditLogMsg.append(",User ID: ");
222                         auditLogMsg.append(userId);
223                 }
224
225                 if (affectedId != null && !affectedId.equals("")) {
226                         auditLogMsg.append(",Affected ID: ");
227                         auditLogMsg.append(affectedId);
228                 }
229
230                 if (comment != null && !comment.equals("")) {
231                         auditLogMsg.append(",Comment: ");
232                         auditLogMsg.append(comment);
233                 }
234                 auditLogMsg.append("]");
235                 return auditLogMsg.toString();
236         }
237
238         /**
239          * Builds a comma-separated string of values to document a user browser
240          * action.
241          * 
242          * @param orgUserId
243          *            String
244          * @param appName
245          *            String
246          * @param action
247          *            String
248          * @param activity
249          *            String
250          * @param actionLink
251          *            String
252          * @param page
253          *            String
254          * @param function
255          *            String
256          * @param type
257          *            String
258          * @return String value suitable for writing to the audit log file.
259          */
260         public static String formatStoreAnalyticsAuditLogMessage(String orgUserId, String appName, String action,
261                         String activity, String actionLink, String page, String function, String type) {
262                 StringBuilder auditLogStoreAnalyticsMsg = new StringBuilder();
263                 auditLogStoreAnalyticsMsg.append("Click_Analytics:[");
264                 if (orgUserId != null && !orgUserId.equals("")) {
265                         auditLogStoreAnalyticsMsg.append(" Organization User ID: ");
266                         auditLogStoreAnalyticsMsg.append(orgUserId);
267                 }
268
269                 if (appName != null && !appName.equals("")) {
270                         auditLogStoreAnalyticsMsg.append(",AppName: ");
271                         auditLogStoreAnalyticsMsg.append(appName);
272                 }
273
274                 if (action != null && !action.equals("")) {
275                         auditLogStoreAnalyticsMsg.append(",Action: ");
276                         auditLogStoreAnalyticsMsg.append(action);
277                 }
278
279                 if (activity != null && !activity.equals("")) {
280                         auditLogStoreAnalyticsMsg.append(",Activity: ");
281                         auditLogStoreAnalyticsMsg.append(activity);
282                 }
283
284                 if (actionLink != null && !actionLink.equals("")) {
285                         auditLogStoreAnalyticsMsg.append(",ActionLink: ");
286                         auditLogStoreAnalyticsMsg.append(actionLink);
287                 }
288
289                 if (page != null && !page.equals("")) {
290                         auditLogStoreAnalyticsMsg.append(",Page: ");
291                         auditLogStoreAnalyticsMsg.append(page);
292                 }
293
294                 if (function != null && !function.equals("")) {
295                         auditLogStoreAnalyticsMsg.append(",Function: ");
296                         auditLogStoreAnalyticsMsg.append(function);
297                 }
298
299                 if (type != null && !type.equals("")) {
300                         auditLogStoreAnalyticsMsg.append(",Type: ");
301                         auditLogStoreAnalyticsMsg.append(type);
302                 }
303                 auditLogStoreAnalyticsMsg.append("]");
304                 return auditLogStoreAnalyticsMsg.toString();
305         }
306
307         public static void logExternalAuthAccessAlarm(EELFLoggerDelegate logger, HttpStatus res) {
308                 if (res.equals(HttpStatus.UNAUTHORIZED) || res.equals(HttpStatus.FORBIDDEN)) {
309                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.ExternalAuthAccessAuthenticationError);
310                 } else if (res.equals(HttpStatus.NOT_FOUND) || res.equals(HttpStatus.NOT_ACCEPTABLE)
311                                 || res.equals(HttpStatus.CONFLICT) || res.equals(HttpStatus.BAD_REQUEST)) {
312                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.ExternalAuthAccessConnectionError);
313                 } else if (!res.equals(HttpStatus.ACCEPTED) && !res.equals(HttpStatus.OK)) {
314                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.ExternalAuthAccessGeneralError);
315                 }
316         }
317
318         public static void schedulerAccessAlarm(EELFLoggerDelegate logger, int res) {
319                 if (res == HttpStatus.UNAUTHORIZED.value() || res == HttpStatus.FORBIDDEN.value()) {
320                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.SchedulerAuxAccessAuthenticationError);
321                 } else if (res == HttpStatus.NOT_FOUND.value() || res == HttpStatus.NOT_ACCEPTABLE.value()
322                                 || res == HttpStatus.CONFLICT.value() || res == HttpStatus.BAD_REQUEST.value()
323                                 || res == HttpStatus.REQUEST_TIMEOUT.value()||res==HttpStatus.INTERNAL_SERVER_ERROR.value()) {
324                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.SchedulerAccessConnectionError);
325                 } else if (res == HttpStatus.PRECONDITION_FAILED.value() || res == HttpStatus.EXPECTATION_FAILED.value()) {
326                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.SchedulerInvalidAttributeError);
327                 } else if (res != HttpStatus.ACCEPTED.value() && res != HttpStatus.OK.value()
328                                 && res != HttpStatus.NO_CONTENT.value()) {
329                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.SchedulerAccessGeneralError);
330                 } else {
331                         logger.error(EELFLoggerDelegate.errorLogger, "Other SchedulerErrors failed", res);
332                 }
333         }
334
335 }