19115ce55b5afc8e0a1f4fc749fe6c60d9942276
[so.git] / common / src / main / java / org / openecomp / mso / logger / MsoLogger.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  * 
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  * 
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.openecomp.mso.logger;
23
24 import java.io.BufferedReader;
25 import java.io.BufferedWriter;
26 import java.io.File;
27 import java.io.FileReader;
28 import java.io.FileWriter;
29 import java.io.IOException;
30 import java.io.PrintWriter;
31 import java.io.StringWriter;
32 import java.net.InetAddress;
33 import java.net.UnknownHostException;
34 import java.util.UUID;
35 import java.util.logging.Level;
36 import java.util.logging.Logger;
37
38 import org.slf4j.MDC;
39
40 import org.openecomp.mso.entity.MsoRequest;
41 import com.att.eelf.configuration.EELFLogger;
42 import com.att.eelf.configuration.EELFManager;
43 import com.att.eelf.i18n.EELFResolvableErrorEnum;
44
45 import java.text.DateFormat;
46 import java.text.SimpleDateFormat;
47 import java.util.Date;
48
49 /**
50  * Simple wrapper around the EELF Logger class for MSO usage. This class
51  * supports all of the normal logging functions (debug, info, etc.), prepending
52  * a string of format "[<requestId>|<serviceId]" to each message.
53  *
54  * MSO code should initialize with these IDs when available, so that individual
55  * requests and/or services can be tracked throughout the various MSO component
56  * logs (API Handler, BPEL, and Adapters).
57  *
58  *
59  */
60 public class MsoLogger {
61     // MDC parameters
62     public static final String  REQUEST_ID                  = "RequestId";
63     public static final String  SERVICE_INSTANCE_ID         = "ServiceInstanceId";
64     public static final String  SERVICE_NAME                = "ServiceName";
65     private static final String SERVICE_NAME_IS_METHOD_NAME = "ServiceNameIsMethodName";
66     private static final String INSTANCE_UUID               = "InstanceUUID";
67     private static final String SERVER_IP                   = "ServerIPAddress";
68     private static final String FQDN                        = "ServerFQDN";
69     public static final String  REMOTE_HOST                 = "RemoteHost";
70     public static final String  ALERT_SEVERITY              = "AlertSeverity";
71     public static final String  TIMER                       = "Timer";
72     private static final String USER                        = "User";
73     private static final String DUMMY_VALUE                 = "trace-#";
74     public static final String  UNKNOWN                     = "UNKNOWN";
75     //For getting an identity of calling application
76     public static final String HEADER_FROM_APP_ID           = "X-FromAppId";
77     public static final String FROM_APP_ID                  = "FromAppId";
78     // Audit/Metric log specific
79     private static final String BEGINTIME                   = "BeginTimestamp";
80     private static final String ENDTIME                     = "EndTimestamp";
81     public static final String  PARTNERNAME                 = "PartnerName";
82     private static final String STATUSCODE                  = "StatusCode";
83     private static final String RESPONSECODE                = "ResponseCode";
84     private static final String RESPONSEDESC                = "ResponseDesc";
85     // Metric log specific
86     private static final String TARGETENTITY                = "TargetEntity";
87     private static final String TARGETSERVICENAME           = "TargetServiceName";
88     private static final String TARGETVIRTUALENTITY         = "TargetVirtualEntity";
89
90     private static final String FATAL_LEVEL                 = "FATAL";
91     private static final String ERROR_LEVEL                 = "ERROR";
92     private static final String WARN_LEVEL                  = "WARN";
93     private static final String INFO_LEVEL                  = "INFO";
94     private static final String DEBUG_LEVEL                 = "DEBUG";
95
96     private static final String ERRORCODE                   = "ErrorCode";
97     private static final String ERRORDESC                   = "ErrorDesc";
98
99     public enum Catalog {
100         APIH, BPEL, RA, ASDC, GENERAL
101     };
102
103     public enum StatusCode {
104         COMPLETE, ERROR
105     };
106
107     public enum ResponseCode {
108         Suc(0), PermissionError(100), DataError(300), DataNotFound(301), BadRequest(302), SchemaError(
109                 400), BusinessProcesssError(500), ServiceNotAvailable(501), InternalError(
110                         502), Conflict(503), DBAccessError(504), CommunicationError(505), UnknownError(900);
111
112         private int value;
113
114         public int getValue() {
115             return this.value;
116         }
117
118         private ResponseCode(int value) {
119             this.value = value;
120         }
121     };
122
123     public enum ErrorCode {
124         PermissionError(100), AvailabilityError(200), DataError(300), SchemaError(400), BusinessProcesssError(
125                 500), UnknownError(900);
126
127         private int value;
128
129         public int getValue() {
130             return this.value;
131         }
132
133         private ErrorCode(int value) {
134             this.value = value;
135         }
136     };
137
138     private EELFLogger          debugLogger, errorLogger, auditLogger, metricsLogger;
139     private static final String CONFIG_FILE = System.getProperty("jboss.home.dir") + "/mso-config/uuid/uuid_"
140             + System.getProperty("jboss.server.name");
141     private static String       instanceUUID, serverIP, serverName;
142     private MessageEnum         exceptionArg, defaultException, defaultWarning, defaultAudit, defaultMetrics;
143
144     // For internal logging of the initialization of MSO logs
145     private static final Logger LOGGER      = Logger.getLogger(MsoLogger.class.getName());
146
147     private MsoLogger(MsoLogger.Catalog cat) {
148         this.debugLogger = EELFManager.getInstance().getDebugLogger();
149         this.errorLogger = EELFManager.getInstance().getErrorLogger();
150         this.auditLogger = EELFManager.getInstance().getAuditLogger();
151         this.metricsLogger = EELFManager.getInstance().getMetricsLogger();
152         MsoLogger.initialization();
153         setDefaultLogCatalog(cat);
154     }
155
156     private static synchronized void initialization() {
157         if (instanceUUID == null || ("").equals(instanceUUID)) {
158             instanceUUID = getInstanceUUID();
159         }
160
161         if (serverIP == null || serverName == null || ("").equals(serverIP) || ("").equals(serverName)) {
162             try {
163                 InetAddress server = InetAddress.getLocalHost();
164                 serverIP = server.getHostAddress();
165                 serverName = server.getHostName();
166             } catch (UnknownHostException e) {
167                 LOGGER.log(Level.SEVERE, "Could not get local hostname", e);
168                 serverIP = "";
169                 serverName = "";
170             }
171         }
172     }
173
174     /**
175      * Get the MsoLogger based on the catalog
176      * 
177      * @param cat
178      *            Catalog of the logger
179      * @return the MsoLogger
180      */
181     public static synchronized MsoLogger getMsoLogger(MsoLogger.Catalog cat) {
182         return new MsoLogger(cat);
183     }
184
185     /**
186      * Record the Metrics event with no argument
187      * 
188      * @param startTime
189      *            Transaction starting time in millieseconds
190      * @param statusCode
191      *            StatusCode of the transaction, either COMPLETE or ERROR
192      * @param responseCode
193      *            The response code returned by the sub-components
194      * @param responseDesc
195      *            Human redable description of the response code
196      * @param targetEntity
197      *            The component which is invoked for this sub-operation
198      * @param targetServiceName
199      *            API invoked on the TargetEntity
200      * @param targetVEntity
201      *            Target VNF or VM acted opon by the component, if available
202      */
203     public void recordMetricEvent(Long startTime, StatusCode statusCode, ResponseCode responseCode, String responseDesc,
204             String targetEntity, String targetServiceName, String targetVEntity) {
205         prepareMetricMsg(startTime, statusCode, responseCode.getValue(), responseDesc, targetEntity, targetServiceName,
206                 targetVEntity);
207         metricsLogger.info("");
208         MDC.remove(TIMER);
209         MDC.remove(TARGETENTITY);
210         MDC.remove(TARGETSERVICENAME);
211     }
212
213     /**
214      * Record the Audit event
215      *
216      * @param startTime
217      *            Transaction starting time in millieseconds
218      * @param statusCode
219      *            StatusCode of the transaction, either COMPLETE or ERROR
220      * @param responseCode
221      *            The application specific response code
222      * @param responseDesc
223      *            Human redable description of the application response code
224      */
225     public void recordAuditEvent(Long startTime, StatusCode statusCode, ResponseCode responseCode,
226             String responseDesc) {
227         prepareAuditMsg(startTime, statusCode, responseCode.getValue(), responseDesc);
228         auditLogger.info("");
229         MDC.remove(TIMER);
230     }
231
232     // Debug methods
233     /**
234      * Record the Debug event
235      *
236      * @param msg
237      *            The log message to put
238      */
239     public void debug(String msg) {
240         prepareMsg(DEBUG_LEVEL);
241         debugLogger.debug(msg);
242     }
243
244     /**
245      * Record the Debug event
246      *
247      * @param msg
248      *            The log message to put
249      * @param t
250      *            The exception to put
251      */
252     public void debug(String msg, Throwable t) {
253         prepareMsg(DEBUG_LEVEL);
254         debugLogger.debug(msg, t);
255     }
256
257     // Info methods
258     /**
259      * Record the Info event
260      *
261      * @param msg
262      *            The log message to put
263      */
264     public void info(EELFResolvableErrorEnum msg, String targetEntity, String targetServiceName) {
265         prepareErrorMsg(INFO_LEVEL, targetEntity, targetServiceName, null, "");
266
267         debugLogger.info(msg);
268         MDC.remove(TARGETENTITY);
269         MDC.remove(TARGETSERVICENAME);
270     }
271
272     /**
273      * Record the Info event with 1 argument
274      *
275      * @param msg
276      *            The log message to put
277      * @param arg0
278      *            The argument used in the log message
279      */
280     public void info(EELFResolvableErrorEnum msg, String arg0, String targetEntity, String targetServiceName) {
281         prepareErrorMsg(INFO_LEVEL, targetEntity, targetServiceName, null, "");
282
283         debugLogger.info(msg, normalize(arg0));
284         MDC.remove(TARGETENTITY);
285         MDC.remove(TARGETSERVICENAME);
286     }
287
288     /**
289      * Record the Info event with 2 arguments
290      *
291      * @param msg
292      *            The log message to put
293      * @param arg0,arg1
294      *            The arguments used in the log message
295      */
296     public void info(EELFResolvableErrorEnum msg, String arg0, String arg1, String targetEntity,
297             String targetServiceName) {
298         prepareErrorMsg(INFO_LEVEL, targetEntity, targetServiceName, null, "");
299
300         debugLogger.info(msg, normalize(arg0), normalize(arg1));
301         MDC.remove(TARGETENTITY);
302         MDC.remove(TARGETSERVICENAME);
303     }
304
305     /**
306      * Record the Info event with 3 arguments
307      *
308      * @param msg
309      *            The log message to put
310      * @param arg0,arg1,arg2
311      *            The arguments used in the log message
312      */
313     public void info(EELFResolvableErrorEnum msg, String arg0, String arg1, String arg2, String targetEntity,
314             String targetServiceName) {
315         prepareErrorMsg(INFO_LEVEL, targetEntity, targetServiceName, null, "");
316
317         debugLogger.info(msg, normalize(arg0), normalize(arg1), normalize(arg2));
318         MDC.remove(TARGETENTITY);
319         MDC.remove(TARGETSERVICENAME);
320     }
321
322     /**
323      * Record the Info event with 4 arguments
324      *
325      * @param msg
326      *            The log message to put
327      * @param arg0,arg1,arg2,arg3
328      *            The arguments used in the log message
329      */
330     public void info(EELFResolvableErrorEnum msg, String arg0, String arg1, String arg2, String arg3,
331             String targetEntity, String targetServiceName) {
332         prepareErrorMsg(INFO_LEVEL, targetEntity, targetServiceName, null, "");
333
334         debugLogger.info(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3));
335         MDC.remove(TARGETENTITY);
336         MDC.remove(TARGETSERVICENAME);
337     }
338
339     /**
340      * Record the Info event with 5 arguments
341      *
342      * @param msg
343      *            The log message to put
344      * @param arg0,arg1,arg2,arg3,arg4
345      *            The arguments used in the log message
346      */
347     public void info(EELFResolvableErrorEnum msg, String arg0, String arg1, String arg2, String arg3, String arg4,
348             String targetEntity, String targetServiceName) {
349         prepareErrorMsg(INFO_LEVEL, targetEntity, targetServiceName, null, "");
350
351         debugLogger.info(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3), normalize(arg4));
352         MDC.remove(TARGETENTITY);
353         MDC.remove(TARGETSERVICENAME);
354     }
355
356     /**
357      * Record the Info event with 6 arguments
358      *
359      * @param msg
360      *            The log message to put
361      * @param arg0,arg1,arg2,arg3,arg4,arg5
362      *            The arguments used in the log message
363      */
364     public void info(EELFResolvableErrorEnum msg, String arg0, String arg1, String arg2, String arg3, String arg4,
365             String arg5, String targetEntity, String targetServiceName) {
366         prepareErrorMsg(INFO_LEVEL, targetEntity, targetServiceName, null, "");
367
368         debugLogger.info(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3), normalize(arg4),
369                 normalize(arg5));
370         MDC.remove(TARGETENTITY);
371         MDC.remove(TARGETSERVICENAME);
372     }
373
374     // Warning methods
375     /**
376      * Record the Warning event
377      *
378      * @param msg
379      *            The log message to put
380      */
381     public void warn(EELFResolvableErrorEnum msg, String targetEntity, String targetServiceName, ErrorCode errorCode,
382             String errorDesc) {
383         prepareErrorMsg(WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc);
384
385         errorLogger.warn(msg);
386         MDC.remove(TARGETENTITY);
387         MDC.remove(TARGETSERVICENAME);
388     }
389
390     /**
391      * Record the Warning event
392      *
393      * @param msg
394      *            The log message to put
395      * @param t
396      *            The exception info
397      */
398     public void warn(EELFResolvableErrorEnum msg, String targetEntity, String targetServiceName, ErrorCode errorCode,
399             String errorDesc, Throwable t) {
400         prepareErrorMsg(WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc);
401         errorLogger.warn(msg);
402         errorLogger.warn("Exception raised: " + getNormalizedStackTrace(t));
403         debugLogger.debug("Exception raised", t);
404         MDC.remove(TARGETENTITY);
405         MDC.remove(TARGETSERVICENAME);
406     }
407
408     /**
409      * Record the Warn event with 1 argument
410      *
411      * @param msg
412      *            The log message to put
413      * @param arg
414      *            The argument used in the log message
415      */
416     public void warn(EELFResolvableErrorEnum msg, String arg, String targetEntity, String targetServiceName,
417             ErrorCode errorCode, String errorDesc) {
418         prepareErrorMsg(WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc);
419         errorLogger.warn(msg, arg);
420         MDC.remove(TARGETENTITY);
421         MDC.remove(TARGETSERVICENAME);
422     }
423
424     /**
425      * Record the Warn event with 1 argument
426      *
427      * @param msg
428      *            The log message to put
429      * @param arg
430      *            The arguments used in the log message
431      * @param t
432      *            The exception info
433      */
434     public void warn(EELFResolvableErrorEnum msg, String arg, String targetEntity, String targetServiceName,
435             ErrorCode errorCode, String errorDesc, Throwable t) {
436         prepareErrorMsg(WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc);
437         errorLogger.warn(msg, arg);
438         errorLogger.warn("Exception raised: " + getNormalizedStackTrace(t));
439         debugLogger.debug("Exception raised", t);
440         MDC.remove(TARGETENTITY);
441         MDC.remove(TARGETSERVICENAME);
442     }
443
444     /**
445      * Record the Warn event with 2 arguments
446      *
447      * @param msg
448      *            The log message to put
449      * @param arg0,arg1
450      *            The arguments used in the log message
451      */
452     public void warn(EELFResolvableErrorEnum msg, String arg0, String arg1, String targetEntity,
453             String targetServiceName, ErrorCode errorCode, String errorDesc) {
454         prepareErrorMsg(WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc);
455         errorLogger.warn(msg, normalize(arg0), normalize(arg1));
456         MDC.remove(TARGETENTITY);
457         MDC.remove(TARGETSERVICENAME);
458     }
459
460     /**
461      * Record the Warn event with 2 arguments
462      *
463      * @param msg
464      *            The log message to put
465      * @param arg0,arg1
466      *            The arguments used in the log message
467      * @param t
468      *            The exception info
469      */
470     public void warn(EELFResolvableErrorEnum msg, String arg0, String arg1, String targetEntity,
471             String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) {
472         prepareErrorMsg(WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc);
473         errorLogger.warn(msg, normalize(arg0), normalize(arg1));
474         errorLogger.warn("Exception raised: " + getNormalizedStackTrace(t));
475         debugLogger.debug("Exception raised", t);
476         MDC.remove(TARGETENTITY);
477         MDC.remove(TARGETSERVICENAME);
478     }
479
480     /**
481      * Record the Warn event with 3 arguments
482      *
483      * @param msg
484      *            The log message to put
485      * @param arg0,arg1,arg2
486      *            The arguments used in the log message
487      */
488     public void warn(EELFResolvableErrorEnum msg, String arg0, String arg1, String arg2, String targetEntity,
489             String targetServiceName, ErrorCode errorCode, String errorDesc) {
490         prepareErrorMsg(WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc);
491         errorLogger.warn(msg, normalize(arg0), normalize(arg1), normalize(arg2));
492         MDC.remove(TARGETENTITY);
493         MDC.remove(TARGETSERVICENAME);
494     }
495
496     /**
497      * Record the Warn event with 3 arguments
498      *
499      * @param msg
500      *            The log message to put
501      * @param arg0,arg1,arg2
502      *            The arguments used in the log message
503      * @param t
504      *            The exception info
505      */
506     public void warn(EELFResolvableErrorEnum msg, String arg0, String arg1, String arg2, String targetEntity,
507             String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) {
508         prepareErrorMsg(WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc);
509         errorLogger.warn(msg, normalize(arg0), normalize(arg1), normalize(arg2));
510         errorLogger.warn("Exception raised: " + getNormalizedStackTrace(t));
511         debugLogger.debug("Exception raised", t);
512         MDC.remove(TARGETENTITY);
513         MDC.remove(TARGETSERVICENAME);
514     }
515
516     /**
517      * Record the Warn event with 4 arguments
518      *
519      * @param msg
520      *            The log message to put
521      * @param arg0,arg1,arg2,arg3
522      *            The arguments used in the log message
523      */
524     public void warn(EELFResolvableErrorEnum msg, String arg0, String arg1, String arg2, String arg3,
525             String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc) {
526         prepareErrorMsg(WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc);
527         errorLogger.warn(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3));
528         MDC.remove(TARGETENTITY);
529         MDC.remove(TARGETSERVICENAME);
530     }
531
532     /**
533      * Record the Warn event with 4 arguments
534      *
535      * @param msg
536      *            The log message to put
537      * @param arg0,arg1,arg2,
538      *            arg3 The arguments used in the log message
539      * @param t
540      *            The exception info
541      */
542     public void warn(EELFResolvableErrorEnum msg, String arg0, String arg1, String arg2, String arg3,
543             String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) {
544         prepareErrorMsg(WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc);
545         errorLogger.warn(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3));
546         errorLogger.warn("Exception raised: " + getNormalizedStackTrace(t));
547         debugLogger.debug("Exception raised", t);
548         MDC.remove(TARGETENTITY);
549         MDC.remove(TARGETSERVICENAME);
550     }
551
552     /**
553      * Record the Warn event with 5 arguments
554      *
555      * @param msg
556      *            The log message to put
557      * @param arg0,arg1,arg2,arg3,arg4
558      *            The arguments used in the log message
559      */
560     public void warn(EELFResolvableErrorEnum msg, String arg0, String arg1, String arg2, String arg3, String arg4,
561             String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc) {
562         prepareErrorMsg(WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc);
563         errorLogger.warn(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3), normalize(arg4));
564         MDC.remove(TARGETENTITY);
565         MDC.remove(TARGETSERVICENAME);
566     }
567
568     /**
569      * Record the Warn event with 5 arguments
570      *
571      * @param msg
572      *            The log message to put
573      * @param arg0,arg1,arg2,arg3,arg4
574      *            The arguments used in the log message
575      * @param t
576      *            The exception info
577      */
578     public void warn(EELFResolvableErrorEnum msg, String arg0, String arg1, String arg2, String arg3, String arg4,
579             String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) {
580         prepareErrorMsg(WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc);
581         errorLogger.warn(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3), normalize(arg4));
582         errorLogger.warn("Exception raised: " + getNormalizedStackTrace(t));
583         debugLogger.debug("Exception raised", t);
584         MDC.remove(TARGETENTITY);
585         MDC.remove(TARGETSERVICENAME);
586     }
587
588     // Error methods
589     /**
590      * Record the Error event
591      *
592      * @param msg
593      *            The log message to put
594      */
595     public void error(EELFResolvableErrorEnum msg, String targetEntity, String targetServiceName, ErrorCode errorCode,
596             String errorDesc) {
597         prepareErrorMsg(ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc);
598         errorLogger.error(msg);
599         MDC.remove(TARGETENTITY);
600         MDC.remove(TARGETSERVICENAME);
601     }
602
603     /**
604      * Record the Error event
605      *
606      * @param msg
607      *            The log message to put
608      * @param t
609      *            The exception info
610      */
611     public void error(EELFResolvableErrorEnum msg, String targetEntity, String targetServiceName, ErrorCode errorCode,
612             String errorDesc, Throwable t) {
613         prepareErrorMsg(ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc);
614         errorLogger.error(msg);
615         errorLogger.error(exceptionArg, getNormalizedStackTrace(t));
616         debugLogger.debug("Exception raised", t);
617         MDC.remove(TARGETENTITY);
618         MDC.remove(TARGETSERVICENAME);
619     }
620
621     /**
622      * Record the Error event with 1 argument
623      *
624      * @param msg
625      *            The log message to put
626      * @param arg0
627      *            The arguments used in the log message
628      */
629     public void error(EELFResolvableErrorEnum msg, String arg0, String targetEntity, String targetServiceName,
630             ErrorCode errorCode, String errorDesc) {
631         prepareErrorMsg(ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc);
632         errorLogger.error(msg, normalize(arg0));
633         MDC.remove(TARGETENTITY);
634         MDC.remove(TARGETSERVICENAME);
635     }
636
637     /**
638      * Record the Error event with 1 argument
639      *
640      * @param msg
641      *            The log message to put
642      * @param arg0
643      *            The arguments used in the log message
644      * @param t
645      *            The exception info
646      */
647     public void error(EELFResolvableErrorEnum msg, String arg0, String targetEntity, String targetServiceName,
648             ErrorCode errorCode, String errorDesc, Throwable t) {
649         prepareErrorMsg(ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc);
650         errorLogger.error(msg, normalize(arg0));
651         errorLogger.error(exceptionArg, getNormalizedStackTrace(t));
652         debugLogger.debug("Exception raised", t);
653         MDC.remove(TARGETENTITY);
654         MDC.remove(TARGETSERVICENAME);
655     }
656
657     /**
658      * Record the Error event with 2 arguments
659      *
660      * @param msg
661      *            The log message to put
662      * @param arg0,arg1
663      *            The arguments used in the log message
664      */
665     public void error(EELFResolvableErrorEnum msg, String arg0, String arg1, String targetEntity,
666             String targetServiceName, ErrorCode errorCode, String errorDesc) {
667         prepareErrorMsg(ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc);
668         errorLogger.error(msg, normalize(arg0), normalize(arg1));
669         MDC.remove(TARGETENTITY);
670         MDC.remove(TARGETSERVICENAME);
671     }
672
673     /**
674      * Record the Error event with 2 arguments
675      *
676      * @param msg
677      *            The log message to put
678      * @param arg0,arg1
679      *            The arguments used in the log message
680      * @param t
681      *            The exception info
682      */
683     public void error(EELFResolvableErrorEnum msg, String arg0, String arg1, String targetEntity,
684             String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) {
685         prepareErrorMsg(ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc);
686         errorLogger.error(msg, normalize(arg0), normalize(arg1));
687         errorLogger.error(exceptionArg, getNormalizedStackTrace(t));
688         debugLogger.debug("Exception raised", t);
689         MDC.remove(TARGETENTITY);
690         MDC.remove(TARGETSERVICENAME);
691     }
692
693     /**
694      * Record the Error event with 3 arguments
695      *
696      * @param msg
697      *            The log message to put
698      * @param arg0,arg1,arg2
699      *            The arguments used in the log message
700      */
701     public void error(EELFResolvableErrorEnum msg, String arg0, String arg1, String arg2, String targetEntity,
702             String targetServiceName, ErrorCode errorCode, String errorDesc) {
703         prepareErrorMsg(ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc);
704         errorLogger.error(msg, normalize(arg0), normalize(arg1), normalize(arg2));
705         MDC.remove(TARGETENTITY);
706         MDC.remove(TARGETSERVICENAME);
707     }
708
709     /**
710      * Record the Error event with 3 arguments
711      *
712      * @param msg
713      *            The log message to put
714      * @param arg0,arg1,arg2
715      *            The arguments used in the log message
716      * @param t
717      *            The exception info
718      */
719     public void error(EELFResolvableErrorEnum msg, String arg0, String arg1, String arg2, String targetEntity,
720             String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) {
721         prepareErrorMsg(ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc);
722         errorLogger.error(msg, normalize(arg0), normalize(arg1), normalize(arg2));
723         errorLogger.error(exceptionArg, getNormalizedStackTrace(t));
724         debugLogger.debug("Exception raised", t);
725         MDC.remove(TARGETENTITY);
726         MDC.remove(TARGETSERVICENAME);
727     }
728
729     /**
730      * Record the Error event with 4 arguments
731      *
732      * @param msg
733      *            The log message to put
734      * @param arg0,arg1,arg2,arg3
735      *            The arguments used in the log message
736      */
737     public void error(EELFResolvableErrorEnum msg, String arg0, String arg1, String arg2, String arg3,
738             String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc) {
739         prepareErrorMsg(ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc);
740         errorLogger.error(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3));
741         MDC.remove(TARGETENTITY);
742         MDC.remove(TARGETSERVICENAME);
743     }
744
745     /**
746      * Record the Error event with 4 arguments
747      *
748      * @param msg
749      *            The log message to put
750      * @param arg0,arg1,arg2,arg3
751      *            The arguments used in the log message
752      * @param t
753      *            The exception info
754      */
755     public void error(EELFResolvableErrorEnum msg, String arg0, String arg1, String arg2, String arg3,
756             String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) {
757         prepareErrorMsg(ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc);
758         errorLogger.error(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3));
759         errorLogger.error(exceptionArg, getNormalizedStackTrace(t));
760         debugLogger.debug("Exception raised", t);
761         MDC.remove(TARGETENTITY);
762         MDC.remove(TARGETSERVICENAME);
763     }
764
765     /**
766      * Record the Error event with 5 arguments
767      *
768      * @param msg
769      *            The log message to put
770      * @param arg0,arg1,arg2,arg3,arg4
771      *            The arguments used in the log message
772      */
773     public void error(EELFResolvableErrorEnum msg, String arg0, String arg1, String arg2, String arg3, String arg4,
774             String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc) {
775         prepareErrorMsg(ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc);
776         errorLogger.error(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3), normalize(arg4));
777         MDC.remove(TARGETENTITY);
778         MDC.remove(TARGETSERVICENAME);
779     }
780
781     /**
782      * Record the Error event with 5 arguments
783      *
784      * @param msg
785      *            The log message to put
786      * @param arg0,arg1,arg2,arg3,arg4
787      *            The arguments used in the log message
788      * @param t
789      *            The exception info
790      */
791     public void error(EELFResolvableErrorEnum msg, String arg0, String arg1, String arg2, String arg3, String arg4,
792             String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) {
793         prepareErrorMsg(ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc);
794         errorLogger.error(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3), normalize(arg4));
795         errorLogger.error(exceptionArg, getNormalizedStackTrace(t));
796         debugLogger.debug("Exception raised", t);
797         MDC.remove(TARGETENTITY);
798         MDC.remove(TARGETSERVICENAME);
799     }
800
801     public boolean isDebugEnabled() {
802         return debugLogger.isDebugEnabled();
803     }
804
805     private void prepareMsg(String loggingLevel) {
806         prepareMsg(loggingLevel, null, null);
807     }
808
809     private void prepareMsg(String loggingLevel, String serviceNamep, String timer) {
810         String reqId = MDC.get(REQUEST_ID);
811         String svcId = MDC.get(SERVICE_INSTANCE_ID);
812
813         // Based on the discussion with Adrian,
814         // if these 2 parameters is not available, using dummy value "trace-#"
815         if (reqId == null || reqId.isEmpty()) {
816             MDC.put(REQUEST_ID, DUMMY_VALUE);
817         }
818
819         if (svcId == null || svcId.isEmpty()) {
820             MDC.put(SERVICE_INSTANCE_ID, DUMMY_VALUE);
821         }
822
823         if (timer != null) {
824             MDC.put(TIMER, timer);
825         } else {
826             MDC.remove(TIMER);
827         }
828
829         MDC.put(SERVICE_NAME, getFinalServiceName(serviceNamep));
830         MDC.put(ALERT_SEVERITY, getSeverityLevel(loggingLevel));
831         MDC.put(INSTANCE_UUID, instanceUUID);
832         MDC.put(SERVER_IP, serverIP);
833         MDC.put(FQDN, serverName);
834     }
835
836     private void prepareAuditMsg(long startTime, StatusCode statusCode, int responseCode, String responseDesc) {
837         long endTime = System.currentTimeMillis();
838         prepareMsg(INFO_LEVEL, null, String.valueOf(endTime - startTime));
839         prepareAuditMetricMsg(startTime, endTime, statusCode, responseCode, responseDesc);
840     }
841
842     private void prepareAuditMetricMsg(long startTime, long endTime, StatusCode statusCode, int responseCode,
843             String responseDesc) {
844         Date startDate = new Date(startTime);
845         Date endDate = new Date(endTime);
846         DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
847
848         MDC.put(BEGINTIME, String.valueOf(formatter.format(startDate)));
849         MDC.put(ENDTIME, String.valueOf(formatter.format(endDate)));
850         MDC.put(STATUSCODE, statusCode.name());
851         MDC.put(RESPONSECODE, String.valueOf(responseCode));
852         MDC.put(RESPONSEDESC, responseDesc);
853     }
854
855     private void prepareErrorMsg(String loggingLevel, String targetEntity, String targetServiceName,
856             ErrorCode errorCode, String errorDesc) {
857         MDC.put(ALERT_SEVERITY, getSeverityLevel(loggingLevel));
858         MDC.put(ERRORCODE, String.valueOf(errorCode));
859         MDC.put(ERRORDESC, errorDesc);
860         MDC.put(TARGETENTITY, targetEntity);
861         MDC.put(TARGETSERVICENAME, targetServiceName);
862         MDC.put(SERVICE_NAME, getFinalServiceName(getServiceName()));
863     }
864
865     private void prepareMetricMsg(long startTime, StatusCode statusCode, int responseCode, String responseDesc,
866             String targetEntity, String targetServiceName, String targetVEntity) {
867         long endTime = System.currentTimeMillis();
868         prepareMsg(INFO_LEVEL, null, String.valueOf(endTime - startTime));
869         prepareAuditMetricMsg(startTime, endTime, statusCode, responseCode, responseDesc);
870
871         // Populate Metric log specific parameter
872         MDC.put(TARGETENTITY, targetEntity);
873         MDC.put(TARGETSERVICENAME, targetServiceName);
874
875         if (null != targetVEntity) {
876             MDC.put(TARGETVIRTUALENTITY, targetVEntity);
877         }
878     }
879
880     private String getSeverityLevel(String loggingLevel) {
881         String severity;
882         // According to the Nagios alerting: 0=OK; 1=WARNING; 2=UNKOWN;
883         // 3=CRITICAL
884         switch (loggingLevel) {
885             case ERROR_LEVEL:
886                 severity = "2";
887                 break;
888             case FATAL_LEVEL:
889                 severity = "3";
890                 break;
891             case WARN_LEVEL:
892                 severity = "1";
893                 break;
894             default:
895                 severity = "0";
896                 break;
897         }
898         return severity;
899     }
900
901     private String getFinalServiceName(String serviceNamep) {
902         // This step to set the serviceName should be put after the className is
903         // get,
904         // since the default serviceName is obtained during the method to get
905         // the className.
906         //
907         // There's 3 ways to set the serviceName. The first method has the most
908         // priority to set the value.
909         // a) If the serviceName is set within the log method, this value will
910         // be used first
911         // b) If serviceName is not set within the log method, the value defined
912         // in the MDC will be used
913         // c) If nothing is set specifically, then MsoLogger will assign a
914         // default(MSO.<method_name>) value to it
915         String serName = MDC.get(MsoLogger.SERVICE_NAME);
916
917         // Check if service name was already set as the method name by a
918         // previous call to this method.
919         String isMethodNameStr = MDC.get(MsoLogger.SERVICE_NAME_IS_METHOD_NAME);
920         boolean isMethodName = isMethodNameStr != null && isMethodNameStr.equals(Boolean.TRUE.toString());
921         if (serviceNamep != null) {
922             return serviceNamep;
923         } else if (serName != null && !isMethodName) {
924             return serName;
925         }
926
927         MDC.put(MsoLogger.SERVICE_NAME_IS_METHOD_NAME, Boolean.TRUE.toString());
928         int limit;
929         StackTraceElement[] classArr = new Exception().getStackTrace();
930         if (classArr.length >= 6) {
931             limit = 7;
932         } else {
933             limit = classArr.length;
934         }
935         for (int i = 1; i < limit; i++) {
936             String className = classArr[i].getClassName();
937             if (!className.equals(this.getClass().getName())) {
938                 return classArr[i].getMethodName();
939             }
940         }
941         return classArr[0].getMethodName();
942     }
943
944     // Based on the discussion with Adrian, instanceUUID is used to identifiy
945     // the mso instance,
946     // it is generated during mso instance initialization period
947     // The same mso instnace will use the same instanceUUID value, even after
948     // restart
949     private static String getInstanceUUID() {
950         // Avoid creation during build and tests
951         if (System.getProperty("jboss.server.name") == null) {
952             return "Test UUID as JBoss not found";
953         }
954         File configFile = new File(CONFIG_FILE);
955         String uuid = "";
956         BufferedReader in = null;
957         BufferedWriter bw = null;
958         try {
959             // Verify whether instanceUUID file exist,
960             // If yes, read the content; if not, generate the instanceUUID and
961             // write to the file
962             if (configFile.exists()) {
963                 // read the content of the file
964                 in = new BufferedReader(new FileReader(CONFIG_FILE));
965                 if ((uuid = in.readLine()) == null) {
966                     // the file is empty, regenerate the file
967                     uuid = UUID.randomUUID().toString();
968                     FileWriter fw = new FileWriter(configFile.getAbsoluteFile());
969                     bw = new BufferedWriter(fw);
970                     bw.write(uuid);
971                     bw.close();
972                 }
973                 in.close();
974             } else {
975                 // file doesn't exist yet -> create the file and generate the
976                 // instanceUUID
977                 uuid = UUID.randomUUID().toString();
978                 configFile.getParentFile().mkdirs();
979                 configFile.createNewFile();
980                 FileWriter fw = new FileWriter(configFile.getAbsoluteFile());
981                 bw = new BufferedWriter(fw);
982                 bw.write(uuid);
983                 bw.close();
984             }
985         } catch (IOException e) {
986             LOGGER.log(Level.SEVERE, "Error trying to read UUID file", e);
987         } finally {
988             try {
989                 if (in != null) {
990                     in.close();
991                 }
992                 if (bw != null) {
993                     bw.close();
994                 }
995             } catch (IOException ex) {
996                 LOGGER.log(Level.SEVERE, "Error trying to close UUID file", ex);
997             }
998         }
999         return uuid;
1000     }
1001
1002     /**
1003      * Set the requestId and serviceInstanceId
1004      * 
1005      * @param reqId
1006      *            The requestId
1007      * @param svcId
1008      *            The serviceInstanceId
1009      */
1010     public static void setLogContext(String reqId, String svcId) {
1011         if (null != reqId) {
1012             MDC.put(REQUEST_ID, reqId);
1013         }
1014
1015         if (null != svcId) {
1016             MDC.put(SERVICE_INSTANCE_ID, svcId);
1017         }
1018     }
1019
1020     /**
1021      * Set the remoteIp and the basic HTTP Authentication user
1022      * 
1023      * @param remoteIpp
1024      *            The remote ip address
1025      * @param userp
1026      *            The basic http authencitation user
1027      */
1028     public static void setLoggerParameters(String remoteIpp, String userp) {
1029         if (null != remoteIpp) {
1030             MDC.put(REMOTE_HOST, remoteIpp);
1031         }
1032         if (null != userp) {
1033             MDC.put(USER, userp);
1034         }
1035     }
1036
1037     /**
1038      * Set the serviceName
1039      * 
1040      * @param serviceNamep
1041      *            The service name
1042      */
1043     public static void setServiceName(String serviceNamep) {
1044         if (null != serviceNamep) {
1045             MDC.put(SERVICE_NAME, serviceNamep);
1046             MDC.remove(SERVICE_NAME_IS_METHOD_NAME);
1047         }
1048     }
1049
1050     /**
1051      * Get the serviceName
1052      * 
1053      * @return The service name
1054      */
1055     public static String getServiceName() {
1056         return MDC.get(SERVICE_NAME);
1057     }
1058
1059     /**
1060      * Reset the serviceName
1061      */
1062     public static void resetServiceName() {
1063         MDC.remove(SERVICE_NAME);
1064     }
1065
1066     /**
1067      * Set the requestId and serviceInstanceId based on the mso request
1068      * 
1069      * @param msoRequest
1070      *            The mso request
1071      */
1072     public static void setLogContext(MsoRequest msoRequest) {
1073         if (msoRequest != null) {
1074             MDC.put(REQUEST_ID, msoRequest.getRequestId());
1075             MDC.put(SERVICE_INSTANCE_ID, msoRequest.getServiceInstanceId());
1076         } else {
1077             MDC.put(REQUEST_ID, DUMMY_VALUE);
1078             MDC.put(SERVICE_INSTANCE_ID, DUMMY_VALUE);
1079         }
1080     }
1081
1082     private String normalize(String input) {
1083         if (input == null) {
1084             return null;
1085         }
1086         String result = input.replace('|', '!');
1087         result = result.replace("\n", " - ");
1088         return result;
1089     }
1090
1091     private String getNormalizedStackTrace(Throwable t) {
1092         StringWriter sw = new StringWriter();
1093         PrintWriter pw = new PrintWriter(sw);
1094         t.printStackTrace(pw);
1095         return sw.toString().replace('|', '!').replace("\n", " - ");
1096     }
1097
1098     private void setDefaultLogCatalog(MsoLogger.Catalog cat) {
1099         if ("APIH".equals(cat.toString())) {
1100             exceptionArg = MessageEnum.APIH_GENERAL_EXCEPTION_ARG;
1101             defaultException = MessageEnum.APIH_GENERAL_EXCEPTION;
1102             defaultWarning = MessageEnum.APIH_GENERAL_WARNING;
1103             defaultAudit = MessageEnum.APIH_AUDIT_EXEC;
1104             defaultMetrics = MessageEnum.APIH_GENERAL_METRICS;
1105         } else if ("RA".equals(cat.toString())) {
1106             exceptionArg = MessageEnum.RA_GENERAL_EXCEPTION_ARG;
1107             defaultException = MessageEnum.RA_GENERAL_EXCEPTION;
1108             defaultWarning = MessageEnum.RA_GENERAL_WARNING;
1109             defaultAudit = MessageEnum.RA_AUDIT_EXEC;
1110             defaultMetrics = MessageEnum.RA_GENERAL_METRICS;
1111         } else if ("BPEL".equals(cat.toString())) {
1112             exceptionArg = MessageEnum.BPMN_GENERAL_EXCEPTION_ARG;
1113             defaultException = MessageEnum.BPMN_GENERAL_EXCEPTION;
1114             defaultWarning = MessageEnum.BPMN_GENERAL_WARNING;
1115             defaultAudit = MessageEnum.BPMN_AUDIT_EXEC;
1116             defaultMetrics = MessageEnum.BPMN_GENERAL_METRICS;
1117         } else if ("ASDC".equals(cat.toString())) {
1118             exceptionArg = MessageEnum.ASDC_GENERAL_EXCEPTION_ARG;
1119             defaultException = MessageEnum.ASDC_GENERAL_EXCEPTION;
1120             defaultWarning = MessageEnum.ASDC_GENERAL_WARNING;
1121             defaultAudit = MessageEnum.ASDC_AUDIT_EXEC;
1122             defaultMetrics = MessageEnum.ASDC_GENERAL_METRICS;
1123         } else {
1124             exceptionArg = MessageEnum.GENERAL_EXCEPTION_ARG;
1125             defaultException = MessageEnum.GENERAL_EXCEPTION;
1126             defaultWarning = MessageEnum.GENERAL_WARNING;
1127             defaultAudit = MessageEnum.AUDIT_EXEC;
1128             defaultMetrics = MessageEnum.GENERAL_METRICS;
1129         }
1130     }
1131 }