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