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