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