dbbb33e0d8ac4b2a31ad022ab78c3b00bc67d808
[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         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         ErrorCode(int value) {
134             this.value = value;
135         }
136     };
137
138     private EELFLogger          logger, 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
148     // Since four adaptors are using the instance of  MsoLogger which will be referenced everywhere
149     // hence limiting the number of MsoLogger instances to five.
150     private static final MsoLogger generalMsoLogger = new MsoLogger(Catalog.GENERAL);
151     private static final MsoLogger apihLogger = new MsoLogger(Catalog.APIH);
152     private static final MsoLogger asdcLogger = new MsoLogger(Catalog.ASDC);
153     private static final MsoLogger raLogger = new MsoLogger(Catalog.RA);
154     private static final MsoLogger bpelLogger = new MsoLogger(Catalog.BPEL);
155
156     static {
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     // Singleton instances of the EELFLogger of all types are referenced by MsoLogger
175     private MsoLogger(Catalog cat) {
176         this.logger = EELFManager.getInstance().getErrorLogger();
177         this.auditLogger = EELFManager.getInstance().getAuditLogger();
178         this.metricsLogger = EELFManager.getInstance().getMetricsLogger();
179         this.setDefaultLogCatalog(cat);
180     }
181
182
183
184     /**
185      * Get the MsoLogger based on the catalog
186      * This method is fixed now to resolve the total number of objects that are getting created
187      * everytime this function gets called. Its supposed to have fixed number of instance per java process.
188      *
189      * @param cat
190      *            Catalog of the logger
191      * @return the MsoLogger
192      */
193     public static synchronized MsoLogger getMsoLogger(MsoLogger.Catalog cat) {
194         switch (cat) {
195             case GENERAL:
196                 return generalMsoLogger;
197             case APIH:
198                 return apihLogger;
199             case RA:
200                 return raLogger;
201             case BPEL:
202                 return bpelLogger;
203             case ASDC:
204                 return asdcLogger;
205             default:
206                 return generalMsoLogger;
207         }
208     }
209
210     /**
211      * Record the Metrics event with no argument
212      * 
213      * @param startTime
214      *            Transaction starting time in millieseconds
215      * @param statusCode
216      *            StatusCode of the transaction, either COMPLETE or ERROR
217      * @param responseCode
218      *            The response code returned by the sub-components
219      * @param responseDesc
220      *            Human redable description of the response code
221      * @param targetEntity
222      *            The component which is invoked for this sub-operation
223      * @param targetServiceName
224      *            API invoked on the TargetEntity
225      * @param targetVEntity
226      *            Target VNF or VM acted opon by the component, if available
227      */
228     public void recordMetricEvent(Long startTime, StatusCode statusCode, ResponseCode responseCode, String responseDesc,
229             String targetEntity, String targetServiceName, String targetVEntity) {
230         prepareMetricMsg(startTime, statusCode, responseCode.getValue(), responseDesc, targetEntity, targetServiceName,
231                 targetVEntity);
232         metricsLogger.info("");
233         MDC.remove(TIMER);
234         MDC.remove(TARGETENTITY);
235         MDC.remove(TARGETSERVICENAME);
236     }
237
238     /**
239      * Record the Audit event
240      *
241      * @param startTime
242      *            Transaction starting time in millieseconds
243      * @param statusCode
244      *            StatusCode of the transaction, either COMPLETE or ERROR
245      * @param responseCode
246      *            The application specific response code
247      * @param responseDesc
248      *            Human redable description of the application response code
249      */
250     public void recordAuditEvent(Long startTime, StatusCode statusCode, ResponseCode responseCode,
251             String responseDesc) {
252         prepareAuditMsg(startTime, statusCode, responseCode.getValue(), responseDesc);
253         auditLogger.info("");
254         MDC.remove(TIMER);
255     }
256
257     // Debug methods
258     /**
259      * Record the Debug event
260      *
261      * @param msg
262      *            The log message to put
263      */
264     public void debug(String msg) {
265         prepareMsg(DEBUG_LEVEL);
266         logger.debug(msg);
267     }
268
269     /**
270      * Record the Debug event
271      *
272      * @param msg
273      *            The log message to put
274      * @param t
275      *            The exception to put
276      */
277     public void debug(String msg, Throwable t) {
278         prepareMsg(DEBUG_LEVEL);
279         logger.debug(msg, t);
280     }
281
282     // Info methods
283     /**
284      * Record the Info event
285      *
286      * @param msg
287      *            The log message to put
288      */
289     public void info(EELFResolvableErrorEnum msg, String targetEntity, String targetServiceName) {
290         prepareErrorMsg(INFO_LEVEL, targetEntity, targetServiceName, null, "");
291
292         logger.info(msg);
293         MDC.remove(TARGETENTITY);
294         MDC.remove(TARGETSERVICENAME);
295     }
296
297     /**
298      * Record the Info event with 1 argument
299      *
300      * @param msg
301      *            The log message to put
302      * @param arg0
303      *            The argument used in the log message
304      */
305     public void info(EELFResolvableErrorEnum msg, String arg0, String targetEntity, String targetServiceName) {
306         prepareErrorMsg(INFO_LEVEL, targetEntity, targetServiceName, null, "");
307
308         logger.info(msg, normalize(arg0));
309         MDC.remove(TARGETENTITY);
310         MDC.remove(TARGETSERVICENAME);
311     }
312
313     /**
314      * Record the Info event with 2 arguments
315      *
316      * @param msg
317      *            The log message to put
318      * @param arg0,arg1
319      *            The arguments used in the log message
320      */
321     public void info(EELFResolvableErrorEnum msg, String arg0, String arg1, String targetEntity,
322             String targetServiceName) {
323         prepareErrorMsg(INFO_LEVEL, targetEntity, targetServiceName, null, "");
324
325         logger.info(msg, normalize(arg0), normalize(arg1));
326         MDC.remove(TARGETENTITY);
327         MDC.remove(TARGETSERVICENAME);
328     }
329
330     /**
331      * Record the Info event with 3 arguments
332      *
333      * @param msg
334      *            The log message to put
335      * @param arg0,arg1,arg2
336      *            The arguments used in the log message
337      */
338     public void info(EELFResolvableErrorEnum msg, String arg0, String arg1, String arg2, String targetEntity,
339             String targetServiceName) {
340         prepareErrorMsg(INFO_LEVEL, targetEntity, targetServiceName, null, "");
341
342         logger.info(msg, normalize(arg0), normalize(arg1), normalize(arg2));
343         MDC.remove(TARGETENTITY);
344         MDC.remove(TARGETSERVICENAME);
345     }
346
347     /**
348      * Record the Info event with 4 arguments
349      *
350      * @param msg
351      *            The log message to put
352      * @param arg0,arg1,arg2,arg3
353      *            The arguments used in the log message
354      */
355     public void info(EELFResolvableErrorEnum msg, String arg0, String arg1, String arg2, String arg3,
356             String targetEntity, String targetServiceName) {
357         prepareErrorMsg(INFO_LEVEL, targetEntity, targetServiceName, null, "");
358
359         logger.info(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3));
360         MDC.remove(TARGETENTITY);
361         MDC.remove(TARGETSERVICENAME);
362     }
363
364     /**
365      * Record the Info event with 5 arguments
366      *
367      * @param msg
368      *            The log message to put
369      * @param arg0,arg1,arg2,arg3,arg4
370      *            The arguments used in the log message
371      */
372     public void info(EELFResolvableErrorEnum msg, String arg0, String arg1, String arg2, String arg3, String arg4,
373             String targetEntity, String targetServiceName) {
374         prepareErrorMsg(INFO_LEVEL, targetEntity, targetServiceName, null, "");
375
376         logger.info(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3), normalize(arg4));
377         MDC.remove(TARGETENTITY);
378         MDC.remove(TARGETSERVICENAME);
379     }
380
381     /**
382      * Record the Info event with 6 arguments
383      *
384      * @param msg
385      *            The log message to put
386      * @param arg0,arg1,arg2,arg3,arg4,arg5
387      *            The arguments used in the log message
388      */
389     public void info(EELFResolvableErrorEnum msg, String arg0, String arg1, String arg2, String arg3, String arg4,
390             String arg5, String targetEntity, String targetServiceName) {
391         prepareErrorMsg(INFO_LEVEL, targetEntity, targetServiceName, null, "");
392
393         logger.info(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3), normalize(arg4),
394                 normalize(arg5));
395         MDC.remove(TARGETENTITY);
396         MDC.remove(TARGETSERVICENAME);
397     }
398
399     // Warning methods
400     /**
401      * Record the Warning event
402      *
403      * @param msg
404      *            The log message to put
405      */
406     public void warn(EELFResolvableErrorEnum msg, String targetEntity, String targetServiceName, ErrorCode errorCode,
407             String errorDesc) {
408         prepareErrorMsg(WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc);
409
410         logger.warn(msg);
411         MDC.remove(TARGETENTITY);
412         MDC.remove(TARGETSERVICENAME);
413     }
414
415     /**
416      * Record the Warning event
417      *
418      * @param msg
419      *            The log message to put
420      * @param t
421      *            The exception info
422      */
423     public void warn(EELFResolvableErrorEnum msg, String targetEntity, String targetServiceName, ErrorCode errorCode,
424             String errorDesc, Throwable t) {
425         prepareErrorMsg(WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc);
426         logger.warn(msg);
427         logger.warn("Exception raised: " + getNormalizedStackTrace(t));
428         logger.debug("Exception raised", t);
429         MDC.remove(TARGETENTITY);
430         MDC.remove(TARGETSERVICENAME);
431     }
432
433     /**
434      * Record the Warn event with 1 argument
435      *
436      * @param msg
437      *            The log message to put
438      * @param arg
439      *            The argument used in the log message
440      */
441     public void warn(EELFResolvableErrorEnum msg, String arg, String targetEntity, String targetServiceName,
442             ErrorCode errorCode, String errorDesc) {
443         prepareErrorMsg(WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc);
444         logger.warn(msg, arg);
445         MDC.remove(TARGETENTITY);
446         MDC.remove(TARGETSERVICENAME);
447     }
448
449     /**
450      * Record the Warn event with 1 argument
451      *
452      * @param msg
453      *            The log message to put
454      * @param arg
455      *            The arguments used in the log message
456      * @param t
457      *            The exception info
458      */
459     public void warn(EELFResolvableErrorEnum msg, String arg, String targetEntity, String targetServiceName,
460             ErrorCode errorCode, String errorDesc, Throwable t) {
461         prepareErrorMsg(WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc);
462         logger.warn(msg, arg);
463         logger.warn("Exception raised: " + getNormalizedStackTrace(t));
464         logger.debug("Exception raised", t);
465         MDC.remove(TARGETENTITY);
466         MDC.remove(TARGETSERVICENAME);
467     }
468
469     /**
470      * Record the Warn event with 2 arguments
471      *
472      * @param msg
473      *            The log message to put
474      * @param arg0,arg1
475      *            The arguments used in the log message
476      */
477     public void warn(EELFResolvableErrorEnum msg, String arg0, String arg1, String targetEntity,
478             String targetServiceName, ErrorCode errorCode, String errorDesc) {
479         prepareErrorMsg(WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc);
480         logger.warn(msg, normalize(arg0), normalize(arg1));
481         MDC.remove(TARGETENTITY);
482         MDC.remove(TARGETSERVICENAME);
483     }
484
485     /**
486      * Record the Warn event with 2 arguments
487      *
488      * @param msg
489      *            The log message to put
490      * @param arg0,arg1
491      *            The arguments used in the log message
492      * @param t
493      *            The exception info
494      */
495     public void warn(EELFResolvableErrorEnum msg, String arg0, String arg1, String targetEntity,
496             String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) {
497         prepareErrorMsg(WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc);
498         logger.warn(msg, normalize(arg0), normalize(arg1));
499         logger.warn("Exception raised: " + getNormalizedStackTrace(t));
500         logger.debug("Exception raised", t);
501         MDC.remove(TARGETENTITY);
502         MDC.remove(TARGETSERVICENAME);
503     }
504
505     /**
506      * Record the Warn event with 3 arguments
507      *
508      * @param msg
509      *            The log message to put
510      * @param arg0,arg1,arg2
511      *            The arguments used in the log message
512      */
513     public void warn(EELFResolvableErrorEnum msg, String arg0, String arg1, String arg2, String targetEntity,
514             String targetServiceName, ErrorCode errorCode, String errorDesc) {
515         prepareErrorMsg(WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc);
516         logger.warn(msg, normalize(arg0), normalize(arg1), normalize(arg2));
517         MDC.remove(TARGETENTITY);
518         MDC.remove(TARGETSERVICENAME);
519     }
520
521     /**
522      * Record the Warn event with 3 arguments
523      *
524      * @param msg
525      *            The log message to put
526      * @param arg0,arg1,arg2
527      *            The arguments used in the log message
528      * @param t
529      *            The exception info
530      */
531     public void warn(EELFResolvableErrorEnum msg, String arg0, String arg1, String arg2, String targetEntity,
532             String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) {
533         prepareErrorMsg(WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc);
534         logger.warn(msg, normalize(arg0), normalize(arg1), normalize(arg2));
535         logger.warn("Exception raised: " + getNormalizedStackTrace(t));
536         logger.debug("Exception raised", t);
537         MDC.remove(TARGETENTITY);
538         MDC.remove(TARGETSERVICENAME);
539     }
540
541     /**
542      * Record the Warn event with 4 arguments
543      *
544      * @param msg
545      *            The log message to put
546      * @param arg0,arg1,arg2,arg3
547      *            The arguments used in the log message
548      */
549     public void warn(EELFResolvableErrorEnum msg, String arg0, String arg1, String arg2, String arg3,
550             String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc) {
551         prepareErrorMsg(WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc);
552         logger.warn(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3));
553         MDC.remove(TARGETENTITY);
554         MDC.remove(TARGETSERVICENAME);
555     }
556
557     /**
558      * Record the Warn event with 4 arguments
559      *
560      * @param msg
561      *            The log message to put
562      * @param arg0,arg1,arg2,
563      *            arg3 The arguments used in the log message
564      * @param t
565      *            The exception info
566      */
567     public void warn(EELFResolvableErrorEnum msg, String arg0, String arg1, String arg2, String arg3,
568             String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) {
569         prepareErrorMsg(WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc);
570         logger.warn(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3));
571         logger.warn("Exception raised: " + getNormalizedStackTrace(t));
572         logger.debug("Exception raised", t);
573         MDC.remove(TARGETENTITY);
574         MDC.remove(TARGETSERVICENAME);
575     }
576
577     /**
578      * Record the Warn event with 5 arguments
579      *
580      * @param msg
581      *            The log message to put
582      * @param arg0,arg1,arg2,arg3,arg4
583      *            The arguments used in the log message
584      */
585     public void warn(EELFResolvableErrorEnum msg, String arg0, String arg1, String arg2, String arg3, String arg4,
586             String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc) {
587         prepareErrorMsg(WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc);
588         logger.warn(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3), normalize(arg4));
589         MDC.remove(TARGETENTITY);
590         MDC.remove(TARGETSERVICENAME);
591     }
592
593     /**
594      * Record the Warn event with 5 arguments
595      *
596      * @param msg
597      *            The log message to put
598      * @param arg0,arg1,arg2,arg3,arg4
599      *            The arguments used in the log message
600      * @param t
601      *            The exception info
602      */
603     public void warn(EELFResolvableErrorEnum msg, String arg0, String arg1, String arg2, String arg3, String arg4,
604             String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) {
605         prepareErrorMsg(WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc);
606         logger.warn(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3), normalize(arg4));
607         logger.warn("Exception raised: " + getNormalizedStackTrace(t));
608         logger.debug("Exception raised", t);
609         MDC.remove(TARGETENTITY);
610         MDC.remove(TARGETSERVICENAME);
611     }
612
613     // Error methods
614     /**
615      * Record the Error event
616      *
617      * @param msg
618      *            The log message to put
619      */
620     public void error(EELFResolvableErrorEnum msg, String targetEntity, String targetServiceName, ErrorCode errorCode,
621             String errorDesc) {
622         prepareErrorMsg(ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc);
623         logger.error(msg);
624         MDC.remove(TARGETENTITY);
625         MDC.remove(TARGETSERVICENAME);
626     }
627
628     /**
629      * Record the Error event
630      *
631      * @param msg
632      *            The log message to put
633      * @param t
634      *            The exception info
635      */
636     public void error(EELFResolvableErrorEnum msg, String targetEntity, String targetServiceName, ErrorCode errorCode,
637             String errorDesc, Throwable t) {
638         prepareErrorMsg(ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc);
639         logger.error(msg);
640         logger.error(exceptionArg, getNormalizedStackTrace(t));
641         logger.debug("Exception raised", t);
642         MDC.remove(TARGETENTITY);
643         MDC.remove(TARGETSERVICENAME);
644     }
645
646     /**
647      * Record the Error event with 1 argument
648      *
649      * @param msg
650      *            The log message to put
651      * @param arg0
652      *            The arguments used in the log message
653      */
654     public void error(EELFResolvableErrorEnum msg, String arg0, String targetEntity, String targetServiceName,
655             ErrorCode errorCode, String errorDesc) {
656         prepareErrorMsg(ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc);
657         logger.error(msg, normalize(arg0));
658         MDC.remove(TARGETENTITY);
659         MDC.remove(TARGETSERVICENAME);
660     }
661
662     /**
663      * Record the Error event with 1 argument
664      *
665      * @param msg
666      *            The log message to put
667      * @param arg0
668      *            The arguments used in the log message
669      * @param t
670      *            The exception info
671      */
672     public void error(EELFResolvableErrorEnum msg, String arg0, String targetEntity, String targetServiceName,
673             ErrorCode errorCode, String errorDesc, Throwable t) {
674         prepareErrorMsg(ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc);
675         logger.error(msg, normalize(arg0));
676         logger.error(exceptionArg, getNormalizedStackTrace(t));
677         logger.debug("Exception raised", t);
678         MDC.remove(TARGETENTITY);
679         MDC.remove(TARGETSERVICENAME);
680     }
681
682     /**
683      * Record the Error event with 2 arguments
684      *
685      * @param msg
686      *            The log message to put
687      * @param arg0,arg1
688      *            The arguments used in the log message
689      */
690     public void error(EELFResolvableErrorEnum msg, String arg0, String arg1, String targetEntity,
691             String targetServiceName, ErrorCode errorCode, String errorDesc) {
692         prepareErrorMsg(ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc);
693         logger.error(msg, normalize(arg0), normalize(arg1));
694         MDC.remove(TARGETENTITY);
695         MDC.remove(TARGETSERVICENAME);
696     }
697
698     /**
699      * Record the Error event with 2 arguments
700      *
701      * @param msg
702      *            The log message to put
703      * @param arg0,arg1
704      *            The arguments used in the log message
705      * @param t
706      *            The exception info
707      */
708     public void error(EELFResolvableErrorEnum msg, String arg0, String arg1, String targetEntity,
709             String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) {
710         prepareErrorMsg(ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc);
711         logger.error(msg, normalize(arg0), normalize(arg1));
712         logger.error(exceptionArg, getNormalizedStackTrace(t));
713         logger.debug("Exception raised", t);
714         MDC.remove(TARGETENTITY);
715         MDC.remove(TARGETSERVICENAME);
716     }
717
718     /**
719      * Record the Error event with 3 arguments
720      *
721      * @param msg
722      *            The log message to put
723      * @param arg0,arg1,arg2
724      *            The arguments used in the log message
725      */
726     public void error(EELFResolvableErrorEnum msg, String arg0, String arg1, String arg2, String targetEntity,
727             String targetServiceName, ErrorCode errorCode, String errorDesc) {
728         prepareErrorMsg(ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc);
729         logger.error(msg, normalize(arg0), normalize(arg1), normalize(arg2));
730         MDC.remove(TARGETENTITY);
731         MDC.remove(TARGETSERVICENAME);
732     }
733
734     /**
735      * Record the Error event with 3 arguments
736      *
737      * @param msg
738      *            The log message to put
739      * @param arg0,arg1,arg2
740      *            The arguments used in the log message
741      * @param t
742      *            The exception info
743      */
744     public void error(EELFResolvableErrorEnum msg, String arg0, String arg1, String arg2, String targetEntity,
745             String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) {
746         prepareErrorMsg(ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc);
747         logger.error(msg, normalize(arg0), normalize(arg1), normalize(arg2));
748         logger.error(exceptionArg, getNormalizedStackTrace(t));
749         logger.debug("Exception raised", t);
750         MDC.remove(TARGETENTITY);
751         MDC.remove(TARGETSERVICENAME);
752     }
753
754     /**
755      * Record the Error event with 4 arguments
756      *
757      * @param msg
758      *            The log message to put
759      * @param arg0,arg1,arg2,arg3
760      *            The arguments used in the log message
761      */
762     public void error(EELFResolvableErrorEnum msg, String arg0, String arg1, String arg2, String arg3,
763             String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc) {
764         prepareErrorMsg(ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc);
765         logger.error(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3));
766         MDC.remove(TARGETENTITY);
767         MDC.remove(TARGETSERVICENAME);
768     }
769
770     /**
771      * Record the Error event with 4 arguments
772      *
773      * @param msg
774      *            The log message to put
775      * @param arg0,arg1,arg2,arg3
776      *            The arguments used in the log message
777      * @param t
778      *            The exception info
779      */
780     public void error(EELFResolvableErrorEnum msg, String arg0, String arg1, String arg2, String arg3,
781             String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) {
782         prepareErrorMsg(ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc);
783         logger.error(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3));
784         logger.error(exceptionArg, getNormalizedStackTrace(t));
785         logger.debug("Exception raised", t);
786         MDC.remove(TARGETENTITY);
787         MDC.remove(TARGETSERVICENAME);
788     }
789
790     /**
791      * Record the Error event with 5 arguments
792      *
793      * @param msg
794      *            The log message to put
795      * @param arg0,arg1,arg2,arg3,arg4
796      *            The arguments used in the log message
797      */
798     public void error(EELFResolvableErrorEnum msg, String arg0, String arg1, String arg2, String arg3, String arg4,
799             String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc) {
800         prepareErrorMsg(ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc);
801         logger.error(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3), normalize(arg4));
802         MDC.remove(TARGETENTITY);
803         MDC.remove(TARGETSERVICENAME);
804     }
805
806     /**
807      * Record the Error event with 5 arguments
808      *
809      * @param msg
810      *            The log message to put
811      * @param arg0,arg1,arg2,arg3,arg4
812      *            The arguments used in the log message
813      * @param t
814      *            The exception info
815      */
816     public void error(EELFResolvableErrorEnum msg, String arg0, String arg1, String arg2, String arg3, String arg4,
817             String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) {
818         prepareErrorMsg(ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc);
819         logger.error(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3), normalize(arg4));
820         logger.error(exceptionArg, getNormalizedStackTrace(t));
821         logger.debug("Exception raised", t);
822         MDC.remove(TARGETENTITY);
823         MDC.remove(TARGETSERVICENAME);
824     }
825
826     public boolean isDebugEnabled() {
827         return logger.isDebugEnabled();
828     }
829
830     private void prepareMsg(String loggingLevel) {
831         prepareMsg(loggingLevel, null, null);
832     }
833
834     private void prepareMsg(String loggingLevel, String serviceNamep, String timer) {
835         String reqId = MDC.get(REQUEST_ID);
836         String svcId = MDC.get(SERVICE_INSTANCE_ID);
837
838         // Based on the discussion with Adrian,
839         // if these 2 parameters is not available, using dummy value "trace-#"
840         if (reqId == null || reqId.isEmpty()) {
841             MDC.put(REQUEST_ID, DUMMY_VALUE);
842         }
843
844         if (svcId == null || svcId.isEmpty()) {
845             MDC.put(SERVICE_INSTANCE_ID, DUMMY_VALUE);
846         }
847
848         if (timer != null) {
849             MDC.put(TIMER, timer);
850         } else {
851             MDC.remove(TIMER);
852         }
853
854         MDC.put(SERVICE_NAME, getFinalServiceName(serviceNamep));
855         MDC.put(ALERT_SEVERITY, getSeverityLevel(loggingLevel));
856         MDC.put(INSTANCE_UUID, instanceUUID);
857         MDC.put(SERVER_IP, serverIP);
858         MDC.put(FQDN, serverName);
859     }
860
861     private void prepareAuditMsg(long startTime, StatusCode statusCode, int responseCode, String responseDesc) {
862         long endTime = System.currentTimeMillis();
863         prepareMsg(INFO_LEVEL, null, String.valueOf(endTime - startTime));
864         prepareAuditMetricMsg(startTime, endTime, statusCode, responseCode, responseDesc);
865     }
866
867     private void prepareAuditMetricMsg(long startTime, long endTime, StatusCode statusCode, int responseCode,
868             String responseDesc) {
869         Date startDate = new Date(startTime);
870         Date endDate = new Date(endTime);
871         DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
872
873         MDC.put(BEGINTIME, String.valueOf(formatter.format(startDate)));
874         MDC.put(ENDTIME, String.valueOf(formatter.format(endDate)));
875         MDC.put(STATUSCODE, statusCode.name());
876         MDC.put(RESPONSECODE, String.valueOf(responseCode));
877         MDC.put(RESPONSEDESC, responseDesc);
878     }
879
880     private void prepareErrorMsg(String loggingLevel, String targetEntity, String targetServiceName,
881             ErrorCode errorCode, String errorDesc) {
882         MDC.put(ALERT_SEVERITY, getSeverityLevel(loggingLevel));
883         MDC.put(ERRORCODE, String.valueOf(errorCode));
884         MDC.put(ERRORDESC, errorDesc);
885         MDC.put(TARGETENTITY, targetEntity);
886         MDC.put(TARGETSERVICENAME, targetServiceName);
887         MDC.put(SERVICE_NAME, getFinalServiceName(getServiceName()));
888     }
889
890     private void prepareMetricMsg(long startTime, StatusCode statusCode, int responseCode, String responseDesc,
891             String targetEntity, String targetServiceName, String targetVEntity) {
892         long endTime = System.currentTimeMillis();
893         prepareMsg(INFO_LEVEL, null, String.valueOf(endTime - startTime));
894         prepareAuditMetricMsg(startTime, endTime, statusCode, responseCode, responseDesc);
895
896         // Populate Metric log specific parameter
897         MDC.put(TARGETENTITY, targetEntity);
898         MDC.put(TARGETSERVICENAME, targetServiceName);
899
900         if (null != targetVEntity) {
901             MDC.put(TARGETVIRTUALENTITY, targetVEntity);
902         }
903     }
904
905     private String getSeverityLevel(String loggingLevel) {
906         String severity;
907         // According to the Nagios alerting: 0=OK; 1=WARNING; 2=UNKOWN;
908         // 3=CRITICAL
909         switch (loggingLevel) {
910             case ERROR_LEVEL:
911                 severity = "2";
912                 break;
913             case FATAL_LEVEL:
914                 severity = "3";
915                 break;
916             case WARN_LEVEL:
917                 severity = "1";
918                 break;
919             default:
920                 severity = "0";
921                 break;
922         }
923         return severity;
924     }
925
926     private String getFinalServiceName(String serviceNamep) {
927         // This step to set the serviceName should be put after the className is
928         // get,
929         // since the default serviceName is obtained during the method to get
930         // the className.
931         //
932         // There's 3 ways to set the serviceName. The first method has the most
933         // priority to set the value.
934         // a) If the serviceName is set within the log method, this value will
935         // be used first
936         // b) If serviceName is not set within the log method, the value defined
937         // in the MDC will be used
938         // c) If nothing is set specifically, then MsoLogger will assign a
939         // default(MSO.<method_name>) value to it
940         String serName = MDC.get(MsoLogger.SERVICE_NAME);
941
942         // Check if service name was already set as the method name by a
943         // previous call to this method.
944         String isMethodNameStr = MDC.get(MsoLogger.SERVICE_NAME_IS_METHOD_NAME);
945         boolean isMethodName = isMethodNameStr != null && isMethodNameStr.equals(Boolean.TRUE.toString());
946         if (serviceNamep != null) {
947             return serviceNamep;
948         } else if (serName != null && !isMethodName) {
949             return serName;
950         }
951
952         MDC.put(MsoLogger.SERVICE_NAME_IS_METHOD_NAME, Boolean.TRUE.toString());
953         int limit;
954         StackTraceElement[] classArr = new Exception().getStackTrace();
955         if (classArr.length >= 6) {
956             limit = 7;
957         } else {
958             limit = classArr.length;
959         }
960         for (int i = 1; i < limit; i++) {
961             String className = classArr[i].getClassName();
962             if (!className.equals(this.getClass().getName())) {
963                 return classArr[i].getMethodName();
964             }
965         }
966         return classArr[0].getMethodName();
967     }
968
969     // Based on the discussion with Adrian, instanceUUID is used to identifiy
970     // the mso instance,
971     // it is generated during mso instance initialization period
972     // The same mso instnace will use the same instanceUUID value, even after
973     // restart
974     private static String getInstanceUUID() {
975         // Avoid creation during build and tests
976         if (System.getProperty("jboss.server.name") == null) {
977             return "Test UUID as JBoss not found";
978         }
979         File configFile = new File(CONFIG_FILE);
980         String uuid = "";
981         BufferedReader in = null;
982         BufferedWriter bw = null;
983         try {
984             // Verify whether instanceUUID file exist,
985             // If yes, read the content; if not, generate the instanceUUID and
986             // write to the file
987             if (configFile.exists()) {
988                 // read the content of the file
989                 in = new BufferedReader(new FileReader(CONFIG_FILE));
990                 if ((uuid = in.readLine()) == null) {
991                     // the file is empty, regenerate the file
992                     uuid = UUID.randomUUID().toString();
993                     FileWriter fw = new FileWriter(configFile.getAbsoluteFile());
994                     bw = new BufferedWriter(fw);
995                     bw.write(uuid);
996                     bw.close();
997                 }
998                 in.close();
999             } else {
1000                 // file doesn't exist yet -> create the file and generate the
1001                 // instanceUUID
1002                 uuid = UUID.randomUUID().toString();
1003                 configFile.getParentFile().mkdirs();
1004                 configFile.createNewFile();
1005                 FileWriter fw = new FileWriter(configFile.getAbsoluteFile());
1006                 bw = new BufferedWriter(fw);
1007                 bw.write(uuid);
1008                 bw.close();
1009             }
1010         } catch (IOException e) {
1011             LOGGER.log(Level.SEVERE, "Error trying to read UUID file", e);
1012         } finally {
1013             try {
1014                 if (in != null) {
1015                     in.close();
1016                 }
1017                 if (bw != null) {
1018                     bw.close();
1019                 }
1020             } catch (IOException ex) {
1021                 LOGGER.log(Level.SEVERE, "Error trying to close UUID file", ex);
1022             }
1023         }
1024         return uuid;
1025     }
1026
1027     /**
1028      * Set the requestId and serviceInstanceId
1029      * 
1030      * @param reqId
1031      *            The requestId
1032      * @param svcId
1033      *            The serviceInstanceId
1034      */
1035     public static void setLogContext(String reqId, String svcId) {
1036         if (null != reqId) {
1037             MDC.put(REQUEST_ID, reqId);
1038         }
1039
1040         if (null != svcId) {
1041             MDC.put(SERVICE_INSTANCE_ID, svcId);
1042         }
1043     }
1044
1045     /**
1046      * Set the remoteIp and the basic HTTP Authentication user
1047      * 
1048      * @param remoteIpp
1049      *            The remote ip address
1050      * @param userp
1051      *            The basic http authencitation user
1052      */
1053     public static void setLoggerParameters(String remoteIpp, String userp) {
1054         if (null != remoteIpp) {
1055             MDC.put(REMOTE_HOST, remoteIpp);
1056         }
1057         if (null != userp) {
1058             MDC.put(USER, userp);
1059         }
1060     }
1061
1062     /**
1063      * Set the serviceName
1064      * 
1065      * @param serviceNamep
1066      *            The service name
1067      */
1068     public static void setServiceName(String serviceNamep) {
1069         if (null != serviceNamep) {
1070             MDC.put(SERVICE_NAME, serviceNamep);
1071             MDC.remove(SERVICE_NAME_IS_METHOD_NAME);
1072         }
1073     }
1074
1075     /**
1076      * Get the serviceName
1077      * 
1078      * @return The service name
1079      */
1080     public static String getServiceName() {
1081         return MDC.get(SERVICE_NAME);
1082     }
1083
1084     /**
1085      * Reset the serviceName
1086      */
1087     public static void resetServiceName() {
1088         MDC.remove(SERVICE_NAME);
1089     }
1090
1091     /**
1092      * Set the requestId and serviceInstanceId based on the mso request
1093      * 
1094      * @param msoRequest
1095      *            The mso request
1096      */
1097     public static void setLogContext(MsoRequest msoRequest) {
1098         if (msoRequest != null) {
1099             MDC.put(REQUEST_ID, msoRequest.getRequestId());
1100             MDC.put(SERVICE_INSTANCE_ID, msoRequest.getServiceInstanceId());
1101         } else {
1102             MDC.put(REQUEST_ID, DUMMY_VALUE);
1103             MDC.put(SERVICE_INSTANCE_ID, DUMMY_VALUE);
1104         }
1105     }
1106
1107     private String normalize(String input) {
1108         if (input == null) {
1109             return null;
1110         }
1111         String result = input.replace('|', '!');
1112         result = result.replace("\n", " - ");
1113         return result;
1114     }
1115
1116     private String getNormalizedStackTrace(Throwable t) {
1117         StringWriter sw = new StringWriter();
1118         PrintWriter pw = new PrintWriter(sw);
1119         t.printStackTrace(pw);
1120         return sw.toString().replace('|', '!').replace("\n", " - ");
1121     }
1122
1123     private void setDefaultLogCatalog(MsoLogger.Catalog cat) {
1124         if ("APIH".equals(cat.toString())) {
1125             exceptionArg = MessageEnum.APIH_GENERAL_EXCEPTION_ARG;
1126             defaultException = MessageEnum.APIH_GENERAL_EXCEPTION;
1127             defaultWarning = MessageEnum.APIH_GENERAL_WARNING;
1128             defaultAudit = MessageEnum.APIH_AUDIT_EXEC;
1129             defaultMetrics = MessageEnum.APIH_GENERAL_METRICS;
1130         } else if ("RA".equals(cat.toString())) {
1131             exceptionArg = MessageEnum.RA_GENERAL_EXCEPTION_ARG;
1132             defaultException = MessageEnum.RA_GENERAL_EXCEPTION;
1133             defaultWarning = MessageEnum.RA_GENERAL_WARNING;
1134             defaultAudit = MessageEnum.RA_AUDIT_EXEC;
1135             defaultMetrics = MessageEnum.RA_GENERAL_METRICS;
1136         } else if ("BPEL".equals(cat.toString())) {
1137             exceptionArg = MessageEnum.BPMN_GENERAL_EXCEPTION_ARG;
1138             defaultException = MessageEnum.BPMN_GENERAL_EXCEPTION;
1139             defaultWarning = MessageEnum.BPMN_GENERAL_WARNING;
1140             defaultAudit = MessageEnum.BPMN_AUDIT_EXEC;
1141             defaultMetrics = MessageEnum.BPMN_GENERAL_METRICS;
1142         } else if ("ASDC".equals(cat.toString())) {
1143             exceptionArg = MessageEnum.ASDC_GENERAL_EXCEPTION_ARG;
1144             defaultException = MessageEnum.ASDC_GENERAL_EXCEPTION;
1145             defaultWarning = MessageEnum.ASDC_GENERAL_WARNING;
1146             defaultAudit = MessageEnum.ASDC_AUDIT_EXEC;
1147             defaultMetrics = MessageEnum.ASDC_GENERAL_METRICS;
1148         } else {
1149             exceptionArg = MessageEnum.GENERAL_EXCEPTION_ARG;
1150             defaultException = MessageEnum.GENERAL_EXCEPTION;
1151             defaultWarning = MessageEnum.GENERAL_WARNING;
1152             defaultAudit = MessageEnum.AUDIT_EXEC;
1153             defaultMetrics = MessageEnum.GENERAL_METRICS;
1154         }
1155     }
1156 }