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