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