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