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