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