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