diff options
author | Pamela Dragosh <pdragosh@research.att.com> | 2018-03-20 14:49:45 +0000 |
---|---|---|
committer | Gerrit Code Review <gerrit@onap.org> | 2018-03-20 14:49:45 +0000 |
commit | ff1b759ff023dc9a940ab9de4333adcac82b9867 (patch) | |
tree | 039e5ae2835874dbcbdf7ba7981b853242c51655 | |
parent | 77ad3209e44b4d749cf45d2c5b2bd9e0214e9c9c (diff) | |
parent | 5492c1dd9d7052781ae5cab28bf5bcc829ae9c9e (diff) |
Merge "Removed checkstyle warnings"
37 files changed, 4848 insertions, 4616 deletions
diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/ONAPLoggingContext.java b/common-logging/src/main/java/org/onap/policy/common/logging/ONAPLoggingContext.java index 883b3a1e..92bc6236 100644 --- a/common-logging/src/main/java/org/onap/policy/common/logging/ONAPLoggingContext.java +++ b/common-logging/src/main/java/org/onap/policy/common/logging/ONAPLoggingContext.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-Logging * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,35 +24,37 @@ import java.text.SimpleDateFormat; import java.time.Duration; import java.time.Instant; import java.util.Date; + import org.onap.policy.common.logging.nsa.LoggingContextFactory; import org.onap.policy.common.logging.nsa.SharedLoggingContext; import org.slf4j.MDC; /** - * A facade over the org.onap.policy.common.logging.nsa.SharedLoggingContext interface/implementation that makes it - * more convenient to use. SharedLoggingContext builds on the SLF4J/log4j Mapped Diagnostic Context (MDC) - * feature, which provides a hashmap-based context for data items that need to be logged, where the - * hashmap is kept in ThreadLocal storage. The data items can be referenced in the log4j configuration - * using the EnhancedPatternLayout appender layout class, and the notation "%X{key}" in the ConversionPattern - * string, where "key" is one of the keys in the MDC hashmap (which is determined by what hashmap entries the - * application code creates). Example: - * log4j.appender.auditAppender.layout=org.apache.log4j.EnhancedPatternLayout - * log4j.appender.auditAppender.layout.ConversionPattern=%d|%X{requestId}|%X{serviceInstanceId}|...|%m%n + * A facade over the org.onap.policy.common.logging.nsa.SharedLoggingContext + * interface/implementation that makes it more convenient to use. SharedLoggingContext builds on the + * SLF4J/log4j Mapped Diagnostic Context (MDC) feature, which provides a hashmap-based context for + * data items that need to be logged, where the hashmap is kept in ThreadLocal storage. The data + * items can be referenced in the log4j configuration using the EnhancedPatternLayout appender + * layout class, and the notation "%X{key}" in the ConversionPattern string, where "key" is one of + * the keys in the MDC hashmap (which is determined by what hashmap entries the application code + * creates). Example: log4j.appender.auditAppender.layout=org.apache.log4j.EnhancedPatternLayout + * log4j.appender.auditAppender.layout.ConversionPattern=%d|%X{requestId}|%X{serviceInstanceId}|...|%m%n * where "requestId" and "serviceInstanceId" are entries in the MDC hashmap. - * - * The notable functionality the SharedLoggingContext adds over MDC is that it maintains its own copy - * of the MDC data items in a hashmap (not in ThreadLocal storage), which allows more control of the data. - * The ONAPLoggingContext constructor that takes another ONAPLoggingContext object as a parameter makes - * use of this feature. For example if there is a thread pulling requests from a queue for processing, it - * can keep a base logging context with data that is common to all requests, and for each request, create a - * new logging context with that base context as a parameter; this will create a new logging context with - * those initial values and none of the request-specific values from the previous request such as a request ID. - - * The setter methods in this class set corresponding items in the SharedLoggingContext/MDC hashmaps. - * These items correspond to the fields defined in the "ONAP platform application logging guidelines" - * document. In addition, there is a pair of convenience functions, transactionStarted() and - * transactionEnded(), that can be called at the beginning and end of transaction processing to calculate - * the duration of the transaction and record that value in the "timer" item. + * + * <p>The notable functionality the SharedLoggingContext adds over MDC is that it maintains its own + * copy of the MDC data items in a hashmap (not in ThreadLocal storage), which allows more control + * of the data. The ONAPLoggingContext constructor that takes another ONAPLoggingContext object as a + * parameter makes use of this feature. For example if there is a thread pulling requests from a + * queue for processing, it can keep a base logging context with data that is common to all + * requests, and for each request, create a new logging context with that base context as a + * parameter; this will create a new logging context with those initial values and none of the + * request-specific values from the previous request such as a request ID. + * + * <p>The setter methods in this class set corresponding items in the SharedLoggingContext/MDC + * hashmaps. These items correspond to the fields defined in the "ONAP platform application logging + * guidelines" document. In addition, there is a pair of convenience functions, transactionStarted() + * and transactionEnded(), that can be called at the beginning and end of transaction processing to + * calculate the duration of the transaction and record that value in the "timer" item. * */ public class ONAPLoggingContext { @@ -101,13 +103,13 @@ public class ONAPLoggingContext { } /** - * Create a new ONAPLoggingContext initially populated with the values - * in the given base context. This can be used for example in a servlet - * where each incoming request may be processed by a separate thread, but - * there may be some logging data items that will be unchanging and common - * to all the threads. That constant data can be populated in a base - * context, and then each request handler creates new context passing that - * base context to populate the common data in the new one. + * Create a new ONAPLoggingContext initially populated with the values in the given base + * context. This can be used for example in a servlet where each incoming request may be + * processed by a separate thread, but there may be some logging data items that will be + * unchanging and common to all the threads. That constant data can be populated in a base + * context, and then each request handler creates new context passing that base context to + * populate the common data in the new one. + * * @param baseContext onap logging context */ public ONAPLoggingContext(ONAPLoggingContext baseContext) { @@ -128,9 +130,8 @@ public class ONAPLoggingContext { } /** - * Indicate the start of transaction processing. The current system time - * will be recorded for use by <code>transactionEnded()</code> to calculate - * the duration of the transaction. + * Indicate the start of transaction processing. The current system time will be recorded for + * use by <code>transactionEnded()</code> to calculate the duration of the transaction. */ public void transactionStarted() { transactionStartTime = Instant.now(); @@ -138,9 +139,9 @@ public class ONAPLoggingContext { } /** - * Indicate the end of transaction processing. The difference between the - * current system time and the time recorded by <code>transactionStarted()</code> - * will be recorded in the data item with key "TransactionElapsedTime". + * Indicate the end of transaction processing. The difference between the current system time + * and the time recorded by <code>transactionStarted()</code> will be recorded in the data item + * with key "TransactionElapsedTime". */ public void transactionEnded() { Instant transactionEndTime = Instant.now(); @@ -149,9 +150,8 @@ public class ONAPLoggingContext { } /** - * Indicate the start of metric processing. The current system time - * will be recorded for use by <code>metricEnded()</code> to calculate - * the duration of the metric. + * Indicate the start of metric processing. The current system time will be recorded for use by + * <code>metricEnded()</code> to calculate the duration of the metric. */ public void metricStarted() { metricStartTime = Instant.now(); @@ -159,9 +159,9 @@ public class ONAPLoggingContext { } /** - * Indicate the end of metric processing. The difference between the - * current system time and the time recorded by <code>metricStarted()</code> - * will be recorded in the data item with key "MetricElapsedTime". + * Indicate the end of metric processing. The difference between the current system time and the + * time recorded by <code>metricStarted()</code> will be recorded in the data item with key + * "MetricElapsedTime". */ public void metricEnded() { Instant metricEndTime = Instant.now(); @@ -170,7 +170,7 @@ public class ONAPLoggingContext { } /** - * Set the value for the data item with key "requestId" + * Set the value for the data item with key "requestId". * * @param id request identifier */ @@ -179,7 +179,8 @@ public class ONAPLoggingContext { } /** - * Get the value for the data item with key "requestId" + * Get the value for the data item with key "requestId". + * * @return current value, or empty string if not set */ public String getRequestID() { @@ -187,7 +188,7 @@ public class ONAPLoggingContext { } /** - * Set the value for the data item with key "serviceInstanceId" + * Set the value for the data item with key "serviceInstanceId". * * @param id service identifier */ @@ -196,7 +197,8 @@ public class ONAPLoggingContext { } /** - * Get the value for the data item with key "serviceInstanceId" + * Get the value for the data item with key "serviceInstanceId". + * * @return current value, or empty string if not set */ public String getServiceInstanceID() { @@ -204,9 +206,8 @@ public class ONAPLoggingContext { } /** - * Set the value for the data item with key "threadId". - * An alternative to using this item is to use the - * %t conversion character in the appender's conversion string. + * Set the value for the data item with key "threadId". An alternative to using this item is to + * use the %t conversion character in the appender's conversion string. * * @param id thread identifier */ @@ -215,7 +216,8 @@ public class ONAPLoggingContext { } /** - * Get the value for the data item with key "threadId" + * Get the value for the data item with key "threadId". + * * @return current value, or empty string if not set */ public String getThreadID() { @@ -223,7 +225,7 @@ public class ONAPLoggingContext { } /** - * Set the value for the data item with key "serverName" + * Set the value for the data item with key "serverName". * * @param name server name */ @@ -232,7 +234,8 @@ public class ONAPLoggingContext { } /** - * Get the value for the data item with key "serverName" + * Get the value for the data item with key "serverName". + * * @return current value, or empty string if not set */ public String getServerName() { @@ -240,7 +243,7 @@ public class ONAPLoggingContext { } /** - * Set the value for the data item with key "serviceName" + * Set the value for the data item with key "serviceName". * * @param name service name */ @@ -249,7 +252,8 @@ public class ONAPLoggingContext { } /** - * Get the value for the data item with key "serviceName" + * Get the value for the data item with key "serviceName". + * * @return current value, or empty string if not set */ public String getServiceName() { @@ -257,7 +261,7 @@ public class ONAPLoggingContext { } /** - * Set the value for the data item with key "partnerName" + * Set the value for the data item with key "partnerName". * * @param name partner name */ @@ -266,7 +270,8 @@ public class ONAPLoggingContext { } /** - * Get the value for the data item with key "partnerName" + * Get the value for the data item with key "partnerName". + * * @return current value, or empty string if not set */ public String getPartnerName() { @@ -274,7 +279,7 @@ public class ONAPLoggingContext { } /** - * Set the value for the data item with key "statusCode" + * Set the value for the data item with key "statusCode". * * @param name status code */ @@ -283,7 +288,8 @@ public class ONAPLoggingContext { } /** - * Get the value for the data item with key "statusCode" + * Get the value for the data item with key "statusCode". + * * @return current value, or empty string if not set */ public String getStatusCode() { @@ -291,7 +297,7 @@ public class ONAPLoggingContext { } /** - * Set the value for the data item with key "targetEntity" + * Set the value for the data item with key "targetEntity". * * @param name target entity */ @@ -300,7 +306,8 @@ public class ONAPLoggingContext { } /** - * Get the value for the data item with key "targetEntity" + * Get the value for the data item with key "targetEntity". + * * @return current value, or empty string if not set */ public String getTargetEntity() { @@ -308,7 +315,7 @@ public class ONAPLoggingContext { } /** - * Set the value for the data item with key "targetServiceName" + * Set the value for the data item with key "targetServiceName". * * @param name target service name */ @@ -317,7 +324,8 @@ public class ONAPLoggingContext { } /** - * Get the value for the data item with key "targetServiceName" + * Get the value for the data item with key "targetServiceName". + * * @return current value, or empty string if not set */ public String getTargetServiceName() { @@ -325,7 +333,7 @@ public class ONAPLoggingContext { } /** - * Set the value for the data item with key "instanceUuid" + * Set the value for the data item with key "instanceUuid". * * @param uuid instance uuid */ @@ -334,7 +342,8 @@ public class ONAPLoggingContext { } /** - * Get the value for the data item with key "instanceUuid" + * Get the value for the data item with key "instanceUuid". + * * @return current value, or empty string if not set */ public String getInstanceUUID() { @@ -342,7 +351,7 @@ public class ONAPLoggingContext { } /** - * Set the value for the data item with key "severity" + * Set the value for the data item with key "severity". * * @param severity severity */ @@ -351,7 +360,8 @@ public class ONAPLoggingContext { } /** - * Get the value for the data item with key "severity" + * Get the value for the data item with key "severity". + * * @return current value, or empty string if not set */ public String getSeverity() { @@ -359,7 +369,7 @@ public class ONAPLoggingContext { } /** - * Set the value for the data item with key "serverIp" + * Set the value for the data item with key "serverIp". * * @param serverIP server ip address */ @@ -368,7 +378,8 @@ public class ONAPLoggingContext { } /** - * Get the value for the data item with key "serverIp" + * Get the value for the data item with key "serverIp". + * * @return current value, or empty string if not set */ public String getServerIPAddress() { @@ -376,7 +387,7 @@ public class ONAPLoggingContext { } /** - * Set the value for the data item with key "server" + * Set the value for the data item with key "server". * * @param server server */ @@ -385,7 +396,8 @@ public class ONAPLoggingContext { } /** - * Get the value for the data item with key "server" + * Get the value for the data item with key "server". + * * @return current value, or empty string if not set */ public String getServer() { @@ -393,7 +405,7 @@ public class ONAPLoggingContext { } /** - * Set the value for the data item with key "clientIp" + * Set the value for the data item with key "clientIp". * * @param clientIP client ip address */ @@ -402,7 +414,8 @@ public class ONAPLoggingContext { } /** - * Get the value for the data item with key "clientIp" + * Get the value for the data item with key "clientIp". + * * @return current value, or empty string if not set */ public String getClientIPAddress() { @@ -410,13 +423,11 @@ public class ONAPLoggingContext { } /** - * Set the value for the data item with key "classname". - * Use of this item is not recommended (unless it is used to - * indicate something other than the Java classname) since - * it would be unwieldy to maintain a correct value across - * calls to/returns from methods in other classes. - * Use of the PatternLayout %c conversion character in the - * conversion string will give a more reliable value. + * Set the value for the data item with key "classname". Use of this item is not recommended + * (unless it is used to indicate something other than the Java classname) since it would be + * unwieldy to maintain a correct value across calls to/returns from methods in other classes. + * Use of the PatternLayout %c conversion character in the conversion string will give a more + * reliable value. * * @param classname class name */ @@ -425,7 +436,8 @@ public class ONAPLoggingContext { } /** - * Get the value for the data item with key "classname" + * Get the value for the data item with key "classname". + * * @return current value, or empty string if not set */ public String getClassname() { @@ -433,7 +445,7 @@ public class ONAPLoggingContext { } /** - * Set the value for the data item with key "TransactionBeginTimestamp" + * Set the value for the data item with key "TransactionBeginTimestamp". * * @param transactionStartTime transaction start time */ @@ -443,7 +455,8 @@ public class ONAPLoggingContext { } /** - * Get the value for the data item with key "TransactionBeginTimestamp" + * Get the value for the data item with key "TransactionBeginTimestamp". + * * @return current value, or 0 if not set */ public long getTransactionBeginTimestamp() { @@ -451,7 +464,7 @@ public class ONAPLoggingContext { } /** - * Set the value for the data item with key "TransactionEndTimestamp" + * Set the value for the data item with key "TransactionEndTimestamp". * * @param transactionEndTime transaction end time */ @@ -461,7 +474,8 @@ public class ONAPLoggingContext { } /** - * Get the value for the data item with key "TransactionEndTimestamp" + * Get the value for the data item with key "TransactionEndTimestamp". + * * @return current value, or 0 if not set */ public long getTransactionEndTimestamp() { @@ -469,12 +483,10 @@ public class ONAPLoggingContext { } /** - * Set the value for the data item with key "TransactionElapsedTime". - * An alternative to calling this method directly is to call - * <code>transactionStarted()</code> at the start of transaction - * processing and <code>transactionEnded()</code> at the end, - * which will compute the time difference in milliseconds - * and store the result as the "ns" value. + * Set the value for the data item with key "TransactionElapsedTime". An alternative to calling + * this method directly is to call <code>transactionStarted()</code> at the start of transaction + * processing and <code>transactionEnded()</code> at the end, which will compute the time + * difference in milliseconds and store the result as the "ns" value. * * @param transactionEndTime transaction end time */ @@ -485,7 +497,8 @@ public class ONAPLoggingContext { } /** - * Get the value for the data item with key "TransactionElapsedTime" + * Get the value for the data item with key "TransactionElapsedTime". + * * @return current value, or 0 if not set */ public long getTransactionElapsedTime() { @@ -493,7 +506,7 @@ public class ONAPLoggingContext { } /** - * Set the value for the data item with key "MetricBeginTimestamp" + * Set the value for the data item with key "MetricBeginTimestamp". * * @param metricStartTime metric start time */ @@ -503,7 +516,8 @@ public class ONAPLoggingContext { } /** - * Get the value for the data item with key "MetricBeginTimestamp" + * Get the value for the data item with key "MetricBeginTimestamp". + * * @return current value, or 0 if not set */ public long getMetricBeginTimestamp() { @@ -511,7 +525,7 @@ public class ONAPLoggingContext { } /** - * Set the value for the data item with key "MetricEndTimestamp" + * Set the value for the data item with key "MetricEndTimestamp". * * @param metricEndTime metric end time */ @@ -521,7 +535,8 @@ public class ONAPLoggingContext { } /** - * Get the value for the data item with key "MetricEndTimestamp" + * Get the value for the data item with key "MetricEndTimestamp". + * * @return current value, or 0 if not set */ public long getMetricEndTimestamp() { @@ -529,11 +544,9 @@ public class ONAPLoggingContext { } /** - * Set the value for the data item with key "MetricElapsedTime". - * An alternative to calling this method directly is to call - * <code>metricStarted()</code> at the start of metric - * processing and <code>metricEnded()</code> at the end, - * which will compute the time difference in milliseconds + * Set the value for the data item with key "MetricElapsedTime". An alternative to calling this + * method directly is to call <code>metricStarted()</code> at the start of metric processing and + * <code>metricEnded()</code> at the end, which will compute the time difference in milliseconds * and store the result as the "ns" value. * * @param metricEndTime metric end time @@ -545,7 +558,8 @@ public class ONAPLoggingContext { } /** - * Get the value for the data item with key "MetricElapsedTime" + * Get the value for the data item with key "MetricElapsedTime". + * * @return current value, or 0 if not set */ public long getMetricElapsedTime() { diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/ONAPLoggingUtils.java b/common-logging/src/main/java/org/onap/policy/common/logging/ONAPLoggingUtils.java index e0778ea3..0983ed6f 100644 --- a/common-logging/src/main/java/org/onap/policy/common/logging/ONAPLoggingUtils.java +++ b/common-logging/src/main/java/org/onap/policy/common/logging/ONAPLoggingUtils.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-Logging * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,33 +24,39 @@ import javax.servlet.http.HttpServletRequest; public class ONAPLoggingUtils { - private ONAPLoggingUtils() {}; - - public static ONAPLoggingContext getLoggingContextForRequest(HttpServletRequest request, - ONAPLoggingContext baseContext) - { - ONAPLoggingContext requestContext = new ONAPLoggingContext(baseContext); - if (request.getLocalAddr() != null) { // may be null in junit tests - requestContext.setServerIPAddress(request.getLocalAddr()); - } - // get client IP address as leftmost address in X-Forwarded-For header if present, - // otherwise from remote address in the request - String forwarded = request.getHeader("X-Forwarded-For"); - if (forwarded != null && forwarded.trim().length() > 0) { - forwarded = forwarded.trim().split(",")[0]; - requestContext.setClientIPAddress(forwarded); - } else if (request.getRemoteAddr() != null) { // may be null in junit tests - requestContext.setClientIPAddress(request.getRemoteAddr()); - } - // RequestID - // This needs to be renamed to ONAP when the other components in ONAP - // rename to this. - String requestId = request.getHeader("X-ECOMP-RequestID"); - if (requestId != null && requestId.trim().length() > 0) { - requestContext.setRequestID(requestId); - } - return requestContext; - } + private ONAPLoggingUtils() {} + + /** + * Get the ONAPLoggingContext for a request. + * + * @param request the request + * @param baseContext the context to supply to the ONAPLoggingContext + * @return the ONAPLoggingContext + */ + public static ONAPLoggingContext getLoggingContextForRequest(HttpServletRequest request, + ONAPLoggingContext baseContext) { + ONAPLoggingContext requestContext = new ONAPLoggingContext(baseContext); + if (request.getLocalAddr() != null) { // may be null in junit tests + requestContext.setServerIPAddress(request.getLocalAddr()); + } + // get client IP address as leftmost address in X-Forwarded-For header if present, + // otherwise from remote address in the request + String forwarded = request.getHeader("X-Forwarded-For"); + if (forwarded != null && forwarded.trim().length() > 0) { + forwarded = forwarded.trim().split(",")[0]; + requestContext.setClientIPAddress(forwarded); + } else if (request.getRemoteAddr() != null) { // may be null in junit tests + requestContext.setClientIPAddress(request.getRemoteAddr()); + } + // RequestID + // This needs to be renamed to ONAP when the other components in ONAP + // rename to this. + String requestId = request.getHeader("X-ECOMP-RequestID"); + if (requestId != null && requestId.trim().length() > 0) { + requestContext.setRequestID(requestId); + } + return requestContext; + } } diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/Configuration.java b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/Configuration.java index 9d550c35..0752b188 100644 --- a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/Configuration.java +++ b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/Configuration.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-Logging * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,77 +24,59 @@ package org.onap.policy.common.logging.eelf; public interface Configuration extends com.att.eelf.configuration.Configuration { /** - * The Date-time of the start of a transaction + * The Date-time of the start of a transaction. */ String BEGIN_TIME_STAMP = "BeginTimestamp"; /** - * The Date-time of the end of transaction + * The Date-time of the end of transaction. */ String END_TIME_STAMP = "EndTimestamp"; /** - * Externally advertised API invoked by clients of this component + * Externally advertised API invoked by clients of this component. */ String SERVICE_NAME = "ServiceName"; /** - * Client or user invoking the API + * Client or user invoking the API. */ String PARTNER_NAME = "PartnerName"; - /** - * Target Entity - */ String TARGET_ENTITY = "TargetEntity"; - /** - * Target service name - */ String TARGET_SERVICE_NAME = "TargetServiceName"; /** - * High level success or failure (COMPLETE or ERROR) + * High level success or failure (COMPLETE or ERROR). */ String STATUS_CODE = "StatusCode"; /** - * Application specific response code + * Application specific response code. */ String RESPONSE_CODE = "ResponseCode"; /** - * Human readable description of the application specific response code + * Human readable description of the application specific response code. */ String RESPONSE_DESCRIPTION = "ResponseDescription"; /** - * Externally advertised API invoked by clients of this component + * Externally advertised API invoked by clients of this component. */ String ELAPSED_TIME = "ElapsedTime"; /** - * High level failure (ERROR) + * High level failure (ERROR). */ String ERROR_CATEGORY = "ErrorCategory"; - /** - * Error Code - */ String ERROR_CODE = "ErrorCode"; - /** - * Error Description - */ String ERROR_DESCRIPTION = "ErrorDescription"; - /** - * Class name - */ String CLASS_NAME = "ClassName"; - /** - * Server name - */ String SERVER_NAME = "ServerName"; } diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/DroolsPDPMDCInfo.java b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/DroolsPDPMDCInfo.java index ae4cc929..0c6c13ba 100644 --- a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/DroolsPDPMDCInfo.java +++ b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/DroolsPDPMDCInfo.java @@ -41,7 +41,9 @@ public class DroolsPDPMDCInfo implements MDCInfo { } /** - * @return the instance of ConcurrentHashMap + * Get the MMDC Info + * + * @return the instance of ConcurrentHashMap. */ @Override public ConcurrentMap<String, String> getMDCInfo() { diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/ErrorCodeMap.java b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/ErrorCodeMap.java index 845c5caf..4ae4068c 100644 --- a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/ErrorCodeMap.java +++ b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/ErrorCodeMap.java @@ -23,85 +23,98 @@ package org.onap.policy.common.logging.eelf; import java.util.EnumMap; /** - * - * ErrorCodeMap contains a HashMap of ErrorCodeInfo (error code and error description) - * + * ErrorCodeMap contains a HashMap of ErrorCodeInfo (error code and error description). */ public class ErrorCodeMap { private static final EnumMap<MessageCodes, ErrorCodeInfo> hm = new EnumMap<>(MessageCodes.class); - + private static final String ERROR_PERMISSIONS = "POLICY-100E"; - private static final String ERROR_PERMISSIONS_DESCRIPTION = "This is a Permissions Error. Please check the error message for detail information"; - - private static final String ERROR_SCHEMA_INVALID = "POLICY-400E"; - private static final String ERROR_SCHEMA_INVALID_DESCRIPTION = "This is an Invalid Schema Error. Please check the error message for detail information"; - + private static final String ERROR_PERMISSIONS_DESCRIPTION = + "This is a Permissions Error. Please check the error message for detail information"; + + private static final String ERROR_SCHEMA_INVALID = "POLICY-400E"; + private static final String ERROR_SCHEMA_INVALID_DESCRIPTION = + "This is an Invalid Schema Error. Please check the error message for detail information"; + private static final String UPDATE_ERROR = "POLICY-502E"; - private static final String UPDATE_ERROR_DESCRIPTION = "This is an updating error. Please check the error message for detail information"; - - private static final String EXCEPTION_ERROR_CODE = "POLICY-503E"; - private static final String EXCEPTION_ERROR_DESCRIPTION = "This is an exception error message during the process. Please check the error message for detail information"; - - private static final String MISS_PROPERTY_ERROR = "POLICY-504E"; - private static final String MISS_PROPERTY_ERROR_DESCRIPTION = "This is an error of missing properties. Please check the error message for detail information"; - + private static final String UPDATE_ERROR_DESCRIPTION = + "This is an updating error. Please check the error message for detail information"; + + private static final String EXCEPTION_ERROR_CODE = "POLICY-503E"; + private static final String EXCEPTION_ERROR_DESCRIPTION = + "This is an exception error message during the process. Please check the error message for detail " + + "information"; + + private static final String MISS_PROPERTY_ERROR = "POLICY-504E"; + private static final String MISS_PROPERTY_ERROR_DESCRIPTION = + "This is an error of missing properties. Please check the error message for detail information"; + private static final String GENERAL_ERROR_CODE = "POLICY-515E"; - private static final String GENERAL_ERROR_DESCRIPTION = "This is a general error message during the process. Please check the error message for detail information"; - + private static final String GENERAL_ERROR_DESCRIPTION = + "This is a general error message during the process. Please check the error message for detail information"; + private static final String ERROR_SYSTEM_ERROR = "POLICY-516E"; - private static final String ERROR_SYSTEM_ERROR_DESCRIPTION = "This is a System Error. Please check the error message for detail information"; - - private static final String ERROR_DATA_ISSUE = "POLICY-517E"; - private static final String ERROR_DATA_ISSUE_DESCRIPTION = "This is a Data Issue Error. Please check the error message for detail information"; - - private static final String ERROR_PROCESS_FLOW = "POLICY-518E"; - private static final String ERROR_PROCESS_FLOW_DESCRIPTION = "This is a Process Flow Error. Please check the error message for detail information"; - - private static final String ERROR_UNKNOWN = "POLICY-519E"; - private static final String ERROR_UNKNOWN_DESCRIPTION = "This is an Unknown Error. Please check the error message for detail information"; - - private static final String ERROR_AUDIT = "POLICY-520E"; - private static final String ERROR_AUDIT_DESCRIPTION = "This is an audit Error. Please check the error message for detail information"; - + private static final String ERROR_SYSTEM_ERROR_DESCRIPTION = + "This is a System Error. Please check the error message for detail information"; + + private static final String ERROR_DATA_ISSUE = "POLICY-517E"; + private static final String ERROR_DATA_ISSUE_DESCRIPTION = + "This is a Data Issue Error. Please check the error message for detail information"; + + private static final String ERROR_PROCESS_FLOW = "POLICY-518E"; + private static final String ERROR_PROCESS_FLOW_DESCRIPTION = + "This is a Process Flow Error. Please check the error message for detail information"; + + private static final String ERROR_UNKNOWN = "POLICY-519E"; + private static final String ERROR_UNKNOWN_DESCRIPTION = + "This is an Unknown Error. Please check the error message for detail information"; + + private static final String ERROR_AUDIT = "POLICY-520E"; + private static final String ERROR_AUDIT_DESCRIPTION = + "This is an audit Error. Please check the error message for detail information"; + static { - hm.put(MessageCodes.EXCEPTION_ERROR, new ErrorCodeInfo(EXCEPTION_ERROR_CODE, EXCEPTION_ERROR_DESCRIPTION)); - hm.put(MessageCodes.GENERAL_ERROR, new ErrorCodeInfo(GENERAL_ERROR_CODE, GENERAL_ERROR_DESCRIPTION)); - hm.put(MessageCodes.MISS_PROPERTY_ERROR, new ErrorCodeInfo(MISS_PROPERTY_ERROR, MISS_PROPERTY_ERROR_DESCRIPTION)); - hm.put(MessageCodes.UPDATE_ERROR, new ErrorCodeInfo(UPDATE_ERROR, UPDATE_ERROR_DESCRIPTION)); - hm.put(MessageCodes.ERROR_SYSTEM_ERROR, new ErrorCodeInfo(ERROR_SYSTEM_ERROR, ERROR_SYSTEM_ERROR_DESCRIPTION)); - hm.put(MessageCodes.ERROR_DATA_ISSUE, new ErrorCodeInfo(ERROR_DATA_ISSUE, ERROR_DATA_ISSUE_DESCRIPTION)); - hm.put(MessageCodes.ERROR_PERMISSIONS, new ErrorCodeInfo(ERROR_PERMISSIONS, ERROR_PERMISSIONS_DESCRIPTION)); - hm.put(MessageCodes.ERROR_DATA_ISSUE, new ErrorCodeInfo(ERROR_DATA_ISSUE, ERROR_DATA_ISSUE_DESCRIPTION)); - hm.put(MessageCodes.ERROR_PROCESS_FLOW, new ErrorCodeInfo(ERROR_PROCESS_FLOW, ERROR_PROCESS_FLOW_DESCRIPTION)); - hm.put(MessageCodes.ERROR_SCHEMA_INVALID, new ErrorCodeInfo(ERROR_SCHEMA_INVALID, ERROR_SCHEMA_INVALID_DESCRIPTION)); - hm.put(MessageCodes.ERROR_UNKNOWN, new ErrorCodeInfo(ERROR_UNKNOWN, ERROR_UNKNOWN_DESCRIPTION)); - hm.put(MessageCodes.ERROR_AUDIT, new ErrorCodeInfo(ERROR_AUDIT, ERROR_AUDIT_DESCRIPTION)); + hm.put(MessageCodes.EXCEPTION_ERROR, new ErrorCodeInfo(EXCEPTION_ERROR_CODE, EXCEPTION_ERROR_DESCRIPTION)); + hm.put(MessageCodes.GENERAL_ERROR, new ErrorCodeInfo(GENERAL_ERROR_CODE, GENERAL_ERROR_DESCRIPTION)); + hm.put(MessageCodes.MISS_PROPERTY_ERROR, + new ErrorCodeInfo(MISS_PROPERTY_ERROR, MISS_PROPERTY_ERROR_DESCRIPTION)); + hm.put(MessageCodes.UPDATE_ERROR, new ErrorCodeInfo(UPDATE_ERROR, UPDATE_ERROR_DESCRIPTION)); + hm.put(MessageCodes.ERROR_SYSTEM_ERROR, new ErrorCodeInfo(ERROR_SYSTEM_ERROR, ERROR_SYSTEM_ERROR_DESCRIPTION)); + hm.put(MessageCodes.ERROR_DATA_ISSUE, new ErrorCodeInfo(ERROR_DATA_ISSUE, ERROR_DATA_ISSUE_DESCRIPTION)); + hm.put(MessageCodes.ERROR_PERMISSIONS, new ErrorCodeInfo(ERROR_PERMISSIONS, ERROR_PERMISSIONS_DESCRIPTION)); + hm.put(MessageCodes.ERROR_DATA_ISSUE, new ErrorCodeInfo(ERROR_DATA_ISSUE, ERROR_DATA_ISSUE_DESCRIPTION)); + hm.put(MessageCodes.ERROR_PROCESS_FLOW, new ErrorCodeInfo(ERROR_PROCESS_FLOW, ERROR_PROCESS_FLOW_DESCRIPTION)); + hm.put(MessageCodes.ERROR_SCHEMA_INVALID, + new ErrorCodeInfo(ERROR_SCHEMA_INVALID, ERROR_SCHEMA_INVALID_DESCRIPTION)); + hm.put(MessageCodes.ERROR_UNKNOWN, new ErrorCodeInfo(ERROR_UNKNOWN, ERROR_UNKNOWN_DESCRIPTION)); + hm.put(MessageCodes.ERROR_AUDIT, new ErrorCodeInfo(ERROR_AUDIT, ERROR_AUDIT_DESCRIPTION)); } + private ErrorCodeMap() {} - + public static ErrorCodeInfo getErrorCodeInfo(MessageCodes messageCode) { return hm.get(messageCode); } - + static class ErrorCodeInfo { - - private String errorCode; - private String errorDesc; - - public ErrorCodeInfo(String errorCode, String errorDesc){ - this.errorCode = errorCode; - this.errorDesc = errorDesc; - } - - public String getErrorCode() { - return errorCode; - } - - public String getErrorDesc() { - return errorDesc; - } - - } - + + private String errorCode; + private String errorDesc; + + public ErrorCodeInfo(String errorCode, String errorDesc) { + this.errorCode = errorCode; + this.errorDesc = errorDesc; + } + + public String getErrorCode() { + return errorCode; + } + + public String getErrorDesc() { + return errorDesc; + } + + } + } diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventData.java b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventData.java index 037a144d..a8d90ad7 100644 --- a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventData.java +++ b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventData.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-Logging * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,35 +23,40 @@ package org.onap.policy.common.logging.eelf; import java.time.Instant; /** - * * EventData can be used for logging a rule event. - * */ public class EventData { - private String requestID = null; + private String requestId = null; private Instant startTime = null; private Instant endTime = null; - //Default constructor takes no arguments. - //Is empty because instance variables are assigned - //their default values upon declaration. - public EventData() { - //See above comments for the reason this constructor is empty + // Default constructor takes no arguments. + // Is empty because instance variables are assigned + // their default values upon declaration. + public EventData() { + // See above comments for the reason this constructor is empty } - public EventData(String requestID, Instant startTime, Instant endTime) { - this.requestID = requestID; + /** + * Create an instance. + * + * @param requestId the request ID + * @param startTime the start time + * @param endTime the end time + */ + public EventData(String requestId, Instant startTime, Instant endTime) { + this.requestId = requestId; this.startTime = startTime; this.endTime = endTime; } public String getRequestID() { - return requestID; + return requestId; } - public void setRequestID(String requestID) { - this.requestID = requestID; + public void setRequestID(String requestId) { + this.requestId = requestId; } public Instant getStartTime() { @@ -72,14 +77,14 @@ public class EventData { @Override public String toString() { - return requestID + " Starting Time : " + this.startTime + " Ending Time : " + this.endTime; + return requestId + " Starting Time : " + this.startTime + " Ending Time : " + this.endTime; } @Override public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + ((requestID == null) ? 0 : requestID.hashCode()); + result = prime * result + ((requestId == null) ? 0 : requestId.hashCode()); return result; } @@ -92,18 +97,18 @@ public class EventData { return false; } if (obj instanceof String) { - String requestId = (String) obj; - return requestID != null && requestID.equals(requestId); + String otherRequestId = (String) obj; + return requestId != null && requestId.equals(otherRequestId); } if (getClass() != obj.getClass()) { return false; } EventData other = (EventData) obj; - if (requestID == null) { - if (other.requestID != null) { + if (requestId == null) { + if (other.requestId != null) { return false; } - } else if (!requestID.equals(other.requestID)) { + } else if (!requestId.equals(other.requestId)) { return false; } return true; diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventTrackInfo.java b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventTrackInfo.java index 077a5a70..46401e9e 100644 --- a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventTrackInfo.java +++ b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventTrackInfo.java @@ -30,17 +30,22 @@ public class EventTrackInfo { private final ConcurrentMap<String, EventData> eventInfo; + /** + * Construct an instance. + */ public EventTrackInfo() { /* - * An initial capacity of 16 ensures the number of elements before resizing happens - * Load factor of 0,9 ensures a dense packaging inside ConcurrentHashMap which will optimize memory use - * Concurrency Level set to 1 will ensure that only one shard is created and maintained + * An initial capacity of 16 ensures the number of elements before resizing happens Load + * factor of 0,9 ensures a dense packaging inside ConcurrentHashMap which will optimize + * memory use Concurrency Level set to 1 will ensure that only one shard is created and + * maintained */ eventInfo = new ConcurrentHashMap<>(16, 0.9f, 1); } /** - * Returns an instance of EventData associated to this requestID + * Returns an instance of EventData associated to this requestID. + * * @param requestID request id * @return EventData */ @@ -50,6 +55,7 @@ public class EventTrackInfo { /** * Stores an EventData object in a ConcurrentHashMap using its requestID as key. + * * @param event event data */ public void storeEventData(EventData event) { @@ -59,7 +65,7 @@ public class EventTrackInfo { if (id == null || id.isEmpty()) { return; } - //in case override the start time, check the original event was already stored or not + // in case override the start time, check the original event was already stored or not if (!eventInfo.containsKey(id)) { eventInfo.put(id, event); } @@ -68,6 +74,7 @@ public class EventTrackInfo { /** * Removes an EventData object from a ConcurrentHashMap using the eventId as key. + * * @param eventId event id */ public void remove(String eventId) { @@ -77,7 +84,7 @@ public class EventTrackInfo { } /** - * Returns a ConcurrentHashMap of EventData + * Returns a ConcurrentHashMap of EventData. */ public ConcurrentMap<String, EventData> getEventInfo() { return eventInfo; diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventTrackInfoHandler.java b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventTrackInfoHandler.java index a79ab521..5f97c365 100644 --- a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventTrackInfoHandler.java +++ b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventTrackInfoHandler.java @@ -28,9 +28,7 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** - * - * EventTrackInfoHandler is the handler of clean up all expired event objects - * + * EventTrackInfoHandler is the handler of clean up all expired event objects. */ public class EventTrackInfoHandler extends TimerTask { @@ -47,7 +45,7 @@ public class EventTrackInfoHandler extends TimerTask { } /** - * Removes all expired event objects from the ConcurrentHashMap of EventData + * Removes all expired event objects from the ConcurrentHashMap of EventData. */ private void cleanUp() { diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/MDCInfo.java b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/MDCInfo.java index f49b34a7..f7832271 100644 --- a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/MDCInfo.java +++ b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/MDCInfo.java @@ -23,15 +23,14 @@ package org.onap.policy.common.logging.eelf; import java.util.concurrent.ConcurrentMap; /** - * - * Interface needs to be implemented by DroolsPDPMDCInfo - * + * Interface needs to be implemented by DroolsPDPMDCInfo. */ @FunctionalInterface public interface MDCInfo { /** * Returns MDC info. + * * @return MDC info */ ConcurrentMap<String, String> getMDCInfo(); diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/MessageCodes.java b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/MessageCodes.java index 3bfce0b5..ab5712ff 100644 --- a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/MessageCodes.java +++ b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/MessageCodes.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-Logging * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,140 +24,142 @@ import com.att.eelf.i18n.EELFResolvableErrorEnum; import com.att.eelf.i18n.EELFResourceManager; /** - * - * MessageCodes contains all the messagge codes for EELF logging messages - * + * MessageCodes contains all the messagge codes for EELF logging messages. */ public enum MessageCodes implements EELFResolvableErrorEnum { - // Below is a list of Error Messages taken from com.att.research.xacml.api XACMLErrorConstants - // found under: policy-engine\XACML\src\main\java\com\att\research\xacml\api\XACMLErrorConstants.java - - ERROR_PERMISSIONS, - - ERROR_SYSTEM_ERROR, - - ERROR_DATA_ISSUE, - - ERROR_SCHEMA_INVALID, - - ERROR_PROCESS_FLOW, - - ERROR_UNKNOWN, - - ERROR_AUDIT, - - // Above is a list of Error Messages taken from com.att.research.xacml.api XACMLErrorConstants - // found under: policy-engine\XACML\src\main\java\com\att\research\xacml\api\XACMLErrorConstants.java - - //----------------------5000-5099 Business/Flow Processing Related --------------------/ - - BAD_TYPE_WARNING, - - GENERAL_INFO, - - GENERAL_WARNING, - - MISS_PROPERTY_ERROR, - - EXCEPTION_ERROR, - - MISS_PROPERTY_INFO, - - RULE_AUDIT_EXEC_INFO, - - RULE_AUDIT_BEGIN_INFO, - - RULE_AUDIT_END_INFO, - - RULE_AUDIT_START_END_INFO, - - RULE_METRICS_INFO, - - UEB_AUDIT_EXEC_INFO, - - UEB_AUDIT_BEGIN_INFO, - - UEB_AUDIT_END_INFO, - - UPDATE_ERROR, - - GENERAL_ERROR, - - //----------------------New enums should be added above this line ------------------------------------------------------------------/ - - //--------------------- The enums below are old code. They should not be used since 1607 release and eventually will be removed -----/ - /** - * Application message which requires no arguments + // Below is a list of Error Messages taken from com.att.research.xacml.api XACMLErrorConstants + // found under: + // policy-engine\XACML\src\main\java\com\att\research\xacml\api\XACMLErrorConstants.java + + ERROR_PERMISSIONS, + + ERROR_SYSTEM_ERROR, + + ERROR_DATA_ISSUE, + + ERROR_SCHEMA_INVALID, + + ERROR_PROCESS_FLOW, + + ERROR_UNKNOWN, + + ERROR_AUDIT, + + // Above is a list of Error Messages taken from com.att.research.xacml.api XACMLErrorConstants + // found under: + // policy-engine\XACML\src\main\java\com\att\research\xacml\api\XACMLErrorConstants.java + + // ----------------------5000-5099 Business/Flow Processing Related --------------------/ + + BAD_TYPE_WARNING, + + GENERAL_INFO, + + GENERAL_WARNING, + + MISS_PROPERTY_ERROR, + + EXCEPTION_ERROR, + + MISS_PROPERTY_INFO, + + RULE_AUDIT_EXEC_INFO, + + RULE_AUDIT_BEGIN_INFO, + + RULE_AUDIT_END_INFO, + + RULE_AUDIT_START_END_INFO, + + RULE_METRICS_INFO, + + UEB_AUDIT_EXEC_INFO, + + UEB_AUDIT_BEGIN_INFO, + + UEB_AUDIT_END_INFO, + + UPDATE_ERROR, + + GENERAL_ERROR, + + // ----------------------New enums should be added above this line + // ------------------------------------------------------------------/ + + // --------------------- The enums below are old code. They should not be used since 1607 + // release and eventually will be removed -----/ + /** + * Application message which requires no arguments. */ - MESSAGE_SAMPLE_NOARGS, - - /** - * Application message which requires one argument {0} + MESSAGE_SAMPLE_NOARGS, + + /** + * Application message which requires one argument {0}. */ - MESSAGE_SAMPLE_ONEARGUMENT, - - /** - * Audit message which requires one argument {0} - */ - AUDIT_MESSAGE_ONEARGUMENT, - - /** - * Error message which requires one argument {0} + MESSAGE_SAMPLE_ONEARGUMENT, + + /** + * Audit message which requires one argument {0}. */ - ERROR_MESSAGE_ONEARGUMENT, - - /** - * Metrics message which requires one argument {0} + AUDIT_MESSAGE_ONEARGUMENT, + + /** + * Error message which requires one argument {0}. */ - METRICS_MESSAGE_ONEARGUMENT, - - /** - * Debug message which requires one argument {0} + ERROR_MESSAGE_ONEARGUMENT, + + /** + * Metrics message which requires one argument {0}. */ - DEBUG_MESSAGE_ONEARGUMENT, - + METRICS_MESSAGE_ONEARGUMENT, + /** - * Application message which requires two argument {0} and another argument {1} + * Debug message which requires one argument {0}. */ - MESSAGE_SAMPLE_TWOARGUMENTS, - - /** - * Sample error exception + DEBUG_MESSAGE_ONEARGUMENT, + + /** + * Application message which requires two argument {0} and another argument {1}. + */ + MESSAGE_SAMPLE_TWOARGUMENTS, + + /** + * Sample error exception. */ MESSAGE_SAMPLE_EXCEPTION, - - /** - * Sample warning message + + /** + * Sample warning message. */ - MESSAGE_WARNING_SAMPLE, - - /** - * Sample exception in method {0} + MESSAGE_WARNING_SAMPLE, + + /** + * Sample exception in method {0}. */ - MESSAGE_SAMPLE_EXCEPTION_ONEARGUMENT, - - /** - * Sample trace message + MESSAGE_SAMPLE_EXCEPTION_ONEARGUMENT, + + /** + * Sample trace message. */ - MESSAGE_TRACE_SAMPLE, - - /** - * Sample error message + MESSAGE_TRACE_SAMPLE, + + /** + * Sample error message. */ - MESSAGE_ERROR_SAMPLE; - - + MESSAGE_ERROR_SAMPLE; + + /** - * Static initializer to ensure the resource bundles for this class are loaded... - * Here this application loads messages from three bundles + * Static initializer to ensure the resource bundles for this class are loaded... Here this + * application loads messages from three bundles. */ static { EELFResourceManager.loadMessageBundle("org/onap/policy/common/logging/eelf/Resources"); String id = EELFResourceManager.getIdentifier(RULE_AUDIT_EXEC_INFO); String value = EELFResourceManager.getMessage(RULE_AUDIT_EXEC_INFO); - + PolicyLogger.info("*********************** Rule audit id: " + id); PolicyLogger.info("*********************** Rule audit value: " + value); - + } } diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/PolicyLogger.java b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/PolicyLogger.java index 3d351722..e3a7ab3f 100644 --- a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/PolicyLogger.java +++ b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/PolicyLogger.java @@ -20,9 +20,28 @@ package org.onap.policy.common.logging.eelf; -import static org.onap.policy.common.logging.eelf.Configuration.*; +import static com.att.eelf.configuration.Configuration.MDC_ALERT_SEVERITY; +import static com.att.eelf.configuration.Configuration.MDC_INSTANCE_UUID; +import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID; +import static com.att.eelf.configuration.Configuration.MDC_REMOTE_HOST; +import static com.att.eelf.configuration.Configuration.MDC_SERVER_FQDN; +import static com.att.eelf.configuration.Configuration.MDC_SERVER_IP_ADDRESS; +import static com.att.eelf.configuration.Configuration.MDC_SERVICE_INSTANCE_ID; +import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME; +import static org.onap.policy.common.logging.eelf.Configuration.BEGIN_TIME_STAMP; +import static org.onap.policy.common.logging.eelf.Configuration.ELAPSED_TIME; +import static org.onap.policy.common.logging.eelf.Configuration.END_TIME_STAMP; +import static org.onap.policy.common.logging.eelf.Configuration.ERROR_CATEGORY; +import static org.onap.policy.common.logging.eelf.Configuration.ERROR_CODE; +import static org.onap.policy.common.logging.eelf.Configuration.ERROR_DESCRIPTION; +import static org.onap.policy.common.logging.eelf.Configuration.PARTNER_NAME; +import static org.onap.policy.common.logging.eelf.Configuration.RESPONSE_CODE; +import static org.onap.policy.common.logging.eelf.Configuration.RESPONSE_DESCRIPTION; +import static org.onap.policy.common.logging.eelf.Configuration.SERVER_NAME; +import static org.onap.policy.common.logging.eelf.Configuration.STATUS_CODE; +import static org.onap.policy.common.logging.eelf.Configuration.TARGET_ENTITY; +import static org.onap.policy.common.logging.eelf.Configuration.TARGET_SERVICE_NAME; -import org.onap.policy.common.logging.flexlogger.LoggerType; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFLogger.Level; import com.att.eelf.configuration.EELFManager; @@ -42,1391 +61,1445 @@ import java.util.TimerTask; import java.util.UUID; import java.util.concurrent.ConcurrentMap; +import org.onap.policy.common.logging.flexlogger.LoggerType; import org.slf4j.MDC; /** - * - * PolicyLogger contains all the static methods for EELF logging - * + * PolicyLogger contains all the static methods for EELF logging. */ public class PolicyLogger { - private static EELFLogger errorLogger = EELFManager.getInstance() - .getErrorLogger(); - - private static EELFLogger metricsLogger = EELFManager.getInstance() - .getMetricsLogger(); - - private static EELFLogger auditLogger = EELFManager.getInstance() - .getAuditLogger(); - - private static EELFLogger debugLogger = EELFManager.getInstance() - .getDebugLogger(); - - private static final String POLICY_LOGGER = "PolicyLogger"; - - private static EventTrackInfo eventTracker = new EventTrackInfo(); - - private static String hostName = null; - private static String hostAddress = null; - private static String component = null; - - private static TimerTask ttrcker = null; - private static boolean isEventTrackerRunning = false; - private static Timer timer = null; - - //Default:Timer initial delay and the delay between in milliseconds before task is to be execute - private static int timerDelayTime = 1000; - - //Default:Timer scheduleAtFixedRate period - time in milliseconds between successive task executions - private static int checkInterval = 30 * 1000; - - //Default:longest time an event info can be stored in the concurrentHashMap for logging - in seconds - static int expiredTime = 60*60*1000*24; //one day - - //Default:the size of the concurrentHashMap which stores the event starting time - when its size reaches this limit, the Timer get executed - private static int concurrentHashMapLimit = 5000; - - //Default:the size of the concurrentHashMap which stores the event starting time - when its size drops to this point, stop the Timer - private static int stopCheckPoint = 2500; - - private static boolean isOverrideLogbackLevel = false; - - private static Level debugLevel = Level.INFO; - private static Level auditLevel = Level.INFO; - private static Level metricsLevel = Level.INFO; - private static Level errorLevel = Level.ERROR; - private static String classNameProp = "ClassName"; - - private static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS+00:00"; - private static final String COMPLETE_STATUS = "COMPLETE"; - private static final String ERROR_CATEGORY_VALUE = "ERROR"; - - static{ - if (hostName == null || hostAddress == null) { - try { - hostName = InetAddress.getLocalHost().getHostName(); - hostAddress = InetAddress.getLocalHost().getHostAddress(); - } catch (UnknownHostException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICY_LOGGER, "UnknownHostException"); - } - } - } - - public static Level getDebugLevel() { - return debugLevel; - } - - public static synchronized void setDebugLevel(Level level) { - debugLevel = level; - } - - public static Level getAuditLevel() { - return auditLevel; - } - - public static synchronized void setAuditLevel(Level level) { - auditLevel = level; - } - - public static Level getMetricsLevel() { - return metricsLevel; - } - - public static synchronized void setMetricsLevel(Level level) { - metricsLevel = level; - } - - public static Level getErrorLevel() { - return errorLevel; - } - - public static synchronized void setErrorLevel(Level level) { - errorLevel = level; - } - - public static String getClassname() { - return classNameProp; - } - - public static synchronized void setClassname(String name) { - classNameProp = name; - } - - /** - * Populates MDC info - * @param transId - * @return String - */ - public static String postMDCInfoForEvent(String transId) { - MDC.clear(); - - String transactionId = transId; - - if(transactionId == null || transactionId.isEmpty()){ - transactionId = UUID.randomUUID().toString(); - } - - if("DROOLS".equalsIgnoreCase(component)){ - MDC.put(TARGET_ENTITY, "POLICY"); - MDC.put(TARGET_SERVICE_NAME, "drools evaluate rule"); - return postMDCInfoForEvent(transactionId, new DroolsPDPMDCInfo()); - } else { - // For Xacml - MDC.put(TARGET_ENTITY, "POLICY"); - MDC.put(TARGET_SERVICE_NAME, "PE Process"); - } - - MDC.put(MDC_REMOTE_HOST, ""); - MDC.put(MDC_KEY_REQUEST_ID, transactionId); - MDC.put(MDC_SERVICE_NAME, "Policy.xacmlPdp"); - MDC.put(MDC_SERVICE_INSTANCE_ID, "Policy.xacmlPdp.event"); - try { - MDC.put(MDC_SERVER_FQDN, hostName); - MDC.put(MDC_SERVER_IP_ADDRESS, hostAddress); - } catch (Exception e) { - errorLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICY_LOGGER); - } - Instant startTime = Instant.now(); - Instant endTime = Instant.now(); - long ns = Duration.between(startTime, endTime).toMillis(); // use millisecond as default and remove unit from log - - MDC.put(MDC_INSTANCE_UUID, ""); - MDC.put(MDC_ALERT_SEVERITY, ""); - - SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); - - String formatedTime = sdf.format(Date.from(startTime)); - MDC.put(BEGIN_TIME_STAMP, formatedTime ); - - //set default values for these required fields below, they can be overridden - formatedTime = sdf.format(Date.from(endTime)); - MDC.put(END_TIME_STAMP, formatedTime); - MDC.put(ELAPSED_TIME, Long.toString(ns)); - - MDC.put(PARTNER_NAME, "N/A"); - - MDC.put(STATUS_CODE, COMPLETE_STATUS); - MDC.put(RESPONSE_CODE, "N/A"); - MDC.put(RESPONSE_DESCRIPTION, "N/A"); - - - return transactionId; - - } - - /** - * Populate MDC Info using the passed in mdcInfo - * @param transId - * @param mdcInfo - * @return String - */ - private static String postMDCInfoForEvent(String transId, MDCInfo mdcInfo ) { - - MDC.put(MDC_KEY_REQUEST_ID, transId); - if(mdcInfo != null && mdcInfo.getMDCInfo() != null && !mdcInfo.getMDCInfo().isEmpty()){ - - ConcurrentMap<String, String> mdcMap = mdcInfo.getMDCInfo(); - Iterator<String> keyIterator = mdcMap.keySet().iterator(); - String key; - - while(keyIterator.hasNext()){ - key = keyIterator.next(); - MDC.put(key, mdcMap.get(key)); - } - } - - try { - MDC.put(MDC_SERVER_FQDN, hostName); - MDC.put(MDC_SERVER_IP_ADDRESS, hostAddress); - } catch (Exception e) { - errorLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICY_LOGGER); - } - Instant startTime = Instant.now(); - Instant endTime = Instant.now(); - long ns = Duration.between(startTime, endTime).toMillis(); // use millisecond as default and remove unit from log - - SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); - - String formatedTime = sdf.format(Date.from(startTime)); - MDC.put(BEGIN_TIME_STAMP, formatedTime ); - - //set default values for these required fields below, they can be overridden - formatedTime = sdf.format(Date.from(endTime)); - MDC.put(END_TIME_STAMP, formatedTime); - MDC.put(ELAPSED_TIME, Long.toString(ns)); - - return transId; - } - - /** - * Set Timestamps for start, end and duration of logging a transaction - */ - private static void seTimeStamps(){ - - Instant startTime = Instant.now(); - Instant endTime = Instant.now(); - long ns = Duration.between(startTime, endTime).toMillis(); - - MDC.put(MDC_INSTANCE_UUID, ""); - MDC.put(MDC_ALERT_SEVERITY, ""); - - SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); - - String formatedTime = sdf.format(Date.from(startTime)); - MDC.put(BEGIN_TIME_STAMP, formatedTime ); - - //set default values for these required fields below, they can be overridden - formatedTime = sdf.format(Date.from(endTime)); - MDC.put(END_TIME_STAMP, formatedTime); - MDC.put(ELAPSED_TIME, Long.toString(ns)); - - MDC.put(PARTNER_NAME, "N/A"); - - MDC.put(STATUS_CODE, COMPLETE_STATUS); - MDC.put(RESPONSE_CODE, "N/A"); - MDC.put(RESPONSE_DESCRIPTION, "N/A"); - - } - - /** - * Sets transaction Id to MDC - * @param transId - */ - public static void setTransId(String transId){ - - MDC.put(MDC_KEY_REQUEST_ID, transId); - } - - /** - * Returns current transaction Id used in MDC - * @return transId - */ - public static String getTransId(){ - - return MDC.get(MDC_KEY_REQUEST_ID); - } - - /** - * Sets transaction Id to MDC - * @param o - */ - public static void postMDCInfoForEvent(Object o){ - postMDCInfoForEvent(""+o); - } - - /** - * Resets transaction Id in MDC for the rule triggered by this event - * @param transactionId - * @return String - */ - public static String postMDCInfoForTriggeredRule(String transId) { - - String transactionId = transId; - - MDC.clear(); - - if(transactionId == null || transactionId.isEmpty()){ - transactionId = UUID.randomUUID().toString(); - } - MDC.put(MDC_REMOTE_HOST, ""); - MDC.put(MDC_KEY_REQUEST_ID, transactionId); - MDC.put(MDC_SERVICE_NAME, "Policy.droolsPdp"); - MDC.put(MDC_SERVICE_INSTANCE_ID, ""); - try { - MDC.put(MDC_SERVER_FQDN, hostName); - MDC.put(MDC_SERVER_IP_ADDRESS, hostAddress); - } catch (Exception e) { - errorLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICY_LOGGER); - } - MDC.put(MDC_INSTANCE_UUID, ""); - MDC.put(MDC_ALERT_SEVERITY, ""); - MDC.put(STATUS_CODE, COMPLETE_STATUS); - - return transactionId; - - } - - /** - * Resets transaction Id in MDC for the rule triggered by this event - * @param o - */ - public static void postMDCUUIDForTriggeredRule(Object o) { - - postMDCInfoForTriggeredRule("" + o); - - } - - // ************************************************************************************************ - /** - * Records the Info event with String [] arguments - * @param msg - * @param className - * @param arguments - */ - public static void info(MessageCodes msg, String className, String... arguments) { - MDC.put(classNameProp, className); - debugLogger.info(msg, arguments); - } - - /** - * Records only one String message with its class name - * @param className - * @param arg0 - */ - public static void info( String className, String arg0) { - MDC.put(classNameProp, className); - debugLogger.info(MessageCodes.GENERAL_INFO, arg0); - } - - - /** - * Records only one String message - * @param arg0 - */ - public static void info(Object arg0) { - MDC.put(classNameProp, ""); - debugLogger.info(MessageCodes.GENERAL_INFO, String.valueOf(arg0)); - } - - /** - * Records a message with passed in message code, Throwable object, a list of string values - * @param msg - * @param arg0 - * @param arguments - */ - public static void info(MessageCodes msg, Throwable arg0, - String... arguments) { - MDC.put(classNameProp, ""); - String arguments2 = getNormalizedStackTrace(arg0, arguments); - debugLogger.info(msg, arguments2); - } - - /** - * Records a message with passed in message code, class name, Throwable object, a list of string values - * @param msg - * @param className - * @param arg0 - * @param arguments - */ - public static void info(MessageCodes msg, String className, Throwable arg0, - String... arguments) { - MDC.put(classNameProp, className); - String arguments2 = getNormalizedStackTrace(arg0, arguments); - debugLogger.info(msg, arguments2); - } - - /** - * Records only one String message with its class name - * @param arg0 log message - * @param className class name - */ - public static void warn( String className, String arg0) { - MDC.put(classNameProp, className); - debugLogger.warn(MessageCodes.GENERAL_INFO, arg0); - } - - /** - * Records only one String message - * @param arg0 - */ - public static void warn(Object arg0) { - MDC.put(classNameProp, ""); - debugLogger.warn(MessageCodes.GENERAL_WARNING, "" + arg0); - } - - /** - * Records only one String message without its class name passed in - * @param arg0 - */ - public static void warn(String arg0) { - MDC.put(classNameProp, ""); - debugLogger.warn(MessageCodes.GENERAL_WARNING, arg0); - } - - /** - * Records a message with passed in message code, class name and a list of string values - * @param msg - * @param className - * @param arguments - */ - public static void warn(MessageCodes msg, String className, String... arguments) { - MDC.put(classNameProp, className); - debugLogger.warn(msg, arguments); - } - - /** - * Records a message with passed in message code, Throwable object, a list of string values - * @param msg - * @param arg0 - * @param arguments - */ - public static void warn(MessageCodes msg, Throwable arg0, - String... arguments) { - MDC.put(classNameProp, ""); - String arguments2 = getNormalizedStackTrace(arg0, arguments); - debugLogger.warn(msg, arguments2); - } - - /** - * Records a message with passed in message code, Throwable object, a list of string values - * @param msg - * @param className - * @param arg0 - * @param arguments - */ - public static void warn(MessageCodes msg, String className, Throwable arg0, - String... arguments) { - MDC.put(classNameProp, className); - String arguments2 = getNormalizedStackTrace(arg0, arguments); - debugLogger.warn(msg, arguments2); - } - - /** - * Records only one String message with its class name - * @param className class name - * @param arg0 log message - */ - public static void error( String className, String arg0) { - MDC.put(classNameProp, className); - if(ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR) != null){ - MDC.put(ERROR_CODE, ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR).getErrorCode()); - MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR).getErrorDesc()); - - } - errorLogger.error(MessageCodes.GENERAL_ERROR, arg0); - } - - /** - * Records only one String message - * @param arg0 - */ - public static void error(String arg0) { - MDC.put(classNameProp, ""); - MDC.put(ERROR_CATEGORY, ERROR_CATEGORY_VALUE); - - if(ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR) != null){ - MDC.put(ERROR_CODE, ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR).getErrorCode()); - MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR).getErrorDesc()); - - } - errorLogger.error(MessageCodes.GENERAL_ERROR, arg0); - } - - /** - * Records only one String message - * @param arg0 - */ - public static void error(Object arg0) { - MDC.put(classNameProp, ""); - MDC.put(ERROR_CATEGORY, ERROR_CATEGORY_VALUE); - - if(ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR) != null){ - MDC.put(ERROR_CODE, ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR).getErrorCode()); - MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR).getErrorDesc()); - - } - errorLogger.error(MessageCodes.GENERAL_ERROR, "" + arg0); - } - - /** - * Records a message with passed in message code, Throwable object, a list of string values - * @param msg - * @param arg0 - * @param arguments - */ - public static void error(MessageCodes msg, Throwable arg0, - String... arguments) { - MDC.put(classNameProp, ""); - MDC.put(ERROR_CATEGORY, ERROR_CATEGORY_VALUE); - - if(ErrorCodeMap.getErrorCodeInfo(msg) != null){ - MDC.put(ERROR_CODE, ErrorCodeMap.getErrorCodeInfo(msg).getErrorCode()); - MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.getErrorCodeInfo(msg).getErrorDesc()); - - } - String arguments2 = getNormalizedStackTrace(arg0, arguments); - errorLogger.error(msg, arguments2); - } - - /** - * Records a message with passed in message code, class name, Throwable object, a list of string values - * @param msg - * @param className - * @param arg0 - * @param arguments - */ - public static void error(MessageCodes msg, String className, Throwable arg0, - String... arguments) { - MDC.put(classNameProp, className); - MDC.put(ERROR_CATEGORY, ERROR_CATEGORY_VALUE); - - if(ErrorCodeMap.getErrorCodeInfo(msg) != null){ - MDC.put(ERROR_CODE, ErrorCodeMap.getErrorCodeInfo(msg).getErrorCode()); - MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.getErrorCodeInfo(msg).getErrorDesc()); - - } - String arguments2 = getNormalizedStackTrace(arg0, arguments); - errorLogger.error(msg, arguments2); - } - - /** - * Records a message with passed in message code and a list of string values - * @param msg - * @param arguments - */ - public static void error(MessageCodes msg, String... arguments) { - MDC.put(classNameProp, ""); - MDC.put(ERROR_CATEGORY, ERROR_CATEGORY_VALUE); - - if(ErrorCodeMap.getErrorCodeInfo(msg) != null){ - MDC.put(ERROR_CODE, ErrorCodeMap.getErrorCodeInfo(msg).getErrorCode()); - MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.getErrorCodeInfo(msg).getErrorDesc()); - - } - errorLogger.error(msg, arguments); - } - - /** - * Records a message with passed in message code and a list of string values - * @param msg - * @param arguments - */ - public static void debug(MessageCodes msg, String... arguments) { - MDC.put(classNameProp, ""); - debugLogger.debug(msg, arguments); - } - - /** - * Records only one String message with its class name - * @param className - * @param arg0 - */ - public static void debug( String className, String arg0) { - MDC.put(classNameProp, className); - debugLogger.debug(MessageCodes.GENERAL_INFO, arg0); - } - - /** - * Records only one String message - * @param arg0 - */ - public static void debug(String arg0) { - MDC.put(classNameProp, ""); - debugLogger.debug(arg0); - } - - /** - * Records only one String message - * @param arg0 - */ - public static void debug(Object arg0) { - - MDC.put(classNameProp, ""); - debugLogger.debug("" + arg0); - } - - /** - * Records only one String message with its class name - * @param className - * @param arg0 - */ - public static void audit(String className, Object arg0) { - MDC.put(STATUS_CODE, COMPLETE_STATUS); - MDC.put(classNameProp, className); - auditLogger.info("" + arg0); - } - - /** - * Records only one String message - * @param arg0 - */ - public static void audit(Object arg0) { - MDC.put(STATUS_CODE, COMPLETE_STATUS); - MDC.put(classNameProp, ""); - auditLogger.info("" + arg0); - } - - /** - * Records a message with passed in message code, hrowable object, a list of string values - * @param msg - * @param arg0 - * @param arguments - */ - public static void debug(MessageCodes msg, Throwable arg0, - String... arguments) { - MDC.put(classNameProp, ""); - String arguments2 = getNormalizedStackTrace(arg0, arguments); - debugLogger.debug(msg, arguments2); - } - - /** - * Records a message with passed in message code, class name, Throwable object, a list of string values - * @param msg - * @param className - * @param arg0 - * @param arguments - */ - public static void debug(MessageCodes msg, String className, Throwable arg0, - String... arguments) { - MDC.put(classNameProp, className); - String arguments2 = getNormalizedStackTrace(arg0, arguments); - debugLogger.debug(msg, arguments2); - } - /** - * returns true for enabled, false for not enabled - */ - public static boolean isDebugEnabled(){ - - return debugLogger.isDebugEnabled(); - } - - /** - * returns true for enabled, false for not enabled - */ - public static boolean isErrorEnabled(){ - - return errorLogger.isErrorEnabled(); - } - - /** - * returns true for enabled, false for not enabled - */ - public static boolean isWarnEnabled(){ - - return debugLogger.isWarnEnabled(); - } - - /** - * returns true for enabled, false for not enabled - */ - public static boolean isInfoEnabled1(){ - - return debugLogger.isInfoEnabled(); - } - - /** - * returns true for enabled, false for not enabled - */ - public static boolean isAuditEnabled(){ - - return debugLogger.isInfoEnabled(); - } - - /** - * returns true for enabled, false for not enabled - */ - public static boolean isInfoEnabled(){ - - return debugLogger.isInfoEnabled(); - } - - /** - * Records only one String message with its class name - * @param className - * @param arg0 - */ - public static void trace( String className, String arg0) { - MDC.put(classNameProp, className); - debugLogger.trace(MessageCodes.GENERAL_INFO, arg0); - } - - /** - * Records only one String message - * @param arg0 - */ - public static void trace(Object arg0){ - - MDC.put(classNameProp, ""); - debugLogger.trace(""+arg0); - } - /** - * Records the starting time of the event with its request Id as the key - * @param eventId - */ - public static void recordAuditEventStart(String eventId) { - - MDC.put(STATUS_CODE, COMPLETE_STATUS); - postMDCInfoForEvent(eventId); - - if(eventTracker == null){ - eventTracker = new EventTrackInfo(); - } - EventData event = new EventData(); - event.setRequestID(eventId); - event.setStartTime(Instant.now()); - eventTracker.storeEventData(event); - MDC.put(MDC_KEY_REQUEST_ID, eventId); - debugLogger.info("CONCURRENTHASHMAP_LIMIT : " + concurrentHashMapLimit); - //--- Tracking the size of the concurrentHashMap, if it is above limit, keep EventTrack Timer running - int size = eventTracker.getEventInfo().size(); - - debugLogger.info("EventInfo concurrentHashMap Size : " + size + " on " + new Date()); - debugLogger.info("isEventTrackerRunning : " + isEventTrackerRunning); - - if( size >= concurrentHashMapLimit){ - - - if(!isEventTrackerRunning){ - - startCleanUp(); - isEventTrackerRunning = true; - } - - }else if( size <= stopCheckPoint && isEventTrackerRunning){ - - stopCleanUp(); - } - } - - /** - * Records the starting time of the event with its request Id as the key - * @param eventId - */ - public static void recordAuditEventStart(UUID eventId) { - - if(eventId == null){ - return; - } - - if(eventTracker == null){ - eventTracker = new EventTrackInfo(); - } - - recordAuditEventStart(eventId.toString()); - - } - - /** - * Records the ending time of the event with its request Id as the key - * @param eventId - * @param rule - */ - public static void recordAuditEventEnd(String eventId, String rule) { - - if(eventTracker == null){ - return; - } - if(eventId == null){ - return; - } - - creatAuditEventTrackingRecord(eventId, rule, ""); - - } - - /** - * Records the ending time of the event with its request Id as the key - * @param eventId - * @param rule - * @param policyVersion - */ - public static void recordAuditEventEnd(String eventId, String rule , String policyVersion) { - - if(eventTracker == null){ - return; - } - if(eventId == null){ - return; - } - - creatAuditEventTrackingRecord(eventId, rule, policyVersion); - - } - - /** - * Records the ending time of the event with its request Id as the key - * @param eventId - * @param rule - * @param policyVersion - */ - public static void recordAuditEventEnd(UUID eventId, String rule, String policyVersion) { - - if(eventId == null){ - return; - } - - recordAuditEventEnd(eventId.toString(), rule, policyVersion); - - } - - - /** - * Records the ending time of the event with its request Id as the key - * @param eventId - * @param rule - */ - public static void recordAuditEventEnd(UUID eventId, String rule) { - - if(eventId == null){ - return; - } - - recordAuditEventEnd(eventId.toString(), rule); - - } - - /** - * Records the ending time of the event with its request Id as the key - * @param eventId - * @param rule - * @param policyVersion - */ - public static void creatAuditEventTrackingRecord(String eventId, String rule, String policyVersion) { - - if(eventTracker == null){ - return; - } - - EventData event = eventTracker.getEventDataByRequestID(eventId); - - if(event != null){ - Instant endTime = event.getEndTime(); - if(endTime == null){ - endTime = Instant.now(); - } - MDC.put(STATUS_CODE, COMPLETE_STATUS); - recordAuditEventStartToEnd(eventId, rule, event.getStartTime(), endTime, policyVersion); - } - } - - /** - * Records the ending time of the event with its request Id as the key - * @param eventId - * @param rule - */ - public static void creatAuditEventTrackingRecord(UUID eventId, String rule) { - - if(eventId == null){ - return; - } - - if(eventTracker == null){ - return; - } - - EventData event = eventTracker.getEventDataByRequestID(eventId.toString()); - - if(event != null){ - Instant endTime = event.getEndTime(); - if(endTime == null){ - endTime = Instant.now(); - } - - recordAuditEventStartToEnd(eventId.toString(), rule, event.getStartTime(), endTime, "N/A"); - } - } - - public static EventTrackInfo getEventTracker() { - return eventTracker; - } - - /** - * Records the audit with an event starting and ending times - * @param eventId - * @param rule - * @param startTime - * @param endTime - * @param policyVersion - */ - public static void recordAuditEventStartToEnd(String eventId, String rule, Instant startTime, Instant endTime, String policyVersion) { - - if(startTime == null || endTime == null){ - return; - } - String serviceName = MDC.get(MDC_SERVICE_NAME); - if(eventId != null && !eventId.isEmpty()){ - MDC.put(MDC_KEY_REQUEST_ID, eventId); - } - - SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); - - String formatedTime = sdf.format(Date.from(startTime)); - MDC.put(BEGIN_TIME_STAMP, formatedTime ); - - //set default values for these required fields below, they can be overridden - formatedTime = sdf.format(Date.from(endTime)); - MDC.put(END_TIME_STAMP, formatedTime); - - MDC.put(RESPONSE_CODE, "N/A"); - MDC.put(RESPONSE_DESCRIPTION, "N/A"); - - long ns = Duration.between(startTime, endTime).toMillis(); - - MDC.put(ELAPSED_TIME, Long.toString(ns)); - - auditLogger.info(MessageCodes.RULE_AUDIT_START_END_INFO, - serviceName, rule, startTime.toString(), endTime.toString(), Long.toString(ns), policyVersion); - - //--- remove the record from the concurrentHashMap - if(eventTracker != null && eventTracker.getEventDataByRequestID(eventId) != null){ - - eventTracker.remove(eventId); - debugLogger.info("eventTracker.remove(" + eventId + ")"); - - } - } - - /** - * Records the metrics with an event Id and log message - * @param eventId - * @param arg1 - */ - public static void recordMetricEvent(String eventId, String arg1) { - - seTimeStamps(); - - String serviceName = MDC.get(MDC_SERVICE_NAME); - MDC.put(MDC_KEY_REQUEST_ID, eventId); - metricsLogger.info(MessageCodes.RULE_AUDIT_END_INFO, - serviceName, arg1); - - } - - /** - * Records the metrics with an event Id, class name and log message - * @param eventId - * @param className - * @param arg1 - */ - public static void recordMetricEvent(String eventId, String className,String arg1) { - - seTimeStamps(); - - MDC.put(classNameProp, className); - String serviceName = MDC.get(MDC_SERVICE_NAME); - MDC.put(MDC_KEY_REQUEST_ID, eventId); - metricsLogger.info(MessageCodes.RULE_AUDIT_END_INFO, - serviceName, arg1); - } - - /** - * Records the metrics with an event Id and log message - * @param eventId - * @param arg1 - */ - public static void recordMetricEvent(UUID eventId, String arg1) { - - if(eventId == null){ - return; - } - String serviceName = MDC.get(MDC_SERVICE_NAME); - MDC.put(MDC_KEY_REQUEST_ID, eventId.toString()); - metricsLogger.info(MessageCodes.RULE_AUDIT_END_INFO, - serviceName, arg1); - } - - /** - * Records a String message for metrics logs - * @param arg0 - */ - public static void recordMetricEvent(String arg0) { - seTimeStamps(); - String serviceName = MDC.get(MDC_SERVICE_NAME); - metricsLogger.info(MessageCodes.RULE_METRICS_INFO, - serviceName, arg0); - } - - - /** - * Records the metrics event with a String message - * @param arg0 - */ - public static void metrics(String arg0) { - String serviceName = MDC.get(MDC_SERVICE_NAME); - metricsLogger.info(MessageCodes.RULE_METRICS_INFO, - serviceName, arg0); - } - - /** - * Records the metrics event with a class name and a String message - * @param arg0 - */ - public static void metrics(String className, Object arg0) { - seTimeStamps(); - MDC.put(classNameProp, className); - String serviceName = MDC.get(MDC_SERVICE_NAME); - metricsLogger.info(MessageCodes.RULE_METRICS_INFO, - serviceName, ""+arg0); - } - - /** - * Records the metrics event with a String message - * @param arg0 - */ - public static void metrics(Object arg0) { - seTimeStamps(); - MDC.put(classNameProp, ""); - String serviceName = MDC.get(MDC_SERVICE_NAME); - metricsLogger.info(MessageCodes.RULE_METRICS_INFO, - serviceName, ""+arg0); - } - - /** - * Records the metrics event with a String message - * @param arg0 - */ - public static void metricsPrintln(String arg0) { - MDC.clear(); - metricsLogger.info(arg0); - } - - /** - * Removes all the return lines from the printStackTrace - * @param t - * @param arguments - */ - private static String getNormalizedStackTrace (Throwable t, String...arguments) { + private static EELFLogger errorLogger = EELFManager.getInstance().getErrorLogger(); + + private static EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger(); + + private static EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger(); + + private static EELFLogger debugLogger = EELFManager.getInstance().getDebugLogger(); + + private static final String POLICY_LOGGER = "PolicyLogger"; + + private static EventTrackInfo eventTracker = new EventTrackInfo(); + + private static String hostName = null; + private static String hostAddress = null; + private static String component = null; + + private static TimerTask ttrcker = null; + private static boolean isEventTrackerRunning = false; + private static Timer timer = null; + + // Default:Timer initial delay and the delay between in milliseconds before task is to be + // execute + private static int timerDelayTime = 1000; + + // Default:Timer scheduleAtFixedRate period - time in milliseconds between successive task + // executions + private static int checkInterval = 30 * 1000; + + // Default:longest time an event info can be stored in the concurrentHashMap for logging - in + // seconds + static int expiredTime = 60 * 60 * 1000 * 24; // one day + + // Default:the size of the concurrentHashMap which stores the event starting time - when its + // size reaches this limit, the Timer get executed + private static int concurrentHashMapLimit = 5000; + + // Default:the size of the concurrentHashMap which stores the event starting time - when its + // size drops to this point, stop the Timer + private static int stopCheckPoint = 2500; + + private static boolean isOverrideLogbackLevel = false; + + private static Level debugLevel = Level.INFO; + private static Level auditLevel = Level.INFO; + private static Level metricsLevel = Level.INFO; + private static Level errorLevel = Level.ERROR; + private static String classNameProp = "ClassName"; + + private static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS+00:00"; + private static final String COMPLETE_STATUS = "COMPLETE"; + private static final String ERROR_CATEGORY_VALUE = "ERROR"; + + static { + if (hostName == null || hostAddress == null) { + try { + hostName = InetAddress.getLocalHost().getHostName(); + hostAddress = InetAddress.getLocalHost().getHostAddress(); + } catch (UnknownHostException e) { + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICY_LOGGER, "UnknownHostException"); + } + } + } + + public static Level getDebugLevel() { + return debugLevel; + } + + public static synchronized void setDebugLevel(Level level) { + debugLevel = level; + } + + /** + * Sets Debug Level. + */ + public static void setDebugLevel(String newDebugLevel) { + + if (isOverrideLogbackLevel) { + PolicyLogger.debugLevel = Level.valueOf(newDebugLevel); + debugLogger.setLevel(debugLevel); + } + + } + + public static Level getAuditLevel() { + return auditLevel; + } + + public static synchronized void setAuditLevel(Level level) { + auditLevel = level; + } + + /** + * Sets Audit OFF or ON. + */ + public static void setAuditLevel(String newAuditLevel) { + + if (isOverrideLogbackLevel) { + if ("OFF".equalsIgnoreCase(newAuditLevel)) { + PolicyLogger.auditLevel = Level.OFF; + auditLogger.setLevel(auditLevel); + } else { + // --- set default value + auditLogger.setLevel(Level.INFO); + PolicyLogger.auditLevel = Level.INFO; + } + } + } + + public static Level getMetricsLevel() { + return metricsLevel; + } + + public static synchronized void setMetricsLevel(Level level) { + metricsLevel = level; + } + + /** + * Sets Metrics OFF or ON. + */ + public static void setMetricsLevel(String newMetricsLevel) { + + if (isOverrideLogbackLevel) { + if ("OFF".equalsIgnoreCase(newMetricsLevel)) { + PolicyLogger.metricsLevel = Level.OFF; + metricsLogger.setLevel(metricsLevel); + } else { + // --- set default value + metricsLogger.setLevel(Level.INFO); + PolicyLogger.metricsLevel = Level.INFO; + } + } + + } + + public static Level getErrorLevel() { + return errorLevel; + } + + public static synchronized void setErrorLevel(Level level) { + errorLevel = level; + } + + /** + * Sets Error OFF or ON. + */ + public static void setErrorLevel(String newErrorLevel) { + + if (isOverrideLogbackLevel) { + if ("OFF".equalsIgnoreCase(newErrorLevel)) { + PolicyLogger.errorLevel = Level.OFF; + errorLogger.setLevel(errorLevel); + } else { + // --- set default value + errorLogger.setLevel(Level.ERROR); + PolicyLogger.errorLevel = Level.ERROR; + } + } + } + + public static String getClassname() { + return classNameProp; + } + + public static synchronized void setClassname(String name) { + classNameProp = name; + } + + /** + * Populates MDC info. + * + * @param transId the transaction ID + * @return String + */ + public static String postMDCInfoForEvent(String transId) { + MDC.clear(); + + String transactionId = transId; + + if (transactionId == null || transactionId.isEmpty()) { + transactionId = UUID.randomUUID().toString(); + } + + if ("DROOLS".equalsIgnoreCase(component)) { + MDC.put(TARGET_ENTITY, "POLICY"); + MDC.put(TARGET_SERVICE_NAME, "drools evaluate rule"); + return postMDCInfoForEvent(transactionId, new DroolsPDPMDCInfo()); + } else { + // For Xacml + MDC.put(TARGET_ENTITY, "POLICY"); + MDC.put(TARGET_SERVICE_NAME, "PE Process"); + } + + MDC.put(MDC_REMOTE_HOST, ""); + MDC.put(MDC_KEY_REQUEST_ID, transactionId); + MDC.put(MDC_SERVICE_NAME, "Policy.xacmlPdp"); + MDC.put(MDC_SERVICE_INSTANCE_ID, "Policy.xacmlPdp.event"); + try { + MDC.put(MDC_SERVER_FQDN, hostName); + MDC.put(MDC_SERVER_IP_ADDRESS, hostAddress); + } catch (Exception e) { + errorLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICY_LOGGER); + } + + MDC.put(MDC_INSTANCE_UUID, ""); + MDC.put(MDC_ALERT_SEVERITY, ""); + + SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); + + Instant startTime = Instant.now(); + Instant endTime = Instant.now(); + + String formatedTime = sdf.format(Date.from(startTime)); + MDC.put(BEGIN_TIME_STAMP, formatedTime); + + // set default values for these required fields below, they can be overridden + formatedTime = sdf.format(Date.from(endTime)); + MDC.put(END_TIME_STAMP, formatedTime); + MDC.put(ELAPSED_TIME, Long.toString(Duration.between(startTime, endTime).toMillis())); + + MDC.put(PARTNER_NAME, "N/A"); + + MDC.put(STATUS_CODE, COMPLETE_STATUS); + MDC.put(RESPONSE_CODE, "N/A"); + MDC.put(RESPONSE_DESCRIPTION, "N/A"); + + + return transactionId; + + } + + /** + * Populate MDC Info using the passed in mdcInfo. + * + * @param transId the transaction ID + * @param mdcInfo the MDC info + * @return String + */ + private static String postMDCInfoForEvent(String transId, MDCInfo mdcInfo) { + + MDC.put(MDC_KEY_REQUEST_ID, transId); + if (mdcInfo != null && mdcInfo.getMDCInfo() != null && !mdcInfo.getMDCInfo().isEmpty()) { + + ConcurrentMap<String, String> mdcMap = mdcInfo.getMDCInfo(); + Iterator<String> keyIterator = mdcMap.keySet().iterator(); + String key; + + while (keyIterator.hasNext()) { + key = keyIterator.next(); + MDC.put(key, mdcMap.get(key)); + } + } + + try { + MDC.put(MDC_SERVER_FQDN, hostName); + MDC.put(MDC_SERVER_IP_ADDRESS, hostAddress); + } catch (Exception e) { + errorLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICY_LOGGER); + } + Instant startTime = Instant.now(); + Instant endTime = Instant.now(); + + SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); + + String formatedTime = sdf.format(Date.from(startTime)); + MDC.put(BEGIN_TIME_STAMP, formatedTime); + + // set default values for these required fields below, they can be overridden + formatedTime = sdf.format(Date.from(endTime)); + MDC.put(END_TIME_STAMP, formatedTime); + MDC.put(ELAPSED_TIME, Long.toString(Duration.between(startTime, endTime).toMillis())); + + return transId; + } + + /** + * Sets transaction Id to MDC. + * + * @param eventObject event object + */ + public static void postMDCInfoForEvent(Object eventObject) { + postMDCInfoForEvent("" + eventObject); + } + + /** + * Set Timestamps for start, end and duration of logging a transaction. + */ + private static void seTimeStamps() { + + MDC.put(MDC_INSTANCE_UUID, ""); + MDC.put(MDC_ALERT_SEVERITY, ""); + + SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); + + Instant startTime = Instant.now(); + Instant endTime = Instant.now(); + + String formatedTime = sdf.format(Date.from(startTime)); + MDC.put(BEGIN_TIME_STAMP, formatedTime); + + // set default values for these required fields below, they can be overridden + formatedTime = sdf.format(Date.from(endTime)); + MDC.put(END_TIME_STAMP, formatedTime); + MDC.put(ELAPSED_TIME, Long.toString(Duration.between(startTime, endTime).toMillis())); + + MDC.put(PARTNER_NAME, "N/A"); + + MDC.put(STATUS_CODE, COMPLETE_STATUS); + MDC.put(RESPONSE_CODE, "N/A"); + MDC.put(RESPONSE_DESCRIPTION, "N/A"); + + } + + /** + * Sets transaction Id to MDC. + * + * @param transId the transaction ID + */ + public static void setTransId(String transId) { + + MDC.put(MDC_KEY_REQUEST_ID, transId); + } + + /** + * Returns current transaction Id used in MDC. + * + * @return transId + */ + public static String getTransId() { + + return MDC.get(MDC_KEY_REQUEST_ID); + } + + /** + * Resets transaction Id in MDC for the rule triggered by this event. + * + * @param transId the transaction ID + * @return String + */ + public static String postMDCInfoForTriggeredRule(String transId) { + + String transactionId = transId; + + MDC.clear(); + + if (transactionId == null || transactionId.isEmpty()) { + transactionId = UUID.randomUUID().toString(); + } + MDC.put(MDC_REMOTE_HOST, ""); + MDC.put(MDC_KEY_REQUEST_ID, transactionId); + MDC.put(MDC_SERVICE_NAME, "Policy.droolsPdp"); + MDC.put(MDC_SERVICE_INSTANCE_ID, ""); + try { + MDC.put(MDC_SERVER_FQDN, hostName); + MDC.put(MDC_SERVER_IP_ADDRESS, hostAddress); + } catch (Exception e) { + errorLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICY_LOGGER); + } + MDC.put(MDC_INSTANCE_UUID, ""); + MDC.put(MDC_ALERT_SEVERITY, ""); + MDC.put(STATUS_CODE, COMPLETE_STATUS); + + return transactionId; + + } + + /** + * Resets transaction Id in MDC for the rule triggered by this event. + * + * @param obj object + */ + public static void postMDCUUIDForTriggeredRule(Object obj) { + + postMDCInfoForTriggeredRule("" + obj); + + } + + // ************************************************************************************************ + /** + * Records the Info event with String [] arguments. + * + * @param msg the message code + * @param className the class name + * @param arguments the messages + */ + public static void info(MessageCodes msg, String className, String... arguments) { + MDC.put(classNameProp, className); + debugLogger.info(msg, arguments); + } + + /** + * Records only one String message with its class name. + * + * @param className the class name + * @param arg0 the message + */ + public static void info(String className, String arg0) { + MDC.put(classNameProp, className); + debugLogger.info(MessageCodes.GENERAL_INFO, arg0); + } + + + /** + * Records only one String message. + * + * @param arg0 the message + */ + public static void info(Object arg0) { + MDC.put(classNameProp, ""); + debugLogger.info(MessageCodes.GENERAL_INFO, String.valueOf(arg0)); + } + + /** + * Records a message with passed in message code, Throwable object, a list of string values. + * + * @param msg the message code + * @param arg0 the throwable + * @param arguments the messages + */ + public static void info(MessageCodes msg, Throwable arg0, String... arguments) { + MDC.put(classNameProp, ""); + String arguments2 = getNormalizedStackTrace(arg0, arguments); + debugLogger.info(msg, arguments2); + } + + /** + * Records a message with passed in message code, class name, Throwable object, a list of string + * values. + * + * @param msg the message code + * @param className the class name + * @param arg0 the throwable + * @param arguments the messages + */ + public static void info(MessageCodes msg, String className, Throwable arg0, String... arguments) { + MDC.put(classNameProp, className); + String arguments2 = getNormalizedStackTrace(arg0, arguments); + debugLogger.info(msg, arguments2); + } + + /** + * Records only one String message with its class name. + * + * @param arg0 log message + * @param className class name + */ + public static void warn(String className, String arg0) { + MDC.put(classNameProp, className); + debugLogger.warn(MessageCodes.GENERAL_INFO, arg0); + } + + /** + * Records only one String message. + * + * @param arg0 the message + */ + public static void warn(Object arg0) { + MDC.put(classNameProp, ""); + debugLogger.warn(MessageCodes.GENERAL_WARNING, "" + arg0); + } + + /** + * Records only one String message without its class name passed in. + * + * @param arg0 the message + */ + public static void warn(String arg0) { + MDC.put(classNameProp, ""); + debugLogger.warn(MessageCodes.GENERAL_WARNING, arg0); + } + + /** + * Records a message with passed in message code, class name and a list of string values. + * + * @param msg the message code + * @param className the class name + * @param arguments the messages + */ + public static void warn(MessageCodes msg, String className, String... arguments) { + MDC.put(classNameProp, className); + debugLogger.warn(msg, arguments); + } + + /** + * Records a message with passed in message code, Throwable object, a list of string values. + * + * @param msg the message code + * @param arg0 the throwable + * @param arguments the messages + */ + public static void warn(MessageCodes msg, Throwable arg0, String... arguments) { + MDC.put(classNameProp, ""); + String arguments2 = getNormalizedStackTrace(arg0, arguments); + debugLogger.warn(msg, arguments2); + } + + /** + * Records a message with passed in message code, Throwable object, a list of string values. + * + * @param msg the message code + * @param className the class name + * @param arg0 the throwable + * @param arguments the messages + */ + public static void warn(MessageCodes msg, String className, Throwable arg0, String... arguments) { + MDC.put(classNameProp, className); + String arguments2 = getNormalizedStackTrace(arg0, arguments); + debugLogger.warn(msg, arguments2); + } + + /** + * Records only one String message with its class name. + * + * @param className class name + * @param arg0 log message + */ + public static void error(String className, String arg0) { + MDC.put(classNameProp, className); + if (ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR) != null) { + MDC.put(ERROR_CODE, ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR).getErrorCode()); + MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR).getErrorDesc()); + + } + errorLogger.error(MessageCodes.GENERAL_ERROR, arg0); + } + + /** + * Records only one String message. + * + * @param arg0 the message + */ + public static void error(String arg0) { + MDC.put(classNameProp, ""); + MDC.put(ERROR_CATEGORY, ERROR_CATEGORY_VALUE); + + if (ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR) != null) { + MDC.put(ERROR_CODE, ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR).getErrorCode()); + MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR).getErrorDesc()); + + } + errorLogger.error(MessageCodes.GENERAL_ERROR, arg0); + } + + /** + * Records only one String message. + * + * @param arg0 the message + */ + public static void error(Object arg0) { + MDC.put(classNameProp, ""); + MDC.put(ERROR_CATEGORY, ERROR_CATEGORY_VALUE); + + if (ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR) != null) { + MDC.put(ERROR_CODE, ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR).getErrorCode()); + MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR).getErrorDesc()); + + } + errorLogger.error(MessageCodes.GENERAL_ERROR, "" + arg0); + } + + /** + * Records a message with passed in message code, Throwable object, a list of string values. + * + * @param msg the message code + * @param arg0 the throwable + * @param arguments the messages + */ + public static void error(MessageCodes msg, Throwable arg0, String... arguments) { + MDC.put(classNameProp, ""); + MDC.put(ERROR_CATEGORY, ERROR_CATEGORY_VALUE); + + if (ErrorCodeMap.getErrorCodeInfo(msg) != null) { + MDC.put(ERROR_CODE, ErrorCodeMap.getErrorCodeInfo(msg).getErrorCode()); + MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.getErrorCodeInfo(msg).getErrorDesc()); + + } + String arguments2 = getNormalizedStackTrace(arg0, arguments); + errorLogger.error(msg, arguments2); + } + + /** + * Records a message with passed in message code, class name, Throwable object, a list of string + * values. + * + * @param msg the message code + * @param className the class name + * @param arg0 the throwable + * @param arguments the messages + */ + public static void error(MessageCodes msg, String className, Throwable arg0, String... arguments) { + MDC.put(classNameProp, className); + MDC.put(ERROR_CATEGORY, ERROR_CATEGORY_VALUE); + + if (ErrorCodeMap.getErrorCodeInfo(msg) != null) { + MDC.put(ERROR_CODE, ErrorCodeMap.getErrorCodeInfo(msg).getErrorCode()); + MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.getErrorCodeInfo(msg).getErrorDesc()); + + } + String arguments2 = getNormalizedStackTrace(arg0, arguments); + errorLogger.error(msg, arguments2); + } + + /** + * Records a message with passed in message code and a list of string values. + * + * @param msg the message code + * @param arguments the messages + */ + public static void error(MessageCodes msg, String... arguments) { + MDC.put(classNameProp, ""); + MDC.put(ERROR_CATEGORY, ERROR_CATEGORY_VALUE); + + if (ErrorCodeMap.getErrorCodeInfo(msg) != null) { + MDC.put(ERROR_CODE, ErrorCodeMap.getErrorCodeInfo(msg).getErrorCode()); + MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.getErrorCodeInfo(msg).getErrorDesc()); + + } + errorLogger.error(msg, arguments); + } + + /** + * Records a message with passed in message code and a list of string values. + * + * @param msg the message code + * @param arguments the messages + */ + public static void debug(MessageCodes msg, String... arguments) { + MDC.put(classNameProp, ""); + debugLogger.debug(msg, arguments); + } + + /** + * Records only one String message with its class name. + * + * @param className the class name + * @param arg0 the message + */ + public static void debug(String className, String arg0) { + MDC.put(classNameProp, className); + debugLogger.debug(MessageCodes.GENERAL_INFO, arg0); + } + + /** + * Records only one String message. + * + * @param arg0 the message + */ + public static void debug(String arg0) { + MDC.put(classNameProp, ""); + debugLogger.debug(arg0); + } + + /** + * Records only one String message. + * + * @param arg0 the message + */ + public static void debug(Object arg0) { + + MDC.put(classNameProp, ""); + debugLogger.debug("" + arg0); + } + + /** + * Records a message with passed in message code, hrowable object, a list of string values. + * + * @param msg the message code + * @param arg0 the throwable + * @param arguments the messages + */ + public static void debug(MessageCodes msg, Throwable arg0, String... arguments) { + MDC.put(classNameProp, ""); + String arguments2 = getNormalizedStackTrace(arg0, arguments); + debugLogger.debug(msg, arguments2); + } + + /** + * Records a message with passed in message code, class name, Throwable object, a list of + * string. values + * + * @param msg the message code + * @param className the class name + * @param arg0 the throwable + * @param arguments the messages + */ + public static void debug(MessageCodes msg, String className, Throwable arg0, String... arguments) { + MDC.put(classNameProp, className); + String arguments2 = getNormalizedStackTrace(arg0, arguments); + debugLogger.debug(msg, arguments2); + } + + /** + * Records only one String message with its class name. + * + * @param className the class name + * @param arg0 the message + */ + public static void audit(String className, Object arg0) { + MDC.put(STATUS_CODE, COMPLETE_STATUS); + MDC.put(classNameProp, className); + auditLogger.info("" + arg0); + } + + /** + * Records only one String message. + * + * @param arg0 the message + */ + public static void audit(Object arg0) { + MDC.put(STATUS_CODE, COMPLETE_STATUS); + MDC.put(classNameProp, ""); + auditLogger.info("" + arg0); + } + + /** + * returns true for enabled, false for not enabled. + */ + public static boolean isDebugEnabled() { + + return debugLogger.isDebugEnabled(); + } + + /** + * returns true for enabled, false for not enabled. + */ + public static boolean isErrorEnabled() { + + return errorLogger.isErrorEnabled(); + } + + /** + * returns true for enabled, false for not enabled. + */ + public static boolean isWarnEnabled() { + + return debugLogger.isWarnEnabled(); + } + + /** + * returns true for enabled, false for not enabled. + */ + public static boolean isInfoEnabled1() { + + return debugLogger.isInfoEnabled(); + } + + /** + * returns true for enabled, false for not enabled. + */ + public static boolean isAuditEnabled() { + + return debugLogger.isInfoEnabled(); + } + + /** + * returns true for enabled, false for not enabled. + */ + public static boolean isInfoEnabled() { + + return debugLogger.isInfoEnabled(); + } + + /** + * Records only one String message with its class name. + * + * @param className the class name + * @param arg0 the message + */ + public static void trace(String className, String arg0) { + MDC.put(classNameProp, className); + debugLogger.trace(MessageCodes.GENERAL_INFO, arg0); + } + + /** + * Records only one String message. + * + * @param arg0 the message + */ + public static void trace(Object arg0) { + + MDC.put(classNameProp, ""); + debugLogger.trace("" + arg0); + } + + /** + * Records the starting time of the event with its request Id as the key. + * + * @param eventId the event ID + */ + public static void recordAuditEventStart(String eventId) { + + MDC.put(STATUS_CODE, COMPLETE_STATUS); + postMDCInfoForEvent(eventId); + + if (eventTracker == null) { + eventTracker = new EventTrackInfo(); + } + EventData event = new EventData(); + event.setRequestID(eventId); + event.setStartTime(Instant.now()); + eventTracker.storeEventData(event); + MDC.put(MDC_KEY_REQUEST_ID, eventId); + debugLogger.info("CONCURRENTHASHMAP_LIMIT : " + concurrentHashMapLimit); + // --- Tracking the size of the concurrentHashMap, if it is above limit, keep EventTrack + // Timer running + int size = eventTracker.getEventInfo().size(); + + debugLogger.info("EventInfo concurrentHashMap Size : " + size + " on " + new Date()); + debugLogger.info("isEventTrackerRunning : " + isEventTrackerRunning); + + if (size >= concurrentHashMapLimit) { + + + if (!isEventTrackerRunning) { + + startCleanUp(); + isEventTrackerRunning = true; + } + + } else if (size <= stopCheckPoint && isEventTrackerRunning) { + + stopCleanUp(); + } + } + + /** + * Records the starting time of the event with its request Id as the key. + * + * @param eventId the event ID + */ + public static void recordAuditEventStart(UUID eventId) { + + if (eventId == null) { + return; + } + + if (eventTracker == null) { + eventTracker = new EventTrackInfo(); + } + + recordAuditEventStart(eventId.toString()); + + } + + /** + * Records the ending time of the event with its request Id as the key. + * + * @param eventId the event ID + * @param rule the rule + */ + public static void recordAuditEventEnd(String eventId, String rule) { + + if (eventTracker == null) { + return; + } + if (eventId == null) { + return; + } + + creatAuditEventTrackingRecord(eventId, rule, ""); + + } + + /** + * Records the ending time of the event with its request Id as the key. + * + * @param eventId the event ID + * @param rule the rule + * @param policyVersion the policy version + */ + public static void recordAuditEventEnd(String eventId, String rule, String policyVersion) { + + if (eventTracker == null) { + return; + } + if (eventId == null) { + return; + } + + creatAuditEventTrackingRecord(eventId, rule, policyVersion); + + } + + /** + * Records the ending time of the event with its request Id as the key. + * + * @param eventId the event ID + * @param rule the rule + * @param policyVersion the policy version + */ + public static void recordAuditEventEnd(UUID eventId, String rule, String policyVersion) { + + if (eventId == null) { + return; + } + + recordAuditEventEnd(eventId.toString(), rule, policyVersion); + + } + + + /** + * Records the ending time of the event with its request Id as the key. + * + * @param eventId the event ID + * @param rule the rule + */ + public static void recordAuditEventEnd(UUID eventId, String rule) { + + if (eventId == null) { + return; + } + + recordAuditEventEnd(eventId.toString(), rule); + + } + + /** + * Records the ending time of the event with its request Id as the key. + * + * @param eventId the event ID + * @param rule the rule + * @param policyVersion the policy version + */ + public static void creatAuditEventTrackingRecord(String eventId, String rule, String policyVersion) { + + if (eventTracker == null) { + return; + } + + EventData event = eventTracker.getEventDataByRequestID(eventId); + + if (event != null) { + Instant endTime = event.getEndTime(); + if (endTime == null) { + endTime = Instant.now(); + } + MDC.put(STATUS_CODE, COMPLETE_STATUS); + recordAuditEventStartToEnd(eventId, rule, event.getStartTime(), endTime, policyVersion); + } + } + + /** + * Records the ending time of the event with its request Id as the key. + * + * @param eventId the event ID + * @param rule the rule + */ + public static void creatAuditEventTrackingRecord(UUID eventId, String rule) { + + if (eventId == null) { + return; + } + + if (eventTracker == null) { + return; + } + + EventData event = eventTracker.getEventDataByRequestID(eventId.toString()); + + if (event != null) { + Instant endTime = event.getEndTime(); + if (endTime == null) { + endTime = Instant.now(); + } + + recordAuditEventStartToEnd(eventId.toString(), rule, event.getStartTime(), endTime, "N/A"); + } + } + + public static EventTrackInfo getEventTracker() { + return eventTracker; + } + + /** + * Records the audit with an event starting and ending times. + * + * @param eventId the event ID + * @param rule the rule + * @param startTime the start time + * @param endTime the end time + * @param policyVersion the policy version + */ + public static void recordAuditEventStartToEnd(String eventId, String rule, Instant startTime, Instant endTime, + String policyVersion) { + + if (startTime == null || endTime == null) { + return; + } + if (eventId != null && !eventId.isEmpty()) { + MDC.put(MDC_KEY_REQUEST_ID, eventId); + } + + SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); + + String formatedTime = sdf.format(Date.from(startTime)); + MDC.put(BEGIN_TIME_STAMP, formatedTime); + + // set default values for these required fields below, they can be overridden + formatedTime = sdf.format(Date.from(endTime)); + MDC.put(END_TIME_STAMP, formatedTime); + + MDC.put(RESPONSE_CODE, "N/A"); + MDC.put(RESPONSE_DESCRIPTION, "N/A"); + + long ns = Duration.between(startTime, endTime).toMillis(); + + MDC.put(ELAPSED_TIME, Long.toString(ns)); + + auditLogger.info(MessageCodes.RULE_AUDIT_START_END_INFO, MDC.get(MDC_SERVICE_NAME), rule, startTime.toString(), + endTime.toString(), Long.toString(ns), policyVersion); + + // --- remove the record from the concurrentHashMap + if (eventTracker != null && eventTracker.getEventDataByRequestID(eventId) != null) { + + eventTracker.remove(eventId); + debugLogger.info("eventTracker.remove(" + eventId + ")"); + + } + } + + /** + * Records the metrics with an event Id and log message. + * + * @param eventId the event ID + * @param arg1 the message + */ + public static void recordMetricEvent(String eventId, String arg1) { + + seTimeStamps(); + + String serviceName = MDC.get(MDC_SERVICE_NAME); + MDC.put(MDC_KEY_REQUEST_ID, eventId); + metricsLogger.info(MessageCodes.RULE_AUDIT_END_INFO, serviceName, arg1); + + } + + /** + * Records the metrics with an event Id, class name and log message. + * + * @param eventId the event ID + * @param className the class name + * @param arg1 the message + */ + public static void recordMetricEvent(String eventId, String className, String arg1) { + + seTimeStamps(); + + MDC.put(classNameProp, className); + String serviceName = MDC.get(MDC_SERVICE_NAME); + MDC.put(MDC_KEY_REQUEST_ID, eventId); + metricsLogger.info(MessageCodes.RULE_AUDIT_END_INFO, serviceName, arg1); + } + + /** + * Records the metrics with an event Id and log message. + * + * @param eventId the event ID + * @param arg1 the message + */ + public static void recordMetricEvent(UUID eventId, String arg1) { + + if (eventId == null) { + return; + } + String serviceName = MDC.get(MDC_SERVICE_NAME); + MDC.put(MDC_KEY_REQUEST_ID, eventId.toString()); + metricsLogger.info(MessageCodes.RULE_AUDIT_END_INFO, serviceName, arg1); + } + + /** + * Records a String message for metrics logs. + * + * @param arg0 the message + */ + public static void recordMetricEvent(String arg0) { + seTimeStamps(); + String serviceName = MDC.get(MDC_SERVICE_NAME); + metricsLogger.info(MessageCodes.RULE_METRICS_INFO, serviceName, arg0); + } + + + /** + * Records the metrics event with a String message. + * + * @param arg0 the message + */ + public static void metrics(String arg0) { + String serviceName = MDC.get(MDC_SERVICE_NAME); + metricsLogger.info(MessageCodes.RULE_METRICS_INFO, serviceName, arg0); + } + + /** + * Records the metrics event with a class name and a String message. + * + * @param arg0 the message + */ + public static void metrics(String className, Object arg0) { + seTimeStamps(); + MDC.put(classNameProp, className); + String serviceName = MDC.get(MDC_SERVICE_NAME); + metricsLogger.info(MessageCodes.RULE_METRICS_INFO, serviceName, "" + arg0); + } + + /** + * Records the metrics event with a String message. + * + * @param arg0 the message + */ + public static void metrics(Object arg0) { + seTimeStamps(); + MDC.put(classNameProp, ""); + String serviceName = MDC.get(MDC_SERVICE_NAME); + metricsLogger.info(MessageCodes.RULE_METRICS_INFO, serviceName, "" + arg0); + } + + /** + * Records the metrics event with a String message. + * + * @param arg0 the message + */ + public static void metricsPrintln(String arg0) { + MDC.clear(); + metricsLogger.info(arg0); + } + + /** + * Removes all the return lines from the printStackTrace. + * + * @param throwable the throwable + * @param arguments the messages + */ + private static String getNormalizedStackTrace(Throwable throwable, String... arguments) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); - t.printStackTrace(pw); - String newStValue = sw.toString().replace ('|', '!').replace ("\n", " - "); + throwable.printStackTrace(pw); + String newStValue = sw.toString().replace('|', '!').replace("\n", " - "); int curSize = arguments == null ? 0 : arguments.length; StringBuilder newArgument = new StringBuilder(); - for(int i=0; i<curSize; i++) { - newArgument.append(arguments[i]); - newArgument.append(":"); + for (int i = 0; i < curSize; i++) { + newArgument.append(arguments[i]); + newArgument.append(":"); + } + newArgument.append(newStValue); + return newArgument.toString(); + } + + /** + * Starts the process of cleaning up the ConcurrentHashMap of EventData. + */ + private static void startCleanUp() { + + if (!isEventTrackerRunning) { + ttrcker = new EventTrackInfoHandler(); + timer = new Timer(true); + timer.scheduleAtFixedRate(ttrcker, timerDelayTime, checkInterval); + debugLogger.info("EventTrackInfoHandler begins! : " + new Date()); + } else { + debugLogger.info("Timer is still running : " + new Date()); + + } + } + + + /** + * Stops the process of cleaning up the ConcurrentHashMap of EventData. + */ + private static void stopCleanUp() { + + if (isEventTrackerRunning && timer != null) { + timer.cancel(); + timer.purge(); + debugLogger.info("Timer stopped: " + new Date()); + } else { + debugLogger.info("Timer was already stopped : " + new Date()); + } - newArgument.append(newStValue); - return newArgument.toString(); - } - - /** - * Starts the process of cleaning up the ConcurrentHashMap of EventData - */ - private static void startCleanUp(){ - - if(!isEventTrackerRunning) { - ttrcker = new EventTrackInfoHandler(); - timer = new Timer(true); - timer.scheduleAtFixedRate(ttrcker, timerDelayTime, checkInterval); - debugLogger.info("EventTrackInfoHandler begins! : " + new Date()); - }else{ - debugLogger.info("Timer is still running : " + new Date()); - - } - } - - - /** - * Stops the process of cleaning up the ConcurrentHashMap of EventData - */ - private static void stopCleanUp(){ - - if(isEventTrackerRunning && timer != null){ - timer.cancel(); - timer.purge(); - debugLogger.info("Timer stopped: " + new Date()); - }else{ - debugLogger.info("Timer was already stopped : " + new Date()); - - } - isEventTrackerRunning = false; - - } - - /** - * Loads all the attributes from policyLogger.properties file - */ - public static LoggerType init(Properties properties) { - - Properties loggerProperties; - if (properties != null) { - loggerProperties = properties; - } else { - System.err.println("PolicyLogger cannot find its configuration - continue"); - loggerProperties = new Properties(); - } - - LoggerType loggerType = LoggerType.EELF; - - // fetch and verify definitions of some properties - try{ - - int timerDelayTimeProp = Integer.parseInt(loggerProperties.getProperty("timer.delay.time", Integer.toString(1000))); - int checkIntervalProp = Integer.parseInt(loggerProperties.getProperty("check.interval", Integer.toString(30000))); - int expiredDateProp = Integer.parseInt(loggerProperties.getProperty("event.expired.time", Integer.toString(86400))); - int concurrentHashMapLimitProp = Integer.parseInt(loggerProperties.getProperty("concurrentHashMap.limit", Integer.toString(5000))); - int stopCheckPointProp = Integer.parseInt(loggerProperties.getProperty("stop.check.point", Integer.toString(2500))); - String loggerTypeProp = loggerProperties.getProperty("logger.type",loggerType.toString()); - - String debugLevelProp = loggerProperties.getProperty("debugLogger.level","INFO"); - String metricsLevelProp = loggerProperties.getProperty("metricsLogger.level","ON"); - String auditLevelProp = loggerProperties.getProperty("audit.level","ON"); - String errorLevelProp = loggerProperties.getProperty("error.level","ON"); - component = loggerProperties.getProperty("policy.component","DROOLS"); - String overrideLogbackLevel = loggerProperties.getProperty("override.logback.level.setup"); - - if(overrideLogbackLevel != null && !overrideLogbackLevel.isEmpty()) { - if("TRUE".equalsIgnoreCase(overrideLogbackLevel)){ - isOverrideLogbackLevel = true; - }else{ - isOverrideLogbackLevel = false; - } - } - - - if (debugLevelProp != null && !debugLevelProp.isEmpty()){ - - PolicyLogger.setDebugLevel(Level.valueOf(debugLevelProp)); - - } - //Only check if it is to turn off or not - if (errorLevelProp != null && errorLevelProp.equalsIgnoreCase(Level.OFF.toString())){ - - PolicyLogger.setErrorLevel(Level.valueOf(errorLevelProp)); - - } - //Only check if it is to turn off or not - if (metricsLevelProp != null && metricsLevelProp.equalsIgnoreCase(Level.OFF.toString())){ - - PolicyLogger.setMetricsLevel(Level.valueOf(metricsLevelProp)); - - } - //Only check if it is to turn off or not - if (auditLevelProp != null && auditLevelProp.equalsIgnoreCase(Level.OFF.toString())){ - - PolicyLogger.setAuditLevel(Level.valueOf(auditLevelProp)); - - } - - if(isOverrideLogbackLevel){ - - debugLogger.setLevel(debugLevel); - metricsLogger.setLevel(metricsLevel); - auditLogger.setLevel(auditLevel); - errorLogger.setLevel(errorLevel); - + isEventTrackerRunning = false; + + } + + /** + * Loads all the attributes from policyLogger.properties file + */ + public static LoggerType init(Properties properties) { + + Properties loggerProperties; + if (properties != null) { + loggerProperties = properties; + } else { + System.err.println("PolicyLogger cannot find its configuration - continue"); + loggerProperties = new Properties(); + } + + LoggerType loggerType = LoggerType.EELF; + + // fetch and verify definitions of some properties + try { + + final int timerDelayTimeProp = + Integer.parseInt(loggerProperties.getProperty("timer.delay.time", Integer.toString(1000))); + final int checkIntervalProp = + Integer.parseInt(loggerProperties.getProperty("check.interval", Integer.toString(30000))); + final int expiredDateProp = + Integer.parseInt(loggerProperties.getProperty("event.expired.time", Integer.toString(86400))); + final int concurrentHashMapLimitProp = + Integer.parseInt(loggerProperties.getProperty("concurrentHashMap.limit", Integer.toString(5000))); + final int stopCheckPointProp = + Integer.parseInt(loggerProperties.getProperty("stop.check.point", Integer.toString(2500))); + final String loggerTypeProp = loggerProperties.getProperty("logger.type", loggerType.toString()); + + final String debugLevelProp = loggerProperties.getProperty("debugLogger.level", "INFO"); + final String metricsLevelProp = loggerProperties.getProperty("metricsLogger.level", "ON"); + final String auditLevelProp = loggerProperties.getProperty("audit.level", "ON"); + final String errorLevelProp = loggerProperties.getProperty("error.level", "ON"); + component = loggerProperties.getProperty("policy.component", "DROOLS"); + final String overrideLogbackLevel = loggerProperties.getProperty("override.logback.level.setup"); + + if (overrideLogbackLevel != null && !overrideLogbackLevel.isEmpty()) { + if ("TRUE".equalsIgnoreCase(overrideLogbackLevel)) { + isOverrideLogbackLevel = true; + } else { + isOverrideLogbackLevel = false; + } + } + + + if (debugLevelProp != null && !debugLevelProp.isEmpty()) { + + PolicyLogger.setDebugLevel(Level.valueOf(debugLevelProp)); + + } + // Only check if it is to turn off or not + if (errorLevelProp != null && errorLevelProp.equalsIgnoreCase(Level.OFF.toString())) { + + PolicyLogger.setErrorLevel(Level.valueOf(errorLevelProp)); + + } + // Only check if it is to turn off or not + if (metricsLevelProp != null && metricsLevelProp.equalsIgnoreCase(Level.OFF.toString())) { + + PolicyLogger.setMetricsLevel(Level.valueOf(metricsLevelProp)); + + } + // Only check if it is to turn off or not + if (auditLevelProp != null && auditLevelProp.equalsIgnoreCase(Level.OFF.toString())) { + + PolicyLogger.setAuditLevel(Level.valueOf(auditLevelProp)); + + } + + if (isOverrideLogbackLevel) { + + debugLogger.setLevel(debugLevel); + metricsLogger.setLevel(metricsLevel); + auditLogger.setLevel(auditLevel); + errorLogger.setLevel(errorLevel); + } - isEventTrackerRunning = false; - - debugLogger.info("timerDelayTime value: " + timerDelayTimeProp); - - debugLogger.info("checkInterval value: " + checkIntervalProp); - - debugLogger.info("expiredDate value: " + expiredDateProp); - - debugLogger.info("concurrentHashMapLimit value: " + concurrentHashMapLimitProp); - - debugLogger.info("loggerType value: " + loggerTypeProp); - - debugLogger.info("debugLogger level: " + debugLevelProp); - - debugLogger.info("component: " + component); - - if (timerDelayTimeProp > 0){ - - timerDelayTime = timerDelayTimeProp; - - }else { - MDC.put(ERROR_CATEGORY, ERROR_CATEGORY_VALUE); - if(ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR) != null){ - MDC.put(ERROR_CODE, ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR).getErrorCode()); - MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR).getErrorDesc()); - - } - errorLogger.error("failed to get the timer.delay.time, so use its default value: " + timerDelayTime); - } - - if (checkIntervalProp > 0){ - - checkInterval = checkIntervalProp; - - }else { - MDC.put(ERROR_CATEGORY, ERROR_CATEGORY_VALUE); - if(ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR) != null){ - MDC.put(ERROR_CODE, ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR).getErrorCode()); - MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR).getErrorDesc()); - - } - errorLogger.error("failed to get the check.interval, so use its default value: " + checkInterval); - } - - if (expiredDateProp > 0){ - - expiredTime = expiredDateProp; - - }else { - MDC.put(ERROR_CATEGORY, ERROR_CATEGORY_VALUE); - - if(ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR) != null){ - MDC.put(ERROR_CODE, ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR).getErrorCode()); - MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR).getErrorDesc()); - - } - errorLogger.error("failed to get the event.expired.time, so use its default value: " + expiredTime); - } - - if (concurrentHashMapLimitProp > 0){ - - concurrentHashMapLimit = concurrentHashMapLimitProp; - - }else { - MDC.put(ERROR_CATEGORY, ERROR_CATEGORY_VALUE); - if(ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR) != null){ - MDC.put(ERROR_CODE, ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR).getErrorCode()); - MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR).getErrorDesc()); - - } - errorLogger.error("failed to get the concurrentHashMap.limit, so use its default value: " + concurrentHashMapLimit); - } - - if (stopCheckPointProp > 0){ - - stopCheckPoint = stopCheckPointProp; - - }else { - MDC.put(ERROR_CATEGORY, ERROR_CATEGORY_VALUE); - if(ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR) != null){ - MDC.put(ERROR_CODE, ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR).getErrorCode()); - MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR).getErrorDesc()); - - } - errorLogger.error("failed to get the stop.check.point, so use its default value: " + stopCheckPoint); - } - - if (loggerTypeProp != null){ - - if ("EELF".equalsIgnoreCase(loggerTypeProp)){ - - loggerType = LoggerType.EELF; - - }else if ("LOG4J".equalsIgnoreCase(loggerTypeProp)){ - - loggerType = LoggerType.LOG4J; - - }else if ("SYSTEMOUT".equalsIgnoreCase(loggerTypeProp)){ - - loggerType = LoggerType.SYSTEMOUT; - - } - - } - - if (debugLevelProp != null && !debugLevelProp.isEmpty()){ - - debugLevel = Level.valueOf(debugLevelProp); - - } - //Only check if it is to turn off or not - if (errorLevelProp != null && errorLevelProp.equalsIgnoreCase(Level.OFF.toString())){ - - errorLevel = Level.valueOf(errorLevelProp); - - } - //Only check if it is to turn off or not - if (metricsLevelProp != null && metricsLevelProp.equalsIgnoreCase(Level.OFF.toString())){ - - metricsLevel = Level.valueOf(metricsLevelProp); - - } - //Only check if it is to turn off or not - if (auditLevelProp != null && auditLevelProp.equalsIgnoreCase(Level.OFF.toString())){ - - auditLevel = Level.valueOf(auditLevelProp); - - } - - }catch(Exception e){ - MDC.put(ERROR_CATEGORY, ERROR_CATEGORY_VALUE); - - if(ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR) != null){ - MDC.put(ERROR_CODE, ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR).getErrorCode()); - MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR).getErrorDesc()); - - } - errorLogger.error("failed to get the policyLogger.properties, so use their default values",e); - } - - return loggerType; - - } - - /** - * Sets Debug Level - */ - public static void setDebugLevel(String newDebugLevel){ - - if(isOverrideLogbackLevel){ - PolicyLogger.debugLevel = Level.valueOf(newDebugLevel); - debugLogger.setLevel(debugLevel); - } - - } - - /** - * Sets Error OFF or ON - */ - public static void setErrorLevel(String newErrorLevel){ - - if(isOverrideLogbackLevel){ - if("OFF".equalsIgnoreCase(newErrorLevel)){ - PolicyLogger.errorLevel = Level.OFF; - errorLogger.setLevel(errorLevel); - }else{ - //--- set default value - errorLogger.setLevel(Level.ERROR); - PolicyLogger.errorLevel = Level.ERROR; - } - } - } - - /** - * Sets Metrics OFF or ON - */ - public static void setMetricsLevel(String newMetricsLevel){ - - if(isOverrideLogbackLevel){ - if("OFF".equalsIgnoreCase(newMetricsLevel)){ - PolicyLogger.metricsLevel = Level.OFF; - metricsLogger.setLevel(metricsLevel); - }else { - //--- set default value - metricsLogger.setLevel(Level.INFO); - PolicyLogger.metricsLevel = Level.INFO; - } - } - - } - - /** - * Sets Audit OFF or ON - */ - public static void setAuditLevel(String newAuditLevel){ - - if(isOverrideLogbackLevel){ - if("OFF".equalsIgnoreCase(newAuditLevel)){ - PolicyLogger.auditLevel = Level.OFF; - auditLogger.setLevel(auditLevel); - }else { - //--- set default value - auditLogger.setLevel(Level.INFO); - PolicyLogger.auditLevel = Level.INFO; - } - } - } - - /** - * Returns true for overriding logback levels; returns false for not - */ - public static boolean isOverrideLogbackLevel(){ - - return isOverrideLogbackLevel; - } - - /** - * Sets true for overriding logback levels; sets false for not - */ - public static void setOverrideLogbackLevel(boolean odl){ - - isOverrideLogbackLevel = odl; - - } - /** - * Sets server information to MDC - */ - public static void setServerInfo(String serverHost, String serverPort){ - MDC.put(SERVER_NAME, serverHost+":"+serverPort); - } + isEventTrackerRunning = false; + + debugLogger.info("timerDelayTime value: " + timerDelayTimeProp); + + debugLogger.info("checkInterval value: " + checkIntervalProp); + + debugLogger.info("expiredDate value: " + expiredDateProp); + + debugLogger.info("concurrentHashMapLimit value: " + concurrentHashMapLimitProp); + + debugLogger.info("loggerType value: " + loggerTypeProp); + + debugLogger.info("debugLogger level: " + debugLevelProp); + + debugLogger.info("component: " + component); + + if (timerDelayTimeProp > 0) { + + timerDelayTime = timerDelayTimeProp; + + } else { + MDC.put(ERROR_CATEGORY, ERROR_CATEGORY_VALUE); + if (ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR) != null) { + MDC.put(ERROR_CODE, ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR).getErrorCode()); + MDC.put(ERROR_DESCRIPTION, + ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR).getErrorDesc()); + + } + errorLogger.error("failed to get the timer.delay.time, so use its default value: " + timerDelayTime); + } + + if (checkIntervalProp > 0) { + + checkInterval = checkIntervalProp; + + } else { + MDC.put(ERROR_CATEGORY, ERROR_CATEGORY_VALUE); + if (ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR) != null) { + MDC.put(ERROR_CODE, ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR).getErrorCode()); + MDC.put(ERROR_DESCRIPTION, + ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR).getErrorDesc()); + + } + errorLogger.error("failed to get the check.interval, so use its default value: " + checkInterval); + } + + if (expiredDateProp > 0) { + + expiredTime = expiredDateProp; + + } else { + MDC.put(ERROR_CATEGORY, ERROR_CATEGORY_VALUE); + + if (ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR) != null) { + MDC.put(ERROR_CODE, ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR).getErrorCode()); + MDC.put(ERROR_DESCRIPTION, + ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR).getErrorDesc()); + + } + errorLogger.error("failed to get the event.expired.time, so use its default value: " + expiredTime); + } + + if (concurrentHashMapLimitProp > 0) { + + concurrentHashMapLimit = concurrentHashMapLimitProp; + + } else { + MDC.put(ERROR_CATEGORY, ERROR_CATEGORY_VALUE); + if (ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR) != null) { + MDC.put(ERROR_CODE, ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR).getErrorCode()); + MDC.put(ERROR_DESCRIPTION, + ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR).getErrorDesc()); + + } + errorLogger.error("failed to get the concurrentHashMap.limit, so use its default value: " + + concurrentHashMapLimit); + } + + if (stopCheckPointProp > 0) { + + stopCheckPoint = stopCheckPointProp; + + } else { + MDC.put(ERROR_CATEGORY, ERROR_CATEGORY_VALUE); + if (ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR) != null) { + MDC.put(ERROR_CODE, ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR).getErrorCode()); + MDC.put(ERROR_DESCRIPTION, + ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR).getErrorDesc()); + + } + errorLogger.error("failed to get the stop.check.point, so use its default value: " + stopCheckPoint); + } + + if (loggerTypeProp != null) { + + if ("EELF".equalsIgnoreCase(loggerTypeProp)) { + + loggerType = LoggerType.EELF; + + } else if ("LOG4J".equalsIgnoreCase(loggerTypeProp)) { + + loggerType = LoggerType.LOG4J; + + } else if ("SYSTEMOUT".equalsIgnoreCase(loggerTypeProp)) { + + loggerType = LoggerType.SYSTEMOUT; + + } + + } + + if (debugLevelProp != null && !debugLevelProp.isEmpty()) { + + debugLevel = Level.valueOf(debugLevelProp); + + } + // Only check if it is to turn off or not + if (errorLevelProp != null && errorLevelProp.equalsIgnoreCase(Level.OFF.toString())) { + + errorLevel = Level.valueOf(errorLevelProp); + + } + // Only check if it is to turn off or not + if (metricsLevelProp != null && metricsLevelProp.equalsIgnoreCase(Level.OFF.toString())) { + + metricsLevel = Level.valueOf(metricsLevelProp); + + } + // Only check if it is to turn off or not + if (auditLevelProp != null && auditLevelProp.equalsIgnoreCase(Level.OFF.toString())) { + + auditLevel = Level.valueOf(auditLevelProp); + + } + + } catch (Exception e) { + MDC.put(ERROR_CATEGORY, ERROR_CATEGORY_VALUE); + + if (ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR) != null) { + MDC.put(ERROR_CODE, ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR).getErrorCode()); + MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR).getErrorDesc()); + + } + errorLogger.error("failed to get the policyLogger.properties, so use their default values", e); + } + + return loggerType; + + } + + + /** + * Returns true for overriding logback levels; returns false for not. + */ + public static boolean isOverrideLogbackLevel() { + + return isOverrideLogbackLevel; + } + + /** + * Sets true for overriding logback levels; sets false for not. + */ + public static void setOverrideLogbackLevel(boolean odl) { + + isOverrideLogbackLevel = odl; + + } + + /** + * Sets server information to MDC. + */ + public static void setServerInfo(String serverHost, String serverPort) { + MDC.put(SERVER_NAME, serverHost + ":" + serverPort); + } } diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/EelfLogger.java b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/EelfLogger.java index 07ef5626..e0c4144b 100644 --- a/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/EelfLogger.java +++ b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/EelfLogger.java @@ -20,461 +20,498 @@ package org.onap.policy.common.logging.flexlogger; +import com.att.eelf.configuration.EELFLogger.Level; + import java.io.Serializable; import java.util.UUID; import org.onap.policy.common.logging.eelf.MessageCodes; import org.onap.policy.common.logging.eelf.PolicyLogger; -import org.onap.policy.common.logging.flexlogger.Logger; -import com.att.eelf.configuration.EELFLogger.Level; /** - * - * EelfLogger implements all the methods of interface Logger by calling PolicyLogger methods - * + * EelfLogger implements all the methods of interface Logger by calling PolicyLogger methods. */ public class EelfLogger implements Logger, Serializable { - - /** - * - */ - private static final long serialVersionUID = 5385586713941277192L; - private String className = ""; + + private static final long serialVersionUID = 5385586713941277192L; + private String className = ""; private String transId = UUID.randomUUID().toString(); - - /** - * Constructor - * @param clazz - */ - public EelfLogger(Class<?> clazz) { - if(clazz != null){ - className = clazz.getName(); - } - PolicyLogger.postMDCInfoForEvent(null); - } - - /** - * Constructor - * @param s - */ - public EelfLogger(String s) { - if(s != null){ - className = s; - } - PolicyLogger.postMDCInfoForEvent(null); - } - - /** - * Constructor - * @param clazz - * @param isNewTransaction - */ - public EelfLogger(Class<?> clazz, boolean isNewTransaction) { - if(clazz != null){ - className = clazz.getName(); - } - if(isNewTransaction){ - transId = PolicyLogger.postMDCInfoForEvent(null); - }else{ - transId = PolicyLogger.getTransId(); - } - } - - /** - * Constructor - * @param s - * @param isNewTransaction - */ - public EelfLogger(String s, boolean isNewTransaction) { - if(s != null){ - className = s; - } - if(isNewTransaction){ - transId = PolicyLogger.postMDCInfoForEvent(null); - }else{ - transId = PolicyLogger.getTransId(); - } - } - - /** - * Constructor - * @param clazz - * @param transId - */ - public EelfLogger(Class<?> clazz, String transId) { - if(clazz != null){ - className = clazz.getName(); - } - PolicyLogger.postMDCInfoForEvent(transId); - this.transId = transId; - } - - /** - * Constructor - * @param s - * @param transId - */ - public EelfLogger(String s, String transId) { - if(s != null){ - className = s; - } - PolicyLogger.postMDCInfoForEvent(transId); - this.transId = transId; - } - - /** - * Sets transaction Id for logging - * @param transId - */ - @Override - public void setTransId(String transId){ - - PolicyLogger.setTransId(transId); - this.transId = transId; - } - - /** - * Returns transaction Id for logging - */ - @Override - public String getTransId(){ - return transId; - } - - /** - * Records a message - * @param message - */ - @Override - public void debug(Object message) { - PolicyLogger.debug(className, ""+message); - } - - /** - * Records an error message - * @param message - */ - @Override - public void error(Object message) { - PolicyLogger.error(className, ""+message); - } - - /** - * Records a message - * @param message - */ - @Override - public void info(Object message) { - PolicyLogger.info(className, ""+message); - } - - /** - * Records a message - * @param message - */ - @Override - public void warn(Object message) { - PolicyLogger.warn(className, ""+message); - } - - /** - * Records a message - * @param message - */ - @Override - public void trace(Object message) { - PolicyLogger.trace(className, ""+message); - } - - /** - * Returns true for debug enabled, or false for not - * @return boolean - */ - @Override - public boolean isDebugEnabled(){ - return PolicyLogger.isDebugEnabled(); - } - - /** - * Returns true for info enabled, or false for not - * @return boolean - */ - @Override - public boolean isInfoEnabled(){ - return PolicyLogger.isInfoEnabled(); - } - - /** - * Returns true for warn enabled, or false for not - * @return boolean - */ - @Override - public boolean isWarnEnabled(){ - return PolicyLogger.isWarnEnabled(); - } - - /** - * Returns true for error enabled, or false for not - * @return boolean - */ - @Override - public boolean isErrorEnabled(){ - return PolicyLogger.isErrorEnabled(); - } - - /** - * Returns true for audit enabled, or false for not - * @return boolean - */ - @Override - public boolean isAuditEnabled(){ - return(PolicyLogger.getAuditLevel() != Level.OFF); - } - - /** - * Returns true for metrics enabled, or false for not - * @return boolean - */ - @Override - public boolean isMetricsEnabled(){ - return(PolicyLogger.getMetricsLevel() != Level.OFF); - } - - /** - * Returns true for trace enabled, or false for not - * @return boolean - */ - @Override - public boolean isTraceEnabled(){ - return PolicyLogger.isDebugEnabled(); - } - - /** - * Records an audit message - * @param arg0 - */ - @Override - public void audit(Object arg0) { - PolicyLogger.audit(className, ""+ arg0); - } - - /** - * Records a message - * @param message - * @param t - */ - @Override - public void debug(Object message, Throwable t) { - PolicyLogger.debug(MessageCodes.GENERAL_INFO, t, message.toString()); - } - - /** - * Records an error message - * @param message - * @param t - */ - @Override - public void error(Object message, Throwable t) { - PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, t, message.toString()); - } - - /** - * Records a message - * @param message - * @param t - */ - @Override - public void info(Object message, Throwable t) { - PolicyLogger.info(MessageCodes.GENERAL_INFO, t, message.toString()); - } - - /** - * Records a message - * @param message - * @param t - */ - @Override - public void warn(Object message, Throwable t) { - PolicyLogger.warn(MessageCodes.GENERAL_WARNING, t, message.toString()); - } - - /** - * Records a message - * @param message - * @param t - */ - @Override - public void trace(Object message, Throwable t) { - PolicyLogger.trace(message); - } - - /** - * Records an audit message - * @param arg0 - * @param t - */ - @Override - public void audit(Object arg0, Throwable t) { - PolicyLogger.audit(arg0); - } - - /** - * Records an audit message - * @param eventId - */ - @Override - public void recordAuditEventStart(String eventId) { - PolicyLogger.recordAuditEventStart(eventId); - } - - /** - * Records an audit message - * @param eventId - */ - @Override - public void recordAuditEventStart(UUID eventId) { - PolicyLogger.recordAuditEventStart(eventId); - } - - /** - * Records an audit message - * @param eventId - * @param rule - * @param policyVersion - */ - @Override - public void recordAuditEventEnd(String eventId, String rule, String policyVersion) { - PolicyLogger.recordAuditEventEnd(eventId, rule, policyVersion); - } - - /** - * Records an audit message - * @param eventId - * @param rule - * @param policyVersion - */ - @Override - public void recordAuditEventEnd(UUID eventId, String rule, String policyVersion) { - PolicyLogger.recordAuditEventEnd(eventId, rule, policyVersion); - } - - /** - * Records an audit message - * @param eventId - * @param rule - */ - @Override - public void recordAuditEventEnd(String eventId, String rule) { - PolicyLogger.recordAuditEventEnd(eventId, rule); - } - - /** - * Records an audit message - * @param eventId - * @param rule - */ - @Override - public void recordAuditEventEnd(UUID eventId, String rule) { - PolicyLogger.recordAuditEventEnd(eventId, rule); - } - - /** - * Records a metrics message - * @param eventId - * @param arg1 - */ - @Override - public void recordMetricEvent(String eventId, String arg1) { - PolicyLogger.recordMetricEvent(eventId, arg1); - } - - /** - * Records a metrics message - * @param eventId - * @param arg1 - */ - @Override - public void recordMetricEvent(UUID eventId, String arg1) { - PolicyLogger.recordMetricEvent(eventId, arg1); - } - - /** - * Records a metrics message - * @param arg0 - */ - @Override - public void metrics(Object arg0) { - PolicyLogger.metrics(className, arg0); - } - - /** - * Records an error message - * @param msg - * @param arg0 - * @param arguments - */ - @Override - public void error(MessageCodes msg, Throwable arg0, String... arguments){ - PolicyLogger.error(msg, className, arg0, arguments); - } - - /** - * Records an error message - * @param msg - * @param arguments - */ - @Override - public void error(MessageCodes msg, String... arguments){ - PolicyLogger.error(msg, arguments); - } - - /** - * Populates MDC Info - * @param transId - */ - @Override - public String postMDCInfoForEvent(String transId) { - return PolicyLogger.postMDCInfoForEvent(transId); - - } - - /** - * Records a message - * @param msg - * @param arguments - */ - @Override - public void warn(MessageCodes msg, String... arguments){ - PolicyLogger.warn(msg, className, arguments); - } - - /** - * Records a message - * @param msg - * @param arg0 - * @param arguments - */ - @Override - public void warn(MessageCodes msg, Throwable arg0, String... arguments){ - PolicyLogger.warn(msg, className, arg0, arguments); - } - - /** - * Populates MDC Info for the rule triggered - * @param transId - */ - @Override - public void postMDCInfoForTriggeredRule(String transId){ - PolicyLogger.postMDCInfoForTriggeredRule(transId); - } - - /** - * Populates MDC Info - * @param o - */ - @Override - public void postMDCInfoForEvent(Object o){ - PolicyLogger.postMDCInfoForEvent(o); - } + + /** + * Constructor. + * + * @param clazz the class + */ + public EelfLogger(Class<?> clazz) { + if (clazz != null) { + className = clazz.getName(); + } + PolicyLogger.postMDCInfoForEvent(null); + } + + /** + * Constructor. + * + * @param className the class name + */ + public EelfLogger(String className) { + if (className != null) { + this.className = className; + } + PolicyLogger.postMDCInfoForEvent(null); + } + + /** + * Constructor. + * + * @param clazz the class + * @param isNewTransaction is a new transaction + */ + public EelfLogger(Class<?> clazz, boolean isNewTransaction) { + if (clazz != null) { + className = clazz.getName(); + } + if (isNewTransaction) { + transId = PolicyLogger.postMDCInfoForEvent(null); + } else { + transId = PolicyLogger.getTransId(); + } + } + + /** + * Constructor. + * + * @param className the class name + * @param isNewTransaction is a new transaction + */ + public EelfLogger(String className, boolean isNewTransaction) { + if (className != null) { + this.className = className; + } + if (isNewTransaction) { + transId = PolicyLogger.postMDCInfoForEvent(null); + } else { + transId = PolicyLogger.getTransId(); + } + } + + /** + * Constructor. + * + * @param clazz the class + * @param transId the transaction ID + */ + public EelfLogger(Class<?> clazz, String transId) { + if (clazz != null) { + className = clazz.getName(); + } + PolicyLogger.postMDCInfoForEvent(transId); + this.transId = transId; + } + + /** + * Constructor. + * + * @param className the class name + * @param transId the transaction ID + */ + public EelfLogger(String className, String transId) { + if (className != null) { + this.className = className; + } + PolicyLogger.postMDCInfoForEvent(transId); + this.transId = transId; + } + + /** + * Sets transaction Id for logging. + * + * @param transId the transaction ID + */ + @Override + public void setTransId(String transId) { + + PolicyLogger.setTransId(transId); + this.transId = transId; + } + + /** + * Returns transaction Id for logging. + */ + @Override + public String getTransId() { + return transId; + } + + /** + * Records a message. + * + * @param message the message + */ + @Override + public void debug(Object message) { + PolicyLogger.debug(className, "" + message); + } + + /** + * Records a message. + * + * @param message the message + * @param throwable the throwable + */ + @Override + public void debug(Object message, Throwable throwable) { + PolicyLogger.debug(MessageCodes.GENERAL_INFO, throwable, message.toString()); + } + + /** + * Records an error message. + * + * @param message the message + */ + @Override + public void error(Object message) { + PolicyLogger.error(className, "" + message); + } + + /** + * Records an error message. + * + * @param message the message + * @param throwable the throwable + */ + @Override + public void error(Object message, Throwable throwable) { + PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, throwable, message.toString()); + } + + /** + * Records an error message. + * + * @param msg the message code + * @param throwable the throwable + * @param arguments the messages + */ + @Override + public void error(MessageCodes msg, Throwable throwable, String... arguments) { + PolicyLogger.error(msg, className, throwable, arguments); + } + + /** + * Records an error message. + * + * @param msg the message code + * @param arguments the messages + */ + @Override + public void error(MessageCodes msg, String... arguments) { + PolicyLogger.error(msg, arguments); + } + + /** + * Records a message. + * + * @param message the message + */ + @Override + public void info(Object message) { + PolicyLogger.info(className, "" + message); + } + + /** + * Records a message. + * + * @param message the message + * @param throwable the throwable + */ + @Override + public void info(Object message, Throwable throwable) { + PolicyLogger.info(MessageCodes.GENERAL_INFO, throwable, message.toString()); + } + + /** + * Records a message. + * + * @param message the message + */ + @Override + public void warn(Object message) { + PolicyLogger.warn(className, "" + message); + } + + /** + * Records a message. + * + * @param message the message + * @param throwable the throwable + */ + @Override + public void warn(Object message, Throwable throwable) { + PolicyLogger.warn(MessageCodes.GENERAL_WARNING, throwable, message.toString()); + } + + /** + * Records a message. + * + * @param msg the message codes + * @param arguments the messages + */ + @Override + public void warn(MessageCodes msg, String... arguments) { + PolicyLogger.warn(msg, className, arguments); + } + + /** + * Records a message. + * + * @param msg the message + * @param throwable the throwable + * @param arguments the messages + */ + @Override + public void warn(MessageCodes msg, Throwable throwable, String... arguments) { + PolicyLogger.warn(msg, className, throwable, arguments); + } + + /** + * Records a message. + * + * @param message the message + */ + @Override + public void trace(Object message) { + PolicyLogger.trace(className, "" + message); + } + + /** + * Records a message. + * + * @param message the message + * @param throwable the throwable + */ + @Override + public void trace(Object message, Throwable throwable) { + PolicyLogger.trace(message); + } + + /** + * Returns true for debug enabled, or false for not. + * + * @return boolean + */ + @Override + public boolean isDebugEnabled() { + return PolicyLogger.isDebugEnabled(); + } + + /** + * Returns true for info enabled, or false for not. + * + * @return boolean + */ + @Override + public boolean isInfoEnabled() { + return PolicyLogger.isInfoEnabled(); + } + + /** + * Returns true for warn enabled, or false for not. + * + * @return boolean + */ + @Override + public boolean isWarnEnabled() { + return PolicyLogger.isWarnEnabled(); + } + + /** + * Returns true for error enabled, or false for not. + * + * @return boolean + */ + @Override + public boolean isErrorEnabled() { + return PolicyLogger.isErrorEnabled(); + } + + /** + * Returns true for audit enabled, or false for not. + * + * @return boolean + */ + @Override + public boolean isAuditEnabled() { + return (PolicyLogger.getAuditLevel() != Level.OFF); + } + + /** + * Returns true for metrics enabled, or false for not. + * + * @return boolean + */ + @Override + public boolean isMetricsEnabled() { + return (PolicyLogger.getMetricsLevel() != Level.OFF); + } + + /** + * Returns true for trace enabled, or false for not. + * + * @return boolean + */ + @Override + public boolean isTraceEnabled() { + return PolicyLogger.isDebugEnabled(); + } + + /** + * Records an audit message. + * + * @param arg0 the message + */ + @Override + public void audit(Object arg0) { + PolicyLogger.audit(className, "" + arg0); + } + + /** + * Records an audit message. + * + * @param message the message + * @param throwable the throwable + */ + @Override + public void audit(Object message, Throwable throwable) { + PolicyLogger.audit(message); + } + + /** + * Records an audit message. + * + * @param eventId the event ID + */ + @Override + public void recordAuditEventStart(String eventId) { + PolicyLogger.recordAuditEventStart(eventId); + } + + /** + * Records an audit message. + * + * @param eventId the event ID + */ + @Override + public void recordAuditEventStart(UUID eventId) { + PolicyLogger.recordAuditEventStart(eventId); + } + + /** + * Records an audit message. + * + * @param eventId the event ID + * @param rule the rule + * @param policyVersion the policy cersion + */ + @Override + public void recordAuditEventEnd(String eventId, String rule, String policyVersion) { + PolicyLogger.recordAuditEventEnd(eventId, rule, policyVersion); + } + + /** + * Records an audit message. + * + * @param eventId the event ID + * @param rule the rule + * @param policyVersion the policy version + */ + @Override + public void recordAuditEventEnd(UUID eventId, String rule, String policyVersion) { + PolicyLogger.recordAuditEventEnd(eventId, rule, policyVersion); + } + + /** + * Records an audit message. + * + * @param eventId the event ID + * @param rule the rule + */ + @Override + public void recordAuditEventEnd(String eventId, String rule) { + PolicyLogger.recordAuditEventEnd(eventId, rule); + } + + /** + * Records an audit message. + * + * @param eventId the event ID + * @param rule the rule + */ + @Override + public void recordAuditEventEnd(UUID eventId, String rule) { + PolicyLogger.recordAuditEventEnd(eventId, rule); + } + + /** + * Records a metrics message. + * + * @param eventId the event ID + * @param message the message + */ + @Override + public void recordMetricEvent(String eventId, String message) { + PolicyLogger.recordMetricEvent(eventId, message); + } + + /** + * Records a metrics message. + * + * @param eventId the event ID + * @param message the message + */ + @Override + public void recordMetricEvent(UUID eventId, String message) { + PolicyLogger.recordMetricEvent(eventId, message); + } + + /** + * Records a metrics message. + * + * @param message the message + */ + @Override + public void metrics(Object message) { + PolicyLogger.metrics(className, message); + } + + /** + * Populates MDC Info. + * + * @param transId the transaction ID + */ + @Override + public String postMDCInfoForEvent(String transId) { + return PolicyLogger.postMDCInfoForEvent(transId); + } + + /** + * Populates MDC Info. + * + * @param obj the object + */ + @Override + public void postMDCInfoForEvent(Object obj) { + PolicyLogger.postMDCInfoForEvent(obj); + } + + /** + * Populates MDC Info for the rule triggered. + * + * @param transId the transaction ID + */ + @Override + public void postMDCInfoForTriggeredRule(String transId) { + PolicyLogger.postMDCInfoForTriggeredRule(transId); + } + } diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/FlexLogger.java b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/FlexLogger.java index 9723755e..90240a77 100644 --- a/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/FlexLogger.java +++ b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/FlexLogger.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-Logging * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,300 +32,305 @@ import org.onap.policy.common.logging.eelf.PolicyLogger; import org.onap.policy.common.logging.flexlogger.PropertyUtil.Listener; /** - * - * FlexLogger acts as factory to generate instances of Logger based on logger type - * + * FlexLogger acts as factory to generate instances of Logger based on logger type. */ -public class FlexLogger extends SecurityManager{ +public class FlexLogger extends SecurityManager { - private static final String GET_LOGGER_PREFIX = "FlexLogger:getLogger : loggerType = "; - private static LoggerType loggerType = LoggerType.EELF; + private static final String GET_LOGGER_PREFIX = "FlexLogger:getLogger : loggerType = "; + private static LoggerType loggerType = LoggerType.EELF; private static ConcurrentHashMap<String, Logger4J> logger4JMap = new ConcurrentHashMap<>(); private static ConcurrentHashMap<String, EelfLogger> eelfLoggerMap = new ConcurrentHashMap<>(); private static ConcurrentHashMap<String, SystemOutLogger> systemOutMap = new ConcurrentHashMap<>(); - //--- init logger first - static { - loggerType = initlogger(); - } - - /** - * Returns an instance of Logger - * @param clazz - */ - public static Logger getLogger(Class<?> clazz) { - Logger logger = null; - System.out.println(GET_LOGGER_PREFIX + loggerType); - switch (loggerType) { - - case EELF: - logger = getEelfLogger(clazz, false); - break; - case LOG4J: - logger = getLog4JLogger(); - break; - case SYSTEMOUT: - logger = getSystemOutLogger(); - break; - } - - return logger; - - } - - /** - * Returns an instance of Logger - * @param s - */ - public static Logger getLogger(String s) { - Logger logger = null; - System.out.println(GET_LOGGER_PREFIX + loggerType); - switch (loggerType) { - - case EELF: - logger = getEelfLogger(null,false); - break; - case LOG4J: - logger = getLog4JLogger(s); - break; - case SYSTEMOUT: - logger = getSystemOutLogger(); - break; - } - - return logger; - - } - - /** - * Returns an instance of Logger - * @param clazz - * @param isNewTransaction - */ - public static Logger getLogger(Class<?> clazz, boolean isNewTransaction) { - Logger logger = null; - System.out.println(GET_LOGGER_PREFIX + loggerType); - switch (loggerType) { - - case EELF: - logger = getEelfLogger(clazz, isNewTransaction); - break; - case LOG4J: - logger = getLog4JLogger(); - break; - case SYSTEMOUT: - logger = getSystemOutLogger(); - break; - } - - return logger; - - } - - /** - * Returns an instance of Logger - * @param s - * @param isNewTransaction - */ - public static Logger getLogger(String s, boolean isNewTransaction) { - Logger logger = null; - System.out.println(GET_LOGGER_PREFIX + loggerType); - switch (loggerType) { - - case EELF: - logger = getEelfLogger(null, isNewTransaction); - break; - case LOG4J: - logger = getLog4JLogger(s); - break; - case SYSTEMOUT: - logger = getSystemOutLogger(); - break; - } - - return logger; - } - - /** - * Returns the calling class name - */ - public String getClassName(){ - System.out.println("getClassContext()[3].getName() " + getClassContext()[3].getName()); - return getClassContext()[3].getName(); - } - - /** - * Returns an instance of Logger4J - * @param clazz - */ - private static Logger4J getLog4JLogger(){ - String className = new FlexLogger().getClassName(); - - if(!logger4JMap.containsKey(className)){ - //for 1610 release use the default debug.log for log4j - Logger4J logger = new Logger4J("debugLogger", className); - logger4JMap.put(className, logger); - } - - return logger4JMap.get(className); - } - - /** - * Returns an instance of Logger4J - * @param s - */ - private static Logger4J getLog4JLogger(String s){ - String className = new FlexLogger().getClassName(); - - if(!logger4JMap.containsKey(className)){ - Logger4J logger = new Logger4J(s, className); - logger4JMap.put(className, logger); - } - - return logger4JMap.get(className); - } - - /** - * Returns an instance of EelfLogger - * @param clazz - * @param isNewTransaction - */ - private static EelfLogger getEelfLogger(Class<?> clazz, boolean isNewTransaction){ - - String className; - EelfLogger logger; - if(clazz != null){ - className = clazz.getName(); - }else{ - className = new FlexLogger().getClassName(); - } - - if(!eelfLoggerMap.containsKey(className)){ - logger = new EelfLogger(clazz, isNewTransaction); - eelfLoggerMap.put(className, logger); - }else{ - logger = eelfLoggerMap.get(className); - if(logger == null){ - logger = new EelfLogger(clazz, isNewTransaction); - eelfLoggerMap.put(className, logger); - } - //installl already created but it is new transaction - if(isNewTransaction){ - String transId = PolicyLogger.postMDCInfoForEvent(null); - logger.setTransId(transId); - } - } - System.out.println("eelfLoggerMap size : " + eelfLoggerMap.size() + " class name: " + className); - return logger; - } - - /** - * Returns an instance of SystemOutLogger - * @param clazz - */ - private static SystemOutLogger getSystemOutLogger(){ - - String className = new FlexLogger().getClassName(); - - if(!systemOutMap.containsKey(className)){ - SystemOutLogger logger = new SystemOutLogger(className); - systemOutMap.put(className, logger); - } - - return systemOutMap.get(className); - } - - /** - * loads the logger properties - */ - private static LoggerType initlogger() { - LoggerType loggerType = LoggerType.EELF; - String overrideLogbackLevel = "FALSE"; - String loggerTypeString = ""; - Properties properties = null; - - try { - properties = PropertyUtil.getProperties("config/policyLogger.properties"); - System.out.println("FlexLogger:properties => " + properties); - - if(properties != null) { - overrideLogbackLevel = properties.getProperty("override.logback.level.setup"); - System.out.println("FlexLogger:overrideLogbackLevel => " + overrideLogbackLevel); - loggerTypeString = properties.getProperty("logger.type"); - if (loggerTypeString != null){ - if ("EELF".equalsIgnoreCase(loggerTypeString)){ - loggerType = LoggerType.EELF; - if ("TRUE".equalsIgnoreCase(overrideLogbackLevel)) { - System.out.println("FlexLogger: start listener."); - properties = PropertyUtil.getProperties - ("config/policyLogger.properties", - new PropertiesCallBack("FlexLogger-CallBack")); - } - }else if ("LOG4J".equalsIgnoreCase(loggerTypeString)){ - loggerType = LoggerType.LOG4J; - }else if ("SYSTEMOUT".equalsIgnoreCase(loggerTypeString)){ - loggerType = LoggerType.SYSTEMOUT; - } - - System.out.println("FlexLogger.logger_Type value: " + loggerTypeString); - } - } - } catch (IOException e1) { - System.out.println("initlogger" + e1); - } finally { - // OK to pass no properties (null) - loggerType = PolicyLogger.init(properties); - } - - return loggerType; - } - - /** - * PropertiesCallBack is listening any updates on the policyLogger.properties - */ - public static class PropertiesCallBack implements Listener { - String name; - - public PropertiesCallBack(String name) { - this.name = name; - } - - /** - * This method will be called automatically if he policyLogger.properties got updated - */ - @Override - public void propertiesChanged(Properties properties, - Set<String> changedKeys) { - - String debugLevel = properties.getProperty("debugLogger.level"); - String metricsLevel = properties.getProperty("metricsLogger.level"); - String auditLevel = properties.getProperty("audit.level"); - String errorLevel = properties.getProperty("error.level"); - - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+00:00"); - Instant startTime = Instant.now(); - String formatedTime = sdf.format(Date.from(startTime)); - System.out.println("FlexLogger.propertiesChanged : called at time : " + formatedTime); - System.out.println("FlexLogger.propertiesChanged : debugLevel : " + debugLevel); - - if (changedKeys != null) { - - if (changedKeys.contains("debugLogger.level")) { - PolicyLogger.setDebugLevel(debugLevel); - } - - if (changedKeys.contains("metricsLogger.level")) { - PolicyLogger.setMetricsLevel(metricsLevel); - } - - if (changedKeys.contains("error.level")) { - PolicyLogger.setErrorLevel(errorLevel); - } - - if (changedKeys.contains("audit.level")) { - PolicyLogger.setAuditLevel(auditLevel); - } - } - } - } - + + // --- init logger first + static { + loggerType = initlogger(); + } + + /** + * Returns an instance of Logger. + * + * @param clazz the class + */ + public static Logger getLogger(Class<?> clazz) { + Logger logger = null; + System.out.println(GET_LOGGER_PREFIX + loggerType); + switch (loggerType) { + + case EELF: + logger = getEelfLogger(clazz, false); + break; + case LOG4J: + logger = getLog4JLogger(); + break; + case SYSTEMOUT: + default: + logger = getSystemOutLogger(); + break; + } + + return logger; + + } + + /** + * Returns an instance of Logger. + * + * @param name the name of the logger + */ + public static Logger getLogger(String name) { + Logger logger = null; + System.out.println(GET_LOGGER_PREFIX + loggerType); + switch (loggerType) { + + case EELF: + logger = getEelfLogger(null, false); + break; + case LOG4J: + logger = getLog4JLogger(name); + break; + case SYSTEMOUT: + default: + logger = getSystemOutLogger(); + break; + } + + return logger; + + } + + /** + * Returns an instance of Logger. + * + * @param clazz the class + * @param isNewTransaction is a new transaction + */ + public static Logger getLogger(Class<?> clazz, boolean isNewTransaction) { + Logger logger = null; + System.out.println(GET_LOGGER_PREFIX + loggerType); + switch (loggerType) { + + case EELF: + logger = getEelfLogger(clazz, isNewTransaction); + break; + case LOG4J: + logger = getLog4JLogger(); + break; + case SYSTEMOUT: + default: + logger = getSystemOutLogger(); + break; + } + + return logger; + + } + + /** + * Returns an instance of Logger. + * + * @param name the name of the logger + * @param isNewTransaction is a new transaction + */ + public static Logger getLogger(String name, boolean isNewTransaction) { + Logger logger = null; + System.out.println(GET_LOGGER_PREFIX + loggerType); + switch (loggerType) { + + case EELF: + logger = getEelfLogger(null, isNewTransaction); + break; + case LOG4J: + logger = getLog4JLogger(name); + break; + case SYSTEMOUT: + default: + logger = getSystemOutLogger(); + break; + } + + return logger; + } + + /** + * Returns the calling class name. + */ + public String getClassName() { + System.out.println("getClassContext()[3].getName() " + getClassContext()[3].getName()); + return getClassContext()[3].getName(); + } + + /** + * Returns an instance of Logger4J. + */ + private static Logger4J getLog4JLogger() { + String className = new FlexLogger().getClassName(); + + if (!logger4JMap.containsKey(className)) { + // for 1610 release use the default debug.log for log4j + Logger4J logger = new Logger4J("debugLogger", className); + logger4JMap.put(className, logger); + } + + return logger4JMap.get(className); + } + + /** + * Returns an instance of Logger4J. + * + * @param name the name of the logger + */ + private static Logger4J getLog4JLogger(String name) { + String className = new FlexLogger().getClassName(); + + if (!logger4JMap.containsKey(className)) { + Logger4J logger = new Logger4J(name, className); + logger4JMap.put(className, logger); + } + + return logger4JMap.get(className); + } + + /** + * Returns an instance of EelfLogger. + * + * @param clazz the class + * @param isNewTransaction is a new transaction + */ + private static EelfLogger getEelfLogger(Class<?> clazz, boolean isNewTransaction) { + + String className; + EelfLogger logger; + if (clazz != null) { + className = clazz.getName(); + } else { + className = new FlexLogger().getClassName(); + } + + if (!eelfLoggerMap.containsKey(className)) { + logger = new EelfLogger(clazz, isNewTransaction); + eelfLoggerMap.put(className, logger); + } else { + logger = eelfLoggerMap.get(className); + if (logger == null) { + logger = new EelfLogger(clazz, isNewTransaction); + eelfLoggerMap.put(className, logger); + } + // installl already created but it is new transaction + if (isNewTransaction) { + String transId = PolicyLogger.postMDCInfoForEvent(null); + logger.setTransId(transId); + } + } + System.out.println("eelfLoggerMap size : " + eelfLoggerMap.size() + " class name: " + className); + return logger; + } + + /** + * Returns an instance of SystemOutLogger. + */ + private static SystemOutLogger getSystemOutLogger() { + + String className = new FlexLogger().getClassName(); + + if (!systemOutMap.containsKey(className)) { + SystemOutLogger logger = new SystemOutLogger(className); + systemOutMap.put(className, logger); + } + + return systemOutMap.get(className); + } + + /** + * loads the logger properties. + */ + private static LoggerType initlogger() { + LoggerType loggerType = LoggerType.EELF; + String overrideLogbackLevel = "FALSE"; + String loggerTypeString = ""; + Properties properties = null; + + try { + properties = PropertyUtil.getProperties("config/policyLogger.properties"); + System.out.println("FlexLogger:properties => " + properties); + + if (properties != null) { + overrideLogbackLevel = properties.getProperty("override.logback.level.setup"); + System.out.println("FlexLogger:overrideLogbackLevel => " + overrideLogbackLevel); + loggerTypeString = properties.getProperty("logger.type"); + if (loggerTypeString != null) { + if ("EELF".equalsIgnoreCase(loggerTypeString)) { + loggerType = LoggerType.EELF; + if ("TRUE".equalsIgnoreCase(overrideLogbackLevel)) { + System.out.println("FlexLogger: start listener."); + properties = PropertyUtil.getProperties("config/policyLogger.properties", + new PropertiesCallBack("FlexLogger-CallBack")); + } + } else if ("LOG4J".equalsIgnoreCase(loggerTypeString)) { + loggerType = LoggerType.LOG4J; + } else if ("SYSTEMOUT".equalsIgnoreCase(loggerTypeString)) { + loggerType = LoggerType.SYSTEMOUT; + } + + System.out.println("FlexLogger.logger_Type value: " + loggerTypeString); + } + } + } catch (IOException e1) { + System.out.println("initlogger" + e1); + } finally { + // OK to pass no properties (null) + loggerType = PolicyLogger.init(properties); + } + + return loggerType; + } + + /** + * PropertiesCallBack is listening any updates on the policyLogger.properties + */ + public static class PropertiesCallBack implements Listener { + String name; + + public PropertiesCallBack(String name) { + this.name = name; + } + + /** + * This method will be called automatically if he policyLogger.properties got updated + */ + @Override + public void propertiesChanged(Properties properties, Set<String> changedKeys) { + + String debugLevel = properties.getProperty("debugLogger.level"); + String metricsLevel = properties.getProperty("metricsLogger.level"); + String auditLevel = properties.getProperty("audit.level"); + String errorLevel = properties.getProperty("error.level"); + + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+00:00"); + Instant startTime = Instant.now(); + String formatedTime = sdf.format(Date.from(startTime)); + System.out.println("FlexLogger.propertiesChanged : called at time : " + formatedTime); + System.out.println("FlexLogger.propertiesChanged : debugLevel : " + debugLevel); + + if (changedKeys != null) { + + if (changedKeys.contains("debugLogger.level")) { + PolicyLogger.setDebugLevel(debugLevel); + } + + if (changedKeys.contains("metricsLogger.level")) { + PolicyLogger.setMetricsLevel(metricsLevel); + } + + if (changedKeys.contains("error.level")) { + PolicyLogger.setErrorLevel(errorLevel); + } + + if (changedKeys.contains("audit.level")) { + PolicyLogger.setAuditLevel(auditLevel); + } + } + } + } + } diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/Logger.java b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/Logger.java index d3113d31..f74aca14 100644 --- a/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/Logger.java +++ b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/Logger.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-Logging * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,197 +25,196 @@ import java.util.UUID; import org.onap.policy.common.logging.eelf.MessageCodes; /** - * - * Interface Logger - implemented by Logger4J, EelfLogger and SystemOutLogger + * Interface Logger - implemented by Logger4J, EelfLogger and SystemOutLogger. * */ -public interface Logger { - - /** - * Prints messages with the level.DEBUG - */ - public void debug(Object message); - - /** - * Prints messages with the level.ERROR - */ - public void error(Object message); - - /** - * Prints messages with the level.ERROR - */ - public void error(MessageCodes msg, Throwable arg0, String... arguments); - - /** - * Prints messages with the level.INFO - */ - public void info(Object message); - - /** - * Prints messages with the level.WARN - */ - public void warn(Object message); - - /** - * Prints messages with the level.TRACE - */ - public void trace(Object message); - - /** - * Prints messages in audit log with the level.INFO - */ - public void audit(Object arg0); - - /** - * Prints messages with the level.DEBUG - */ - public void debug(Object message, Throwable t); - - /** - * Prints messages with the level.ERROR - */ - public void error(Object message, Throwable t); - - /** - * Prints messages with the level.INFO - */ - public void info(Object message, Throwable t); - - /** - * Prints messages with the level.WARN - */ - public void warn(Object message, Throwable t); - - /** - * Prints messages with the level.TRACE - */ - public void trace(Object message, Throwable t); - - /** - * Prints messages in audit log with the level.INFO - */ - public void audit(Object arg0, Throwable t); - - /** - * Records event Id in audit log with the level.INFO - */ - public void recordAuditEventStart(String eventId); - - /** - * Records the starting time of the event with its request Id as the key - */ - public void recordAuditEventStart(UUID eventId); - - /** - * Records the ending time of the event with its request Id as the key - */ - public void recordAuditEventEnd(String eventId, String rule, String policyVersion ); - - /** - * Records the ending time of the event with its request Id as the key - */ - public void recordAuditEventEnd(UUID eventId, String rule, String policyVersion); - - /** - * Records the ending time of the event with its request Id as the key - */ - public void recordAuditEventEnd(String eventId, String rule); - - /** - * Records the ending time of the event with its request Id as the key - */ - public void recordAuditEventEnd(UUID eventId, String rule); - - - /** - * Records the Metrics with event Id and log message - */ - public void recordMetricEvent(String eventId, String arg1); - - /** - * Records the Metrics with event Id and log message - */ - public void recordMetricEvent(UUID eventId, String arg1); - - /** - * Records the Metrics log message - */ - public void metrics(Object arg0); - - /** - * Returns a boolean value, true for debug logging enabled, false for not enabled - */ - public boolean isDebugEnabled(); - - /** - * Returns a boolean value, true for error logging enabled, false for not enabled - */ - public boolean isErrorEnabled(); - - /** - * Returns a boolean value, true for warn logging enabled, false for not enabled - */ - public boolean isWarnEnabled(); - - /** - * Returns a boolean value, true for info logging enabled, false for not enabled - */ - public boolean isInfoEnabled(); - - /** - * Returns a boolean value, true for error logging enabled, false for not enabled - */ - public boolean isAuditEnabled(); - - /** - * Returns a boolean value, true for warn logging enabled, false for not enabled - */ - public boolean isMetricsEnabled(); - - /** - * Returns a boolean value, true for trace logging enabled, false for not enabled - */ - public boolean isTraceEnabled(); - - - /** - * Populates MDC info - */ - public String postMDCInfoForEvent(String transId); - - /** - * Prints messages with the level.WARN - */ - public void warn(MessageCodes msg, String... arguments) ; - - /** - * Prints messages with the level.WARN - */ - public void warn(MessageCodes msg, Throwable arg0, String... arguments) ; - - /** - * Prints messages with the level.ERROR - */ - public void error(MessageCodes msg, String... arguments) ; - - /** - * Sets transaction Id - */ - public void setTransId(String transId); - - /** - * Returns transaction Id - */ - String getTransId(); - - /** - * Populates MDC Info for the rule triggered - */ - public void postMDCInfoForTriggeredRule(String transId); - - /** - * Populates MDC Info - */ - public void postMDCInfoForEvent(Object o); - +public interface Logger { + + /** + * Prints messages with the level.DEBUG + */ + public void debug(Object message); + + /** + * Prints messages with the level.DEBUG + */ + public void debug(Object message, Throwable throwable); + + /** + * Prints messages with the level.ERROR + */ + public void error(Object message); + + /** + * Prints messages with the level.ERROR + */ + public void error(Object message, Throwable throwable); + + /** + * Prints messages with the level.ERROR + */ + public void error(MessageCodes msg, String... arguments); + + /** + * Prints messages with the level.ERROR + */ + public void error(MessageCodes msg, Throwable arg0, String... arguments); + + /** + * Prints messages with the level.INFO + */ + public void info(Object message); + + /** + * Prints messages with the level.INFO + */ + public void info(Object message, Throwable throwable); + + /** + * Prints messages with the level.WARN + */ + public void warn(Object message); + + /** + * Prints messages with the level.WARN + */ + public void warn(Object message, Throwable throwable); + + /** + * Prints messages with the level.WARN + */ + public void warn(MessageCodes msg, String... arguments); + + /** + * Prints messages with the level.WARN + */ + public void warn(MessageCodes msg, Throwable arg0, String... arguments); + + /** + * Prints messages with the level.TRACE + */ + public void trace(Object message); + + /** + * Prints messages with the level.TRACE + */ + public void trace(Object message, Throwable throwable); + + /** + * Prints messages in audit log with the level.INFO + */ + public void audit(Object arg0); + + /** + * Prints messages in audit log with the level.INFO + */ + public void audit(Object arg0, Throwable throwable); + + /** + * Records event Id in audit log with the level.INFO + */ + public void recordAuditEventStart(String eventId); + + /** + * Records the starting time of the event with its request Id as the key. + */ + public void recordAuditEventStart(UUID eventId); + + /** + * Records the ending time of the event with its request Id as the key. + */ + public void recordAuditEventEnd(String eventId, String rule, String policyVersion); + + /** + * Records the ending time of the event with its request Id as the key. + */ + public void recordAuditEventEnd(UUID eventId, String rule, String policyVersion); + + /** + * Records the ending time of the event with its request Id as the key. + */ + public void recordAuditEventEnd(String eventId, String rule); + + /** + * Records the ending time of the event with its request Id as the key. + */ + public void recordAuditEventEnd(UUID eventId, String rule); + + + /** + * Records the Metrics with event Id and log message. + */ + public void recordMetricEvent(String eventId, String arg1); + + /** + * Records the Metrics with event Id and log message. + */ + public void recordMetricEvent(UUID eventId, String arg1); + + /** + * Records the Metrics log message. + */ + public void metrics(Object arg0); + + /** + * Returns a boolean value, true for debug logging enabled, false for not enabled. + */ + public boolean isDebugEnabled(); + + /** + * Returns a boolean value, true for error logging enabled, false for not enabled. + */ + public boolean isErrorEnabled(); + + /** + * Returns a boolean value, true for warn logging enabled, false for not enabled. + */ + public boolean isWarnEnabled(); + + /** + * Returns a boolean value, true for info logging enabled, false for not enabled. + */ + public boolean isInfoEnabled(); + + /** + * Returns a boolean value, true for error logging enabled, false for not enabled. + */ + public boolean isAuditEnabled(); + + /** + * Returns a boolean value, true for warn logging enabled, false for not enabled. + */ + public boolean isMetricsEnabled(); + + /** + * Returns a boolean value, true for trace logging enabled, false for not enabled. + */ + public boolean isTraceEnabled(); + + + /** + * Populates MDC info. + */ + public String postMDCInfoForEvent(String transId); + + /** + * Populates MDC Info. + */ + public void postMDCInfoForEvent(Object obj); + + /** + * Sets transaction Id. + */ + public void setTransId(String transId); + + /** + * Returns transaction Id. + */ + String getTransId(); + + /** + * Populates MDC Info for the rule triggered. + */ + public void postMDCInfoForTriggeredRule(String transId); + } diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/Logger4J.java b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/Logger4J.java index 555620f2..88d3800a 100644 --- a/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/Logger4J.java +++ b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/Logger4J.java @@ -20,6 +20,8 @@ package org.onap.policy.common.logging.flexlogger; +import com.att.eelf.configuration.EELFLogger.Level; + import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; @@ -29,454 +31,482 @@ import java.util.UUID; import org.apache.log4j.Logger; import org.apache.log4j.Priority; - import org.onap.policy.common.logging.eelf.MessageCodes; import org.onap.policy.common.logging.eelf.PolicyLogger; -import com.att.eelf.configuration.EELFLogger.Level; /** - * * Logger4J implements all the methods of interface Logger by calling org.apache.log4j.Logger - * */ public class Logger4J implements org.onap.policy.common.logging.flexlogger.Logger, Serializable { - - /** - * - */ - private static final long serialVersionUID = 3183729429888828471L; - private Logger log = null; + + private static final long serialVersionUID = 3183729429888828471L; + private Logger log = null; private String methodName = ""; private String className = ""; - private String transId = UUID.randomUUID().toString(); - - /** - * Constructor - * @param clazz - */ - public Logger4J (Class<?> clazz){ - System.out.println("create instance of Logger4J"); - if(clazz != null){ - log = Logger.getLogger(clazz); - className = clazz.getName(); - } - } - - /** - * Constructor - * @param s - * @param className - */ - public Logger4J (String s, String className){ - System.out.println("create instance of Logger4J"); - if(s != null){ - log = Logger.getLogger(s); - } - this.className = className; - } - - /** - * Sets transaction Id - */ - @Override - public void setTransId(String transId){ - log.info(transId); - this.transId = transId; - } - - /** - * Returns transaction Id - */ - @Override - public String getTransId(){ - return transId; - } - - /** - * Records a message - * @param message - */ - @Override - public void debug(Object message) { - if(isDebugEnabled()){ - log.debug(transId + "|" + message); - } - } - - /** - * Records an error message - * @param message - */ - @Override - public void error(Object message) { - log.error( transId + "|" + className +"|" + message); - } - - /** - * Records a message - * @param message - */ - @Override - public void info(Object message) { - log.info( transId + "|" + className +"|" + message); - } - - /** - * Records a message - * @param message - */ - @Override - public void warn(Object message) { - log.warn( transId + "|" + className +"|" + message); - } - - /** - * Records a message - * @param message - */ - @Override - public void trace(Object message) { - log.trace(transId + "|"+ className +"|" + message); - } - - /** - * Returns true for debug enabled, or false for not - * @return boolean - */ - @Override - public boolean isDebugEnabled(){ - return log.isDebugEnabled(); - } - - /** - * Returns true for error enabled, or false for not - * @return boolean - */ - @SuppressWarnings("deprecation") - @Override - public boolean isErrorEnabled(){ - return log.isEnabledFor(Priority.ERROR); - } - - /** - * Returns true for info enabled, or false for not - * @return boolean - */ - @Override - public boolean isInfoEnabled(){ - return log.isInfoEnabled(); - } - - /** - * Returns true for warn enabled, or false for not - * @return boolean - */ - @SuppressWarnings("deprecation") - @Override - public boolean isWarnEnabled(){ - //return log4j value - return log.isEnabledFor(Priority.WARN); - } - - /** - * Returns true for audit enabled, or false for not - * @return boolean - */ - @Override - public boolean isAuditEnabled(){ - return(PolicyLogger.getAuditLevel() != Level.OFF); - } - - /** - * Returns true for metrics enabled, or false for not - * @return boolean - */ - @Override - public boolean isMetricsEnabled(){ - return(PolicyLogger.getMetricsLevel() != Level.OFF); - } - - /** - * Records an audit message - * @param arg0 - */ - @Override - public void audit(Object arg0) { - log.info(className +"|" +arg0); - } - - /** - * Records an audit message - * @param eventId - */ - @Override - public void recordAuditEventStart(String eventId) { - log.info(className +"|recordAuditEventStart with eventId " + eventId); - } - - /** - * Records an audit message - * @param eventId - */ - @Override - public void recordAuditEventStart(UUID eventId) { - if(eventId != null){ - recordAuditEventStart(eventId.toString()); - } - } - - /** - * Records an audit message - * @param eventId - * @param rule - * @param policyVersion - */ - @Override - public void recordAuditEventEnd(String eventId, String rule, String policyVersion) { - log.info(className +"|"+ eventId + ":" + rule); - } - - /** - * Records an audit message - * @param eventId - * @param rule - * @param policyVersion - */ - @Override - public void recordAuditEventEnd(UUID eventId, String rule, String policyVersion) { - if(eventId != null){ - recordAuditEventEnd(eventId.toString(), rule, policyVersion); - }else{ - recordAuditEventEnd(eventId, rule, policyVersion); - } - } - - /** - * Records an audit message - * @param eventId - * @param rule - */ - @Override - public void recordAuditEventEnd(String eventId, String rule) { - log.info(className +"|" +eventId + ":" + rule); - } - - /** - * Records an audit message - * @param eventId - * @param rule - */ - @Override - public void recordAuditEventEnd(UUID eventId, String rule) { - if(eventId != null){ - recordAuditEventEnd(eventId.toString(), rule); - }else{ - recordAuditEventEnd(eventId, rule); - } - } - - /** - * Records a metrics message - * @param eventId - * @param arg1 - */ - @Override - public void recordMetricEvent(String eventId, String arg1) { - log.info(className +"|" +eventId + ":" + arg1); - - } - - /** - * Records a metrics message - * @param eventId - * @param arg1 - */ - @Override - public void recordMetricEvent(UUID eventId, String arg1) { - if(eventId != null){ - recordMetricEvent(eventId.toString(), arg1); - }else{ - recordMetricEvent(eventId, arg1); - } - } - - /** - * Records a metrics message - * @param arg0 - */ - @Override - public void metrics(Object arg0) { - log.info(arg0); - } - - /** - * Records an error message - * @param msg - * @param arg0 - * @param arguments - */ - @Override - public void error(MessageCodes msg, Throwable arg0, String... arguments){ - log.error(transId + "|" + className +"|" + "MessageCodes :" + msg + Arrays.asList(arguments)); - - } - - /** - * Records an error message - * @param msg - * @param arguments - */ - @Override - public void error(MessageCodes msg, String... arguments){ - log.error(transId + "|" + className +"|" + "MessageCode:" + msg + Arrays.asList(arguments)); - } - - /** - * Returns transaction Id - * @param transId - */ - @Override - public String postMDCInfoForEvent(String transId) { - String transactionId = transId; - if(transactionId == null || transactionId.isEmpty()){ - transactionId = UUID.randomUUID().toString(); - } - - return transactionId; - } - - /** - * Records a message - * @param msg - * @param arguments - */ - @Override - public void warn(MessageCodes msg, String... arguments){ - log.warn(className +"|" +"MessageCodes:" + msg + Arrays.asList(arguments)); - } - - /** - * Records a message - * @param msg - * @param arg0 - * @param arguments - */ - @Override - public void warn(MessageCodes msg, Throwable arg0, String... arguments){ - log.warn(className +"|" +"MessageCodes:" + msg + Arrays.asList(arguments)); - } - - /** - * Records a message - * @param message - * @param t - */ - @Override - public void debug(Object message, Throwable t) { - log.debug(message, t); - } - - /** - * Records an error message - * @param message - * @param t - */ - @Override - public void error(Object message, Throwable t) { - log.error(message, t); - } - - /** - * Records a message - * @param message - * @param t - */ - @Override - public void info(Object message, Throwable t) { - log.info(message, t); - } - - /** - * Records a message - * @param message - * @param t - */ - @Override - public void warn(Object message, Throwable t) { - log.warn(message, t); - } - - /** - * Records a message - * @param message - * @param t - */ - @Override - public void trace(Object message, Throwable t) { - log.trace(message, t); - } - - /** - * Records an audit message - * @param arg0 - * @param t - */ - - @Override - public void audit(Object arg0, Throwable t) { - log.info(arg0, t); - } - - /** - * Returns true for trace enabled, or false for not - * @return boolean - */ - @Override - public boolean isTraceEnabled() { - return log.isTraceEnabled(); - } - - /** - * Records transaction Id - * @param transId - */ - @Override - public void postMDCInfoForTriggeredRule(String transId){ - log.info(transId); - } - - /** - * Records transaction Id - * @param o - */ - @Override - public void postMDCInfoForEvent(Object o){ - log.info(o); - } - - /* ============================================================ */ - - /* - * Support for 'Serializable' -- - * the default rules don't work for the 'log' field - */ - - private void writeObject(ObjectOutputStream out) throws IOException { - // write out 'methodName', 'className', 'transId' strings - out.writeObject(methodName); - out.writeObject(className); - out.writeObject(transId); - } - - private void readObject(ObjectInputStream in) - throws IOException, ClassNotFoundException { - - // read in 'methodName', 'className', 'transId' strings - methodName = (String)(in.readObject()); - className = (String)(in.readObject()); - transId = (String)(in.readObject()); - - // look up associated logger - log = Logger.getLogger(className); - } + private String transId = UUID.randomUUID().toString(); + + /** + * Constructor. + * + * @param clazz the class + */ + public Logger4J(Class<?> clazz) { + System.out.println("create instance of Logger4J"); + if (clazz != null) { + log = Logger.getLogger(clazz); + className = clazz.getName(); + } + } + + /** + * Constructor. + * + * @param name the name of the logger + * @param className the name of the class + */ + public Logger4J(String name, String className) { + System.out.println("create instance of Logger4J"); + if (name != null) { + log = Logger.getLogger(name); + } + this.className = className; + } + + /** + * Sets transaction Id. + */ + @Override + public void setTransId(String transId) { + log.info(transId); + this.transId = transId; + } + + /** + * Returns transaction Id. + */ + @Override + public String getTransId() { + return transId; + } + + /** + * Records a message. + * + * @param message the message + */ + @Override + public void debug(Object message) { + if (isDebugEnabled()) { + log.debug(transId + "|" + message); + } + } + + /** + * Records a message. + * + * @param message the message + * @param throwable the throwable + */ + @Override + public void debug(Object message, Throwable throwable) { + log.debug(message, throwable); + } + + /** + * Records an error message. + * + * @param message the message + */ + @Override + public void error(Object message) { + log.error(transId + "|" + className + "|" + message); + } + + /** + * Records an error message. + * + * @param message the message + * @param throwable the throwable + */ + @Override + public void error(Object message, Throwable throwable) { + log.error(message, throwable); + } + + /** + * Records an error message. + * + * @param msg the message code + * @param throwable the throwable + * @param arguments the messages + */ + @Override + public void error(MessageCodes msg, Throwable throwable, String... arguments) { + log.error(transId + "|" + className + "|" + "MessageCodes :" + msg + Arrays.asList(arguments)); + + } + + /** + * Records an error message. + * + * @param msg the message code + * @param arguments the messages + */ + @Override + public void error(MessageCodes msg, String... arguments) { + log.error(transId + "|" + className + "|" + "MessageCode:" + msg + Arrays.asList(arguments)); + } + + /** + * Records a message. + * + * @param message the message + */ + @Override + public void info(Object message) { + log.info(transId + "|" + className + "|" + message); + } + + /** + * Records a message. + * + * @param message the message + * @param throwable the throwable + */ + @Override + public void info(Object message, Throwable throwable) { + log.info(message, throwable); + } + + /** + * Records a message. + * + * @param message the message + */ + @Override + public void warn(Object message) { + log.warn(transId + "|" + className + "|" + message); + } + + /** + * Records a message. + * + * @param message the message + * @param throwable the throwable + */ + @Override + public void warn(Object message, Throwable throwable) { + log.warn(message, throwable); + } + + /** + * Records a message. + * + * @param msg the message code + * @param arguments the messages + */ + @Override + public void warn(MessageCodes msg, String... arguments) { + log.warn(className + "|" + "MessageCodes:" + msg + Arrays.asList(arguments)); + } + + /** + * Records a message. + * + * @param msg the message code + * @param throwable the throwable + * @param arguments the messages + */ + @Override + public void warn(MessageCodes msg, Throwable throwable, String... arguments) { + log.warn(className + "|" + "MessageCodes:" + msg + Arrays.asList(arguments)); + } + + /** + * Records a message. + * + * @param message the message + */ + @Override + public void trace(Object message) { + log.trace(transId + "|" + className + "|" + message); + } + + /** + * Records a message. + * + * @param message the message + * @param throwable the throwable + */ + @Override + public void trace(Object message, Throwable throwable) { + log.trace(message, throwable); + } + + /** + * Returns true for debug enabled, or false for not. + * + * @return boolean + */ + @Override + public boolean isDebugEnabled() { + return log.isDebugEnabled(); + } + + /** + * Returns true for error enabled, or false for not. + * + * @return boolean + */ + @SuppressWarnings("deprecation") + @Override + public boolean isErrorEnabled() { + return log.isEnabledFor(Priority.ERROR); + } + + /** + * Returns true for info enabled, or false for not. + * + * @return boolean + */ + @Override + public boolean isInfoEnabled() { + return log.isInfoEnabled(); + } + + /** + * Returns true for warn enabled, or false for not. + * + * @return boolean + */ + @SuppressWarnings("deprecation") + @Override + public boolean isWarnEnabled() { + // return log4j value + return log.isEnabledFor(Priority.WARN); + } + + /** + * Returns true for audit enabled, or false for not. + * + * @return boolean + */ + @Override + public boolean isAuditEnabled() { + return (PolicyLogger.getAuditLevel() != Level.OFF); + } + + /** + * Returns true for metrics enabled, or false for not. + * + * @return boolean + */ + @Override + public boolean isMetricsEnabled() { + return (PolicyLogger.getMetricsLevel() != Level.OFF); + } + + /** + * Records an audit message. + * + * @param message the message + */ + @Override + public void audit(Object message) { + log.info(className + "|" + message); + } + + /** + * Records an audit message. + * + * @param message the message + * @param throwable the throwable + */ + + @Override + public void audit(Object message, Throwable throwable) { + log.info(message, throwable); + } + + /** + * Records an audit message. + * + * @param eventId the event ID + */ + @Override + public void recordAuditEventStart(String eventId) { + log.info(className + "|recordAuditEventStart with eventId " + eventId); + } + + /** + * Records an audit message. + * + * @param eventId the event ID + */ + @Override + public void recordAuditEventStart(UUID eventId) { + if (eventId != null) { + recordAuditEventStart(eventId.toString()); + } + } + + /** + * Records an audit message. + * + * @param eventId the event ID + * @param rule the rule + * @param policyVersion the policy version + */ + @Override + public void recordAuditEventEnd(String eventId, String rule, String policyVersion) { + log.info(className + "|" + eventId + ":" + rule); + } + + /** + * Records an audit message. + * + * @param eventId the event ID + * @param rule the rule + * @param policyVersion the policy version + */ + @Override + public void recordAuditEventEnd(UUID eventId, String rule, String policyVersion) { + if (eventId != null) { + recordAuditEventEnd(eventId.toString(), rule, policyVersion); + } else { + recordAuditEventEnd(eventId, rule, policyVersion); + } + } + + /** + * Records an audit message. + * + * @param eventId the event ID + * @param rule the rule + */ + @Override + public void recordAuditEventEnd(String eventId, String rule) { + log.info(className + "|" + eventId + ":" + rule); + } + + /** + * Records an audit message. + * + * @param eventId the event ID + * @param rule the rule + */ + @Override + public void recordAuditEventEnd(UUID eventId, String rule) { + if (eventId != null) { + recordAuditEventEnd(eventId.toString(), rule); + } else { + recordAuditEventEnd(eventId, rule); + } + } + + /** + * Records a metrics message. + * + * @param eventId the event ID + * @param message the message + */ + @Override + public void recordMetricEvent(String eventId, String message) { + log.info(className + "|" + eventId + ":" + message); + + } + + /** + * Records a metrics message. + * + * @param eventId the event ID + * @param message the message + */ + @Override + public void recordMetricEvent(UUID eventId, String message) { + if (eventId != null) { + recordMetricEvent(eventId.toString(), message); + } else { + recordMetricEvent(eventId, message); + } + } + + /** + * Records a metrics message. + * + * @param message the message + */ + @Override + public void metrics(Object message) { + log.info(message); + } + + /** + * Returns transaction Id. + * + * @param transId the transaction ID + */ + @Override + public String postMDCInfoForEvent(String transId) { + String transactionId = transId; + if (transactionId == null || transactionId.isEmpty()) { + transactionId = UUID.randomUUID().toString(); + } + + return transactionId; + } + + /** + * Records transaction Id. + * + * @param message the message + */ + @Override + public void postMDCInfoForEvent(Object message) { + log.info(message); + } + + /** + * Returns true for trace enabled, or false for not. + * + * @return boolean + */ + @Override + public boolean isTraceEnabled() { + return log.isTraceEnabled(); + } + + /** + * Records transaction Id. + * + * @param transId the transaction ID + */ + @Override + public void postMDCInfoForTriggeredRule(String transId) { + log.info(transId); + } + + /* ============================================================ */ + + /* + * Support for 'Serializable' -- the default rules don't work for the 'log' field + */ + + private void writeObject(ObjectOutputStream out) throws IOException { + // write out 'methodName', 'className', 'transId' strings + out.writeObject(methodName); + out.writeObject(className); + out.writeObject(transId); + } + + private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { + + // read in 'methodName', 'className', 'transId' strings + methodName = (String) (in.readObject()); + className = (String) (in.readObject()); + transId = (String) (in.readObject()); + + // look up associated logger + log = Logger.getLogger(className); + } } diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/LoggerType.java b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/LoggerType.java index ed2029e6..8bf0dd78 100644 --- a/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/LoggerType.java +++ b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/LoggerType.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-Logging * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,10 +21,8 @@ package org.onap.policy.common.logging.flexlogger; /** - * - * Logger types - * + * Logger types. */ public enum LoggerType { - EELF, LOG4J, SYSTEMOUT + EELF, LOG4J, SYSTEMOUT } diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/PropertyUtil.java b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/PropertyUtil.java index 86d119ea..54e06411 100644 --- a/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/PropertyUtil.java +++ b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/PropertyUtil.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-Logging * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,360 +32,313 @@ import java.util.Timer; import java.util.TimerTask; /** - * This class provides utilities to read properties from a properties - * file, and optionally get notifications of future changes + * This class provides utilities to read properties from a properties file, and optionally get + * notifications of future changes. */ -public class PropertyUtil -{ - - // timer thread used for polling for property file changes - private static Timer timer = null; - - // this table maps canonical file into a 'ListenerRegistration' instance - private static HashMap<File, ListenerRegistration> registrations = - new HashMap<>(); - - /** - * Read in a properties file - * @param file the properties file - * @return a Properties object, containing the associated properties - * @throws IOException - subclass 'FileNotFoundException' if the file - * does not exist or can't be opened, and 'IOException' if there is - * a problem loading the properties file. - */ - public static Properties getProperties(File file) throws IOException - { - // create an InputStream (may throw a FileNotFoundException) - FileInputStream fis = new FileInputStream(file); - try - { - // create the properties instance - Properties rval = new Properties(); - - // load properties (may throw an IOException) - rval.load(fis); - return rval; - } - finally - { - // close input stream - fis.close(); - } - } - - /** - * Read in a properties file - * @param fileName the properties file - * @return a Properties object, containing the associated properties - * @throws IOException - subclass 'FileNotFoundException' if the file - * does not exist or can't be opened, and 'IOException' if there is - * a problem loading the properties file. - */ - public static Properties getProperties(String fileName) throws IOException - { - return getProperties(new File(fileName)); - } - - /* ============================================================ */ - - /** - * This is the callback interface, used for sending notifications of - * changes in the properties file. - */ - @FunctionalInterface - public interface Listener - { - /** - * Notification of a properties file change - * @param properties the new properties - * @param the set of property names that have changed, including - * additions and removals - */ - void propertiesChanged(Properties properties, Set<String> changedKeys); - } - - /** - * This is an internal class - one instance of this exists for each - * property file that is being monitored. Note that multiple listeners - * can be registered for the same file. - */ - private static class ListenerRegistration - { - // the canonical path of the file being monitored - File file; - - // the most recent value of 'file.lastModified()' - long lastModified; - - // the most recent set of properties - Properties properties; - - // the set of listeners monitoring this file - LinkedList<Listener> listeners; - - // the 'TimerTask' instance, used for periodic polling - TimerTask timerTask; - - /** - * Constructor - create a 'ListenerRegistration' instance for this - * file, but with no listeners - */ - ListenerRegistration(File file) throws IOException - { - this.file = file; - - // The initial value of 'lastModified' is set to 0 to ensure that we - // correctly handle the case where the file is modified within the - // same second that polling begins. - lastModified = 0; - - // fetch current properties - properties = getProperties(file); - - // no listeners yet - listeners = new LinkedList<>(); - - // add to static table, so this instance can be shared - registrations.put(file, this); - - if (timer == null) - { - // still need to create a timer thread - synchronized(PropertyUtil.class) - { - // an additional check is added inside the 'synchronized' block, - // just in case someone beat us to it - if (timer == null) - { - timer = new Timer("PropertyUtil-Timer", true); - } - } - } - - // create and schedule the timer task, so this is periodically polled - timerTask = new TimerTask() - { - @Override - public void run() - { - try - { - poll(); - } - catch (Exception e) - { - System.err.println(e); - } - } - }; - timer.schedule(timerTask, 10000L, 10000L); - } - - /** - * Add a listener to the notification list - * @param listener this is the listener to add to the list - * @return the properties at the moment the listener was added to the list - */ - synchronized Properties addListener(Listener listener) - { - listeners.add(listener); - return (Properties)properties.clone(); - } - - /** - * Remove a listener from the notification list - * @param listener this is the listener to remove - */ - synchronized void removeListener(Listener listener) - { - listeners.remove(listener); - - // See if we need to remove this 'ListenerRegistration' instance - // from the table. The 'synchronized' block is needed in case - // another listener is being added at about the same time that this - // one is being removed. - synchronized(registrations) - { - if (listeners.isEmpty()) - { - timerTask.cancel(); - registrations.remove(file); - } - } - } - - /** - * This method is periodically called to check for property list updates - * @throws IOException if there is an error in reading the properties file - */ - synchronized void poll() throws IOException - { - long timestamp = file.lastModified(); - if (timestamp != lastModified) - { - // update the record, and send out the notifications - lastModified = timestamp; - - // Save old set, and initial set of changed properties. - Properties oldProperties = properties; - HashSet<String> changedProperties = - new HashSet<>(oldProperties.stringPropertyNames()); - - // Fetch the list of listeners that we will potentially notify, - // and the new properties. Note that this is in a 'synchronized' - // block to ensure that all listeners receiving notifications - // actually have a newer list of properties than the one - // returned on the initial 'getProperties' call. - properties = getProperties(file); - - Set<String> newPropertyNames = properties.stringPropertyNames(); - changedProperties.addAll(newPropertyNames); - - // At this point, 'changedProperties' is the union of all properties - // in both the old and new properties files. Iterate through all - // of the entries in the new properties file - if the entry - // matches the one in the old file, remove it from - // 'changedProperties'. - for (String name : newPropertyNames) - { - if (properties.getProperty(name).equals - (oldProperties.getProperty(name))) - { - // Apparently, any property that exists must be of type - // 'String', and can't be null. For this reason, we don't - // need to worry about the case where - // 'properties.getProperty(name)' returns 'null'. Note that - // 'oldProperties.getProperty(name)' may be 'null' if the - // old property does not exist. - changedProperties.remove(name); - } - } - - // 'changedProperties' should be correct at this point - if (!changedProperties.isEmpty()) - { - // there were changes - notify everyone in 'listeners' - for (final Listener notify : listeners) - { - // Copy 'properties' and 'changedProperties', so it doesn't - // cause problems if the recipient makes changes. - final Properties tmpProperties = - (Properties)(properties.clone()); - final HashSet<String> tmpChangedProperties = - new HashSet<>(changedProperties); - - // Do the notification in a separate thread, so blocking - // won't cause any problems. - new Thread() - { - @Override - public void run() - { - notify.propertiesChanged - (tmpProperties, tmpChangedProperties); - } - }.start(); - } - } - } - } - } - - /** - * Read in a properties file, and register for update notifications. - * NOTE: it is possible that the first callback will occur while this - * method is still in progress. To avoid this problem, use 'synchronized' - * blocks around this invocation and in the callback -- that will ensure - * that the processing of the initial properties complete before any - * updates are processed. - * - * @param file the properties file - * @param notify if not null, this is a callback interface that is used for - * notifications of changes - * @return a Properties object, containing the associated properties - * @throws IOException - subclass 'FileNotFoundException' if the file - * does not exist or can't be opened, and 'IOException' if there is - * a problem loading the properties file. - */ - public static Properties getProperties(File file, Listener listener) - throws IOException - { - if (listener == null) - { - // no listener specified -- just fetch the properties - return getProperties(file); - } - - // Convert the file to a canonical form in order to avoid the situation - // where different names refer to the same file. - File tempFile = file.getCanonicalFile(); - - // See if there is an existing registration. The 'synchronized' block - // is needed to handle the case where a new listener is added at about - // the same time that another one is being removed. - synchronized(registrations) - { - ListenerRegistration reg = registrations.get(tempFile); - if (reg == null) - { - // a new registration is needed - reg = new ListenerRegistration(tempFile); - } - return reg.addListener(listener); - } - } - - /** - * Read in a properties file, and register for update notifications. - * NOTE: it is possible that the first callback will occur while this - * method is still in progress. To avoid this problem, use 'synchronized' - * blocks around this invocation and in the callback -- that will ensure - * that the processing of the initial properties complete before any - * updates are processed. - * - * @param fileName the properties file - * @param notify if not null, this is a callback interface that is used for - * notifications of changes - * @return a Properties object, containing the associated properties - * @throws IOException - subclass 'FileNotFoundException' if the file - * does not exist or can't be opened, and 'IOException' if there is - * a problem loading the properties file. - */ - public static Properties getProperties(String fileName, Listener listener) - throws IOException - { - return getProperties(new File(fileName), listener); - } - - /** - * Stop listenening for updates - * @param file the properties file - * @param notify if not null, this is a callback interface that was used for - * notifications of changes - * @throws IOException - */ - public static void stopListening(File file, Listener listener) throws IOException - { - if (listener != null) - { - ListenerRegistration reg = registrations.get(file.getCanonicalFile()); - if (reg != null) - { - reg.removeListener(listener); - } - } - } - - /** - * Stop listenening for updates - * @param fileName the properties file - * @param notify if not null, this is a callback interface that was used for - * notifications of changes - * @throws IOException - */ - public static void stopListening(String fileName, Listener listener) throws IOException - { - stopListening(new File(fileName), listener); - } - -} +public class PropertyUtil { + + // timer thread used for polling for property file changes + private static Timer timer = null; + + // this table maps canonical file into a 'ListenerRegistration' instance + private static HashMap<File, ListenerRegistration> registrations = new HashMap<>(); + + /** + * Read in a properties file + * + * @param file the properties file + * @return a Properties object, containing the associated properties + * @throws IOException - subclass 'FileNotFoundException' if the file does not exist or can't be + * opened, and 'IOException' if there is a problem loading the properties file. + */ + public static Properties getProperties(File file) throws IOException { + // create an InputStream (may throw a FileNotFoundException) + FileInputStream fis = new FileInputStream(file); + try { + // create the properties instance + Properties rval = new Properties(); + + // load properties (may throw an IOException) + rval.load(fis); + return rval; + } finally { + // close input stream + fis.close(); + } + } + + /** + * Read in a properties file + * + * @param fileName the properties file + * @return a Properties object, containing the associated properties + * @throws IOException - subclass 'FileNotFoundException' if the file does not exist or can't be + * opened, and 'IOException' if there is a problem loading the properties file. + */ + public static Properties getProperties(String fileName) throws IOException { + return getProperties(new File(fileName)); + } + + /* ============================================================ */ + + /** + * This is the callback interface, used for sending notifications of changes in the properties + * file. + */ + @FunctionalInterface + public interface Listener { + /** + * Notification of a properties file change. + * + * @param properties the new properties + * @param changedKeys the set of property names that have changed, including additions and + * removals + */ + void propertiesChanged(Properties properties, Set<String> changedKeys); + } + + /** + * This is an internal class - one instance of this exists for each property file that is being + * monitored. Note that multiple listeners can be registered for the same file. + */ + private static class ListenerRegistration { + // the canonical path of the file being monitored + File file; + + // the most recent value of 'file.lastModified()' + long lastModified; + + // the most recent set of properties + Properties properties; + + // the set of listeners monitoring this file + LinkedList<Listener> listeners; + + // the 'TimerTask' instance, used for periodic polling + TimerTask timerTask; + + /** + * Constructor - create a 'ListenerRegistration' instance for this file, but with no + * listeners. + */ + ListenerRegistration(File file) throws IOException { + this.file = file; + + // The initial value of 'lastModified' is set to 0 to ensure that we + // correctly handle the case where the file is modified within the + // same second that polling begins. + lastModified = 0; + + // fetch current properties + properties = getProperties(file); + + // no listeners yet + listeners = new LinkedList<>(); + + // add to static table, so this instance can be shared + registrations.put(file, this); + + if (timer == null) { + // still need to create a timer thread + synchronized (PropertyUtil.class) { + // an additional check is added inside the 'synchronized' block, + // just in case someone beat us to it + if (timer == null) { + timer = new Timer("PropertyUtil-Timer", true); + } + } + } + + // create and schedule the timer task, so this is periodically polled + timerTask = new TimerTask() { + @Override + public void run() { + try { + poll(); + } catch (Exception e) { + System.err.println(e); + } + } + }; + timer.schedule(timerTask, 10000L, 10000L); + } + + /** + * Add a listener to the notification list. + * + * @param listener this is the listener to add to the list + * @return the properties at the moment the listener was added to the list + */ + synchronized Properties addListener(Listener listener) { + listeners.add(listener); + return (Properties) properties.clone(); + } + + /** + * Remove a listener from the notification list. + * + * @param listener this is the listener to remove + */ + synchronized void removeListener(Listener listener) { + listeners.remove(listener); + + // See if we need to remove this 'ListenerRegistration' instance + // from the table. The 'synchronized' block is needed in case + // another listener is being added at about the same time that this + // one is being removed. + synchronized (registrations) { + if (listeners.isEmpty()) { + timerTask.cancel(); + registrations.remove(file); + } + } + } + + /** + * This method is periodically called to check for property list updates. + * + * @throws IOException if there is an error in reading the properties file + */ + synchronized void poll() throws IOException { + long timestamp = file.lastModified(); + if (timestamp != lastModified) { + // update the record, and send out the notifications + lastModified = timestamp; + + // Save old set, and initial set of changed properties. + Properties oldProperties = properties; + HashSet<String> changedProperties = new HashSet<>(oldProperties.stringPropertyNames()); + + // Fetch the list of listeners that we will potentially notify, + // and the new properties. Note that this is in a 'synchronized' + // block to ensure that all listeners receiving notifications + // actually have a newer list of properties than the one + // returned on the initial 'getProperties' call. + properties = getProperties(file); + + Set<String> newPropertyNames = properties.stringPropertyNames(); + changedProperties.addAll(newPropertyNames); + + // At this point, 'changedProperties' is the union of all properties + // in both the old and new properties files. Iterate through all + // of the entries in the new properties file - if the entry + // matches the one in the old file, remove it from + // 'changedProperties'. + for (String name : newPropertyNames) { + if (properties.getProperty(name).equals(oldProperties.getProperty(name))) { + // Apparently, any property that exists must be of type + // 'String', and can't be null. For this reason, we don't + // need to worry about the case where + // 'properties.getProperty(name)' returns 'null'. Note that + // 'oldProperties.getProperty(name)' may be 'null' if the + // old property does not exist. + changedProperties.remove(name); + } + } + + // 'changedProperties' should be correct at this point + if (!changedProperties.isEmpty()) { + // there were changes - notify everyone in 'listeners' + for (final Listener notify : listeners) { + // Copy 'properties' and 'changedProperties', so it doesn't + // cause problems if the recipient makes changes. + final Properties tmpProperties = (Properties) (properties.clone()); + final HashSet<String> tmpChangedProperties = new HashSet<>(changedProperties); + + // Do the notification in a separate thread, so blocking + // won't cause any problems. + new Thread() { + @Override + public void run() { + notify.propertiesChanged(tmpProperties, tmpChangedProperties); + } + }.start(); + } + } + } + } + } + + /** + * Read in a properties file, and register for update notifications. NOTE: it is possible that + * the first callback will occur while this method is still in progress. To avoid this problem, + * use 'synchronized' blocks around this invocation and in the callback -- that will ensure that + * the processing of the initial properties complete before any updates are processed. + * + * @param file the properties file + * @param listener notify if not null, this is a callback interface that is used for + * notifications of changes + * @return a Properties object, containing the associated properties + * @throws IOException - subclass 'FileNotFoundException' if the file does not exist or can't be + * opened, and 'IOException' if there is a problem loading the properties file. + */ + public static Properties getProperties(File file, Listener listener) throws IOException { + if (listener == null) { + // no listener specified -- just fetch the properties + return getProperties(file); + } + + // Convert the file to a canonical form in order to avoid the situation + // where different names refer to the same file. + File tempFile = file.getCanonicalFile(); + + // See if there is an existing registration. The 'synchronized' block + // is needed to handle the case where a new listener is added at about + // the same time that another one is being removed. + synchronized (registrations) { + ListenerRegistration reg = registrations.get(tempFile); + if (reg == null) { + // a new registration is needed + reg = new ListenerRegistration(tempFile); + } + return reg.addListener(listener); + } + } + + /** + * Read in a properties file, and register for update notifications. NOTE: it is possible that + * the first callback will occur while this method is still in progress. To avoid this problem, + * use 'synchronized' blocks around this invocation and in the callback -- that will ensure that + * the processing of the initial properties complete before any updates are processed. + * + * @param fileName the properties file + * @param listener notify if not null, this is a callback interface that is used for + * notifications of changes + * @return a Properties object, containing the associated properties + * @throws IOException - subclass 'FileNotFoundException' if the file does not exist or can't be + * opened, and 'IOException' if there is a problem loading the properties file. + */ + public static Properties getProperties(String fileName, Listener listener) throws IOException { + return getProperties(new File(fileName), listener); + } + + /** + * Stop listenening for updates. + * + * @param file the properties file + * @param listener notify if not null, this is a callback interface that was used for + * notifications of changes + * @throws IOException If an I/O error occurs + */ + public static void stopListening(File file, Listener listener) throws IOException { + if (listener != null) { + ListenerRegistration reg = registrations.get(file.getCanonicalFile()); + if (reg != null) { + reg.removeListener(listener); + } + } + } + + /** + * Stop listenening for updates. + * + * @param fileName the properties file + * @param listener notify if not null, this is a callback interface that was used for + * notifications of changes + * @throws IOException If an I/O error occurs + */ + public static void stopListening(String fileName, Listener listener) throws IOException { + stopListening(new File(fileName), listener); + } + +} diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/SystemOutLogger.java b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/SystemOutLogger.java index 825799b9..70ad08ae 100644 --- a/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/SystemOutLogger.java +++ b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/SystemOutLogger.java @@ -20,485 +20,510 @@ package org.onap.policy.common.logging.flexlogger; +import com.att.eelf.configuration.EELFLogger.Level; + import java.io.Serializable; import java.util.Arrays; import java.util.UUID; import org.onap.policy.common.logging.eelf.MessageCodes; import org.onap.policy.common.logging.eelf.PolicyLogger; -import com.att.eelf.configuration.EELFLogger.Level; /** - * * SystemOutLogger implements all the methods of interface Logger by calling System.out.println - * */ public class SystemOutLogger implements Logger, Serializable { - - /** - * - */ - private static final long serialVersionUID = 4956408061058933929L; - private String className = ""; - private boolean isDebugEnabled = true; - private boolean isInfoEnabled = true; - private boolean isWarnEnabled = true; - private boolean isErrorEnabled = true; - private boolean isAuditEnabled = true; - private boolean isMetricsEnabled = true; - private String transId = UUID.randomUUID().toString(); - - /** - * Constructor - * @param clazz - */ - public SystemOutLogger (Class<?> clazz){ - System.out.println("create instance of SystemOutLogger"); - if(clazz != null){ - className = clazz.getName(); - } + + private static final long serialVersionUID = 4956408061058933929L; + private String className = ""; + private boolean isDebugEnabled = true; + private boolean isInfoEnabled = true; + private boolean isWarnEnabled = true; + private boolean isErrorEnabled = true; + private boolean isAuditEnabled = true; + private boolean isMetricsEnabled = true; + private String transId = UUID.randomUUID().toString(); + + /** + * Constructor. + * + * @param clazz the class + */ + public SystemOutLogger(Class<?> clazz) { + System.out.println("create instance of SystemOutLogger"); + if (clazz != null) { + className = clazz.getName(); + } initLevel(); - } - + } + /** - * Constructor - * @param s + * Constructor. + * + * @param className the class name */ - public SystemOutLogger (String s){ - System.out.println("create instance of SystemOutLogger"); - if(s != null){ - className = s; - } + public SystemOutLogger(String className) { + System.out.println("create instance of SystemOutLogger"); + if (className != null) { + this.className = className; + } initLevel(); - } - - /** - * Sets logging levels - */ - private void initLevel(){ - - if(PolicyLogger.getDebugLevel() == Level.DEBUG){ - isDebugEnabled = true; - isInfoEnabled = true; - isWarnEnabled = true; - }else{ - isDebugEnabled = false; - } - - if(PolicyLogger.getDebugLevel() == Level.INFO){ - isInfoEnabled = true; - isWarnEnabled = true; - isDebugEnabled = false; - } - - if(PolicyLogger.getDebugLevel() == Level.OFF){ - isInfoEnabled = false; - isWarnEnabled = false; - isDebugEnabled = false; - } - - if(PolicyLogger.getErrorLevel() == Level.OFF){ - isErrorEnabled = false; - } - - if(PolicyLogger.getAuditLevel() == Level.OFF){ - isAuditEnabled = false; - } - - if(PolicyLogger.getMetricsLevel() == Level.OFF){ - isMetricsEnabled = false; - } - } - - /** - * Sets transaction Id - */ - @Override - public void setTransId(String transId){ - - System.out.println(transId); - this.transId = transId; - } - - /** - * Returns transaction Id - */ - @Override - public String getTransId(){ - - return transId; - } - - /** - * Records a message - * @param message - */ - @Override - public void debug(Object message) { - - System.out.println(transId + "|" + className+" : "+message); - } - - /** - * Records an error message - * @param message - */ - @Override - public void error(Object message) { - - System.out.println(transId + "|" + className+" : "+message); - } - - /** - * Records a message - * @param message - */ - @Override - public void info(Object message) { - - System.out.println(transId + "|" + className+" : "+message); - - } - - /** - * Records a message - * @param message - */ - @Override - public void warn(Object message) { - - System.out.println(transId + "|" + className+" : "+message); - } - - /** - * Records a message - * @param message - */ - @Override - public void trace(Object message) { - - System.out.println(transId + "|" + className+" : "+message); - } - - /** - * Returns true for debug enabled, or false for not - * @return boolean - */ - @Override - public boolean isDebugEnabled(){ - - return isDebugEnabled; - } - - /** - * Returns true for warn enabled, or false for not - * @return boolean - */ - @Override - public boolean isWarnEnabled(){ - - return isWarnEnabled; - } - - /** - * Returns true for info enabled, or false for not - * @return boolean - */ - @Override - public boolean isInfoEnabled(){ - - return isInfoEnabled; - } - - /** - * Returns true for error enabled, or false for not - * @return boolean - */ - @Override - public boolean isErrorEnabled(){ - - return isErrorEnabled; - } - - /** - * Returns true for audit enabled, or false for not - * @return boolean - */ - @Override - public boolean isAuditEnabled(){ - - return isAuditEnabled; - } - - /** - * Returns true for metrics enabled, or false for not - * @return boolean - */ - @Override - public boolean isMetricsEnabled(){ - - return isMetricsEnabled; - } - - /** - * Records an audit message - * @param arg0 - */ - @Override - public void audit(Object arg0) { - - System.out.println(transId + "|" +className+" : "+arg0); - } - - /** - * Records an audit message - * @param eventId - */ - @Override - public void recordAuditEventStart(String eventId) { - - System.out.println(transId + "|" +className+" : "+eventId); - - } - - /** - * Records an audit message - * @param eventId - */ - @Override - public void recordAuditEventStart(UUID eventId) { - - System.out.println(eventId); - } - - /** - * Records an audit message - * @param eventId - * @param rule - * @param policyVersion - */ - @Override - public void recordAuditEventEnd(String eventId, String rule, String policyVersion) { - - System.out.println(className+" : "+eventId + ":" + rule + ":" + policyVersion); - } - - /** - * Records an audit message - * @param eventId - * @param rule - * @param policyVersion - */ - @Override - public void recordAuditEventEnd(UUID eventId, String rule, String policyVersion) { - - System.out.println(className+" : "+eventId + ":" + rule + ":" + policyVersion); - } - - /** - * Records an audit message - * @param eventId - * @param rule - */ - @Override - public void recordAuditEventEnd(String eventId, String rule) { - - System.out.println(className+" : "+eventId + ":" + rule); - } - - /** - * Records an audit message - * @param eventId - * @param rule - */ - @Override - public void recordAuditEventEnd(UUID eventId, String rule) { - - System.out.println(className+" : "+eventId + ":" + rule); - } - - /** - * Records a metrics message - * @param eventId - * @param arg1 - */ - @Override - public void recordMetricEvent(String eventId, String arg1) { - - System.out.println(className+" : "+"eventId:" + eventId + "message:" + arg1); - - } - - /** - * Records a metrics message - * @param eventId - * @param arg1 - */ - @Override - public void recordMetricEvent(UUID eventId, String arg1) { - - System.out.println(className+" : "+eventId + ":" + arg1); - } - - /** - * Records a metrics message - * @param arg0 - */ - @Override - public void metrics(Object arg0) { - - System.out.println(className+" : "+arg0); - } - - /** - * Records an error message - * @param msg - * @param arg0 - * @param arguments - */ - @Override - public void error(MessageCodes msg, Throwable arg0, String... arguments){ - - System.out.println(className+" : "+"MessageCodes :" + msg + Arrays.asList(arguments)); - - } - - /** - * Records an error message - * @param msg - * @param arguments - */ - @Override - public void error(MessageCodes msg, String... arguments){ - - System.out.println(transId + "|" + className+" : "+"MessageCode:" + msg + Arrays.asList(arguments)); - } - - /** - * Returns transaction Id - * @param transId - */ - @Override - public String postMDCInfoForEvent(String transId) { - - String transactionId = transId; - if(transactionId == null || transactionId.isEmpty()){ - transactionId = UUID.randomUUID().toString(); - } - - return transactionId; - } - - /** - * Records a message - * @param msg - * @param arguments - */ - @Override - public void warn(MessageCodes msg, String... arguments){ - - System.out.println(transId + "|" + className+" : "+"MessageCodes:" + msg + Arrays.asList(arguments)); - } - - /** - * Records a message - * @param msg - * @param arg0 - * @param arguments - */ - @Override - public void warn(MessageCodes msg, Throwable arg0, String... arguments){ - - System.out.println(transId + "|" + className+" : "+"MessageCodes:" + msg + Arrays.asList(arguments)); - - } - - /** - * Records a message - * @param message - * @param t - */ - @Override - public void debug(Object message, Throwable t) { - System.out.println(transId + "|" + className+" : "+ message + ":" + t); - } - - /** - * Records an error message - * @param message - * @param t - */ - @Override - public void error(Object message, Throwable t) { - System.out.println(transId + "|" + className+" : "+ message + ":" + t); - } - - /** - * Records a message - * @param message - * @param t - */ - @Override - public void info(Object message, Throwable t) { - System.out.println(transId + "|" + className+" : "+ message + ":" + t); - } - - /** - * Records a message - * @param message - * @param t - */ - @Override - public void warn(Object message, Throwable t) { - System.out.println(transId + "|" + className+" : "+ message + ":" + t); - } - - /** - * Records a message - * @param message - * @param t - */ - @Override - public void trace(Object message, Throwable t) { - System.out.println(transId + "|" + className+" : "+ message + ":" + t); - } - - /** - * Records an audit message - * @param arg0 - * @param t - */ - @Override - public void audit(Object arg0, Throwable t) { - System.out.println(transId + "|" + className+" : "+ arg0 + ":" + t); - } - - /** - * Returns true for trace enabled, or false for not - * @return boolean - */ - @Override - public boolean isTraceEnabled() { - // default - return false; - } - - /** - * Records transaction Id - * @param transId - */ - @Override - public void postMDCInfoForTriggeredRule(String transId){ - - System.out.println(transId); - } - - /** - * Records transaction Id - * @param o - */ - @Override - public void postMDCInfoForEvent(Object o){ - System.out.println(o); - } + } + + /** + * Sets logging levels. + */ + private void initLevel() { + + if (PolicyLogger.getDebugLevel() == Level.DEBUG) { + isDebugEnabled = true; + isInfoEnabled = true; + isWarnEnabled = true; + } else { + isDebugEnabled = false; + } + + if (PolicyLogger.getDebugLevel() == Level.INFO) { + isInfoEnabled = true; + isWarnEnabled = true; + isDebugEnabled = false; + } + + if (PolicyLogger.getDebugLevel() == Level.OFF) { + isInfoEnabled = false; + isWarnEnabled = false; + isDebugEnabled = false; + } + + if (PolicyLogger.getErrorLevel() == Level.OFF) { + isErrorEnabled = false; + } + + if (PolicyLogger.getAuditLevel() == Level.OFF) { + isAuditEnabled = false; + } + + if (PolicyLogger.getMetricsLevel() == Level.OFF) { + isMetricsEnabled = false; + } + } + + /** + * Sets transaction Id. + */ + @Override + public void setTransId(String transId) { + + System.out.println(transId); + this.transId = transId; + } + + /** + * Returns transaction Id. + */ + @Override + public String getTransId() { + + return transId; + } + + /** + * Records a message. + * + * @param message the message + */ + @Override + public void debug(Object message) { + + System.out.println(transId + "|" + className + " : " + message); + } + + /** + * Records a message. + * + * @param message the message + * @param throwable the throwable + */ + @Override + public void debug(Object message, Throwable throwable) { + System.out.println(transId + "|" + className + " : " + message + ":" + throwable); + } + + /** + * Records an error message. + * + * @param message the message + */ + @Override + public void error(Object message) { + + System.out.println(transId + "|" + className + " : " + message); + } + + /** + * Records an error message. + * + * @param message the message + * @param throwable the throwable + */ + @Override + public void error(Object message, Throwable throwable) { + System.out.println(transId + "|" + className + " : " + message + ":" + throwable); + } + + /** + * Records an error message. + * + * @param msg the message code + * @param throwable the throwable + * @param arguments the messages + */ + @Override + public void error(MessageCodes msg, Throwable throwable, String... arguments) { + System.out.println(className + " : " + "MessageCodes :" + msg + Arrays.asList(arguments)); + } + + /** + * Records an error message. + * + * @param msg the message code + * @param arguments the messages + */ + @Override + public void error(MessageCodes msg, String... arguments) { + + System.out.println(transId + "|" + className + " : " + "MessageCode:" + msg + Arrays.asList(arguments)); + } + + /** + * Records a message. + * + * @param message the message + */ + @Override + public void info(Object message) { + System.out.println(transId + "|" + className + " : " + message); + } + + /** + * Records a message. + * + * @param message the message + * @param throwable the throwable + */ + @Override + public void info(Object message, Throwable throwable) { + System.out.println(transId + "|" + className + " : " + message + ":" + throwable); + } + + /** + * Records a message. + * + * @param message the message + */ + @Override + public void warn(Object message) { + System.out.println(transId + "|" + className + " : " + message); + } + + /** + * Records a message. + * + * @param message the message + * @param throwable the throwable + */ + @Override + public void warn(Object message, Throwable throwable) { + System.out.println(transId + "|" + className + " : " + message + ":" + throwable); + } + + /** + * Records a message. + * + * @param msg the message code + * @param arguments the messages + */ + @Override + public void warn(MessageCodes msg, String... arguments) { + + System.out.println(transId + "|" + className + " : " + "MessageCodes:" + msg + Arrays.asList(arguments)); + } + + /** + * Records a message. + * + * @param msg the message code + * @param throwable the throwable + * @param arguments the messages + */ + @Override + public void warn(MessageCodes msg, Throwable throwable, String... arguments) { + + System.out.println(transId + "|" + className + " : " + "MessageCodes:" + msg + Arrays.asList(arguments)); + + } + + /** + * Records a message. + * + * @param message the message + */ + @Override + public void trace(Object message) { + System.out.println(transId + "|" + className + " : " + message); + } + + /** + * Records a message. + * + * @param message the message + * @param throwable the throwable + */ + @Override + public void trace(Object message, Throwable throwable) { + System.out.println(transId + "|" + className + " : " + message + ":" + throwable); + } + + /** + * Returns true for debug enabled, or false for not. + * + * @return boolean + */ + @Override + public boolean isDebugEnabled() { + return isDebugEnabled; + } + + /** + * Returns true for warn enabled, or false for not. + * + * @return boolean + */ + @Override + public boolean isWarnEnabled() { + return isWarnEnabled; + } + + /** + * Returns true for info enabled, or false for not. + * + * @return boolean + */ + @Override + public boolean isInfoEnabled() { + return isInfoEnabled; + } + + /** + * Returns true for error enabled, or false for not. + * + * @return boolean + */ + @Override + public boolean isErrorEnabled() { + return isErrorEnabled; + } + + /** + * Returns true for audit enabled, or false for not. + * + * @return boolean + */ + @Override + public boolean isAuditEnabled() { + + return isAuditEnabled; + } + + /** + * Returns true for metrics enabled, or false for not. + * + * @return boolean + */ + @Override + public boolean isMetricsEnabled() { + + return isMetricsEnabled; + } + + /** + * Records an audit message. + * + * @param message the message + */ + @Override + public void audit(Object message) { + + System.out.println(transId + "|" + className + " : " + message); + } + + /** + * Records an audit message. + * + * @param message the message + * @param throwable the throwable + */ + @Override + public void audit(Object message, Throwable throwable) { + System.out.println(transId + "|" + className + " : " + message + ":" + throwable); + } + + /** + * Records an audit message. + * + * @param eventId the event ID + */ + @Override + public void recordAuditEventStart(String eventId) { + + System.out.println(transId + "|" + className + " : " + eventId); + + } + + /** + * Records an audit message. + * + * @param eventId the event ID + */ + @Override + public void recordAuditEventStart(UUID eventId) { + + System.out.println(eventId); + } + + /** + * Records an audit message. + * + * @param eventId the event ID + * @param rule the rule + * @param policyVersion the policy version + */ + @Override + public void recordAuditEventEnd(String eventId, String rule, String policyVersion) { + + System.out.println(className + " : " + eventId + ":" + rule + ":" + policyVersion); + } + + /** + * Records an audit message. + * + * @param eventId the event ID + * @param rule the rule + * @param policyVersion the policy version + */ + @Override + public void recordAuditEventEnd(UUID eventId, String rule, String policyVersion) { + + System.out.println(className + " : " + eventId + ":" + rule + ":" + policyVersion); + } + + /** + * Records an audit message. + * + * @param eventId the event ID + * @param rule the rule + */ + @Override + public void recordAuditEventEnd(String eventId, String rule) { + + System.out.println(className + " : " + eventId + ":" + rule); + } + + /** + * Records an audit message. + * + * @param eventId the event ID + * @param rule the rule + */ + @Override + public void recordAuditEventEnd(UUID eventId, String rule) { + + System.out.println(className + " : " + eventId + ":" + rule); + } + + /** + * Records a metrics message. + * + * @param eventId the event ID + * @param message the message + */ + @Override + public void recordMetricEvent(String eventId, String message) { + + System.out.println(className + " : " + "eventId:" + eventId + "message:" + message); + + } + + /** + * Records a metrics message. + * + * @param eventId the event ID + * @param message the message + */ + @Override + public void recordMetricEvent(UUID eventId, String message) { + + System.out.println(className + " : " + eventId + ":" + message); + } + + /** + * Records a metrics message. + * + * @param message the message + */ + @Override + public void metrics(Object message) { + + System.out.println(className + " : " + message); + } + + /** + * Returns transaction Id. + * + * @param transId the transaction ID + */ + @Override + public String postMDCInfoForEvent(String transId) { + + String transactionId = transId; + if (transactionId == null || transactionId.isEmpty()) { + transactionId = UUID.randomUUID().toString(); + } + + return transactionId; + } + + /** + * Records transaction Id. + * + * @param message the message + */ + @Override + public void postMDCInfoForEvent(Object message) { + System.out.println(message); + } + + + /** + * Returns true for trace enabled, or false for not. + * + * @return boolean + */ + @Override + public boolean isTraceEnabled() { + // default + return false; + } + + /** + * Records transaction Id. + * + * @param transId the transaction ID + */ + @Override + public void postMDCInfoForTriggeredRule(String transId) { + + System.out.println(transId); + } + } diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/nsa/LoggingContext.java b/common-logging/src/main/java/org/onap/policy/common/logging/nsa/LoggingContext.java index 0786febd..a8dde087 100644 --- a/common-logging/src/main/java/org/onap/policy/common/logging/nsa/LoggingContext.java +++ b/common-logging/src/main/java/org/onap/policy/common/logging/nsa/LoggingContext.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-Logging * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,41 +21,44 @@ package org.onap.policy.common.logging.nsa; /** - * An interface for providing data into the underlying logging context. Systems should use - * this interface rather than log system specific MDC solutions in order to reduce dependencies. + * An interface for providing data into the underlying logging context. Systems should use this + * interface rather than log system specific MDC solutions in order to reduce dependencies. * - * A LoggingContext is specific to the calling thread. + * <p>A LoggingContext is specific to the calling thread. * */ -public interface LoggingContext -{ - /** - * Put a key/value pair into the logging context, replacing an entry with the same key. - * @param key - * @param value - */ - void put ( String key, String value ); +public interface LoggingContext { + /** + * Put a key/value pair into the logging context, replacing an entry with the same key. + * + * @param key the key + * @param value the value + */ + void put(String key, String value); - /** - * Put a key/value pair into the logging context, replacing an entry with the same key. - * @param key - * @param value - */ - void put ( String key, long value ); + /** + * Put a key/value pair into the logging context, replacing an entry with the same key. + * + * @param key the key + * @param value the value + */ + void put(String key, long value); - /** - * Get a string value, returning the default value if the value is missing. - * @param key - * @param defaultValue - * @return a string value - */ - String get ( String key, String defaultValue ); - - /** - * Get a long value, returning the default value if the value is missing or not a long. - * @param key - * @param defaultValue - * @return a long value - */ - long get ( String key, long defaultValue ); + /** + * Get a string value, returning the default value if the value is missing. + * + * @param key the key + * @param defaultValue the default value + * @return a string value + */ + String get(String key, String defaultValue); + + /** + * Get a long value, returning the default value if the value is missing or not a long. + * + * @param key the key + * @param defaultValue the default value + * @return a long value + */ + long get(String key, long defaultValue); } diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/nsa/LoggingContextFactory.java b/common-logging/src/main/java/org/onap/policy/common/logging/nsa/LoggingContextFactory.java index b2ad76ca..85600671 100644 --- a/common-logging/src/main/java/org/onap/policy/common/logging/nsa/LoggingContextFactory.java +++ b/common-logging/src/main/java/org/onap/policy/common/logging/nsa/LoggingContextFactory.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-Logging * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,37 +20,31 @@ package org.onap.policy.common.logging.nsa; - import org.onap.policy.common.logging.nsa.impl.SharedContext; import org.onap.policy.common.logging.nsa.impl.Slf4jLoggingContext; /** - * A factory for setting up a LoggingContext + * A factory for setting up a LoggingContext. * */ -public class LoggingContextFactory -{ - public static class Builder - { +public class LoggingContextFactory { + public static class Builder { + + private LoggingContext baseContext = null; + private boolean forShared = false; - private LoggingContext fBase = null; - private boolean fShared = false; - - public Builder withBaseContext ( LoggingContext lc ) - { - fBase = lc; - return this; - } + public Builder withBaseContext(LoggingContext lc) { + baseContext = lc; + return this; + } - public Builder forSharing () - { - fShared = true; - return this; - } + public Builder forSharing() { + forShared = true; + return this; + } - public LoggingContext build () - { - return fShared ? new SharedContext ( fBase ) : new Slf4jLoggingContext ( fBase ); - } - } + public LoggingContext build() { + return forShared ? new SharedContext(baseContext) : new Slf4jLoggingContext(baseContext); + } + } } diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/nsa/SharedLoggingContext.java b/common-logging/src/main/java/org/onap/policy/common/logging/nsa/SharedLoggingContext.java index af0cc393..1d844fa0 100644 --- a/common-logging/src/main/java/org/onap/policy/common/logging/nsa/SharedLoggingContext.java +++ b/common-logging/src/main/java/org/onap/policy/common/logging/nsa/SharedLoggingContext.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-Logging * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,17 +21,17 @@ package org.onap.policy.common.logging.nsa; /** - * A logging context must be thread-specific. Contexts that implement SharedLoggingContext - * are expected to be shared across threads, and they have to be able to populate another - * logging context with their data. + * A logging context must be thread-specific. Contexts that implement SharedLoggingContext are + * expected to be shared across threads, and they have to be able to populate another logging + * context with their data. * */ -public interface SharedLoggingContext extends LoggingContext -{ - /** - * Copy this context's data to the given context. This must work across threads so that - * a base context can be shared in another thread. - * @param lc - */ - void transferTo ( SharedLoggingContext lc ); +public interface SharedLoggingContext extends LoggingContext { + /** + * Copy this context's data to the given context. This must work across threads so that a base + * context can be shared in another thread. + * + * @param lc the shared logging context + */ + void transferTo(SharedLoggingContext lc); } diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/nsa/impl/SharedContext.java b/common-logging/src/main/java/org/onap/policy/common/logging/nsa/impl/SharedContext.java index 97f61699..e5f5e65b 100644 --- a/common-logging/src/main/java/org/onap/policy/common/logging/nsa/impl/SharedContext.java +++ b/common-logging/src/main/java/org/onap/policy/common/logging/nsa/impl/SharedContext.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-Logging * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,32 +27,27 @@ import org.onap.policy.common.logging.nsa.LoggingContext; import org.onap.policy.common.logging.nsa.SharedLoggingContext; /** - * A shared logging context for SLF4J + * A shared logging context for SLF4J. * */ -public class SharedContext extends Slf4jLoggingContext implements SharedLoggingContext -{ - private final HashMap<String,String> fMap; - - public SharedContext ( LoggingContext base ) - { - super ( base ); - fMap = new HashMap<> (); - } +public class SharedContext extends Slf4jLoggingContext implements SharedLoggingContext { + private final HashMap<String, String> contextMap; - @Override - public void put ( String key, String value ) - { - super.put ( key, value ); - fMap.put ( key, value ); - } + public SharedContext(LoggingContext base) { + super(base); + contextMap = new HashMap<>(); + } - @Override - public void transferTo ( SharedLoggingContext lc ) - { - for ( Entry<String,String> e : fMap.entrySet () ) - { - lc.put ( e.getKey(), e.getValue() ); - } - } + @Override + public void put(String key, String value) { + super.put(key, value); + contextMap.put(key, value); + } + + @Override + public void transferTo(SharedLoggingContext lc) { + for (Entry<String, String> e : contextMap.entrySet()) { + lc.put(e.getKey(), e.getValue()); + } + } } diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/nsa/impl/Slf4jLoggingContext.java b/common-logging/src/main/java/org/onap/policy/common/logging/nsa/impl/Slf4jLoggingContext.java index 628d4b9e..80bb2383 100644 --- a/common-logging/src/main/java/org/onap/policy/common/logging/nsa/impl/Slf4jLoggingContext.java +++ b/common-logging/src/main/java/org/onap/policy/common/logging/nsa/impl/Slf4jLoggingContext.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-Logging * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,54 +20,42 @@ package org.onap.policy.common.logging.nsa.impl; -import org.slf4j.MDC; - import org.onap.policy.common.logging.nsa.LoggingContext; +import org.slf4j.MDC; /** - * A logging context for SLF4J + * A logging context for SLF4J. * */ -public class Slf4jLoggingContext implements LoggingContext -{ - public Slf4jLoggingContext ( LoggingContext base ) - { - } - - @Override - public void put ( String key, String value ) - { - MDC.put ( key, value ); - } - - @Override - public void put ( String key, long value ) - { - put ( key, Long.toString(value)); - } - - @Override - public String get ( String key, String defaultValue ) - { - String result = MDC.get ( key ); - if ( result == null ) - { - result = defaultValue; - } - return result; - } - - @Override - public long get ( String key, long defaultValue ) - { - final String str = get ( key, Long.toString(defaultValue)); - try - { - return Long.parseLong ( str ); - } - catch ( NumberFormatException x ) - { - return defaultValue; - } - } +public class Slf4jLoggingContext implements LoggingContext { + public Slf4jLoggingContext(LoggingContext base) {} + + @Override + public void put(String key, String value) { + MDC.put(key, value); + } + + @Override + public void put(String key, long value) { + put(key, Long.toString(value)); + } + + @Override + public String get(String key, String defaultValue) { + String result = MDC.get(key); + if (result == null) { + result = defaultValue; + } + return result; + } + + @Override + public long get(String key, long defaultValue) { + final String str = get(key, Long.toString(defaultValue)); + try { + return Long.parseLong(str); + } catch (NumberFormatException x) { + return defaultValue; + } + } } diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/nsa/package-info.java b/common-logging/src/main/java/org/onap/policy/common/logging/nsa/package-info.java index 6f58bb0f..76554c49 100644 --- a/common-logging/src/main/java/org/onap/policy/common/logging/nsa/package-info.java +++ b/common-logging/src/main/java/org/onap/policy/common/logging/nsa/package-info.java @@ -19,9 +19,10 @@ */ /** - * This package provides a logging context infrastructure and a corresponding - * implementation based on the SLF4J/Log4j "MDC" (Mapped Diagnostic Context) feature. + * This package provides a logging context infrastructure and a corresponding implementation based + * on the SLF4J/Log4j "MDC" (Mapped Diagnostic Context) feature. * */ + package org.onap.policy.common.logging.nsa; diff --git a/common-logging/src/main/resources/org/onap/policy/common/logging/eelf/Resources.properties b/common-logging/src/main/resources/org/onap/policy/common/logging/eelf/Resources.properties index b41dbb26..b344fac1 100644 --- a/common-logging/src/main/resources/org/onap/policy/common/logging/eelf/Resources.properties +++ b/common-logging/src/main/resources/org/onap/policy/common/logging/eelf/Resources.properties @@ -2,7 +2,7 @@ # ============LICENSE_START======================================================= # ONAP-Logging # ================================================================================ -# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. # ================================================================================ # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -32,12 +32,12 @@ # ###### #Error code classification category -#100-199 Permission/Security Related -#200-299 Availability/Timeout Related -#300-399 Data Access/Integrity Related -#400-499 Schema Interface type/validation Related -#500-599 Business/Flow Processing Related -#900-999 Unknown errors +#100-199 Permission/Security Related +#200-299 Availability/Timeout Related +#300-399 Data Access/Integrity Related +#400-499 Schema Interface type/validation Related +#500-599 Business/Flow Processing Related +#900-999 Unknown errors # #{classification} description # I = Information diff --git a/common-logging/src/test/java/org/onap/policy/common/logging/eelf/DroolsPDPMDCInfoTest.java b/common-logging/src/test/java/org/onap/policy/common/logging/eelf/DroolsPDPMDCInfoTest.java index 1be10dae..3dd62e69 100644 --- a/common-logging/src/test/java/org/onap/policy/common/logging/eelf/DroolsPDPMDCInfoTest.java +++ b/common-logging/src/test/java/org/onap/policy/common/logging/eelf/DroolsPDPMDCInfoTest.java @@ -20,24 +20,22 @@ package org.onap.policy.common.logging.eelf; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import org.junit.Test; -/** - * - */ public class DroolsPDPMDCInfoTest { - /** - * Test method for {@link org.onap.policy.common.logging.eelf.DroolsPDPMDCInfo#getMDCInfo()}. - */ - @Test - public void testGetMDCInfo() { - DroolsPDPMDCInfo di = new DroolsPDPMDCInfo(); - - assertNotNull(di.getMDCInfo()); - assertEquals("Policy.droolsPdp", di.getMDCInfo().get(Configuration.MDC_SERVICE_NAME)); - } + /** + * Test method for {@link org.onap.policy.common.logging.eelf.DroolsPDPMDCInfo#getMDCInfo()}. + */ + @Test + public void testGetMDCInfo() { + DroolsPDPMDCInfo di = new DroolsPDPMDCInfo(); + + assertNotNull(di.getMDCInfo()); + assertEquals("Policy.droolsPdp", di.getMDCInfo().get(Configuration.MDC_SERVICE_NAME)); + } } diff --git a/common-logging/src/test/java/org/onap/policy/common/logging/eelf/ErrorCodeMapTest.java b/common-logging/src/test/java/org/onap/policy/common/logging/eelf/ErrorCodeMapTest.java index ed4c879f..781be600 100644 --- a/common-logging/src/test/java/org/onap/policy/common/logging/eelf/ErrorCodeMapTest.java +++ b/common-logging/src/test/java/org/onap/policy/common/logging/eelf/ErrorCodeMapTest.java @@ -17,9 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.common.logging.eelf; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + import org.junit.Test; import org.onap.policy.common.logging.eelf.ErrorCodeMap.ErrorCodeInfo; @@ -40,17 +43,18 @@ public class ErrorCodeMapTest { assertNotNull(ErrorCodeMap.getErrorCodeInfo(MessageCodes.ERROR_UNKNOWN)); assertNotNull(ErrorCodeMap.getErrorCodeInfo(MessageCodes.ERROR_AUDIT)); } - + @Test public void testErrorCodeInfoGetErrorCode() { ErrorCodeInfo errorCodeInfo = ErrorCodeMap.getErrorCodeInfo(MessageCodes.EXCEPTION_ERROR); assertEquals("POLICY-503E", errorCodeInfo.getErrorCode()); } - + @Test public void testErrorCodeInfoGetErrorDesc() { ErrorCodeInfo errorCodeInfo = ErrorCodeMap.getErrorCodeInfo(MessageCodes.EXCEPTION_ERROR); - assertEquals("This is an exception error message during the process. Please check the error message for detail information", errorCodeInfo.getErrorDesc()); + assertEquals("This is an exception error message during the process. Please check the error message for detail " + + "information", errorCodeInfo.getErrorDesc()); } } diff --git a/common-logging/src/test/java/org/onap/policy/common/logging/eelf/EventDataTest.java b/common-logging/src/test/java/org/onap/policy/common/logging/eelf/EventDataTest.java index edd57ee1..f7aa733a 100644 --- a/common-logging/src/test/java/org/onap/policy/common/logging/eelf/EventDataTest.java +++ b/common-logging/src/test/java/org/onap/policy/common/logging/eelf/EventDataTest.java @@ -20,155 +20,154 @@ package org.onap.policy.common.logging.eelf; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; import java.time.Instant; import org.junit.Test; -/** - * - */ public class EventDataTest { - private static final Instant istart = Instant.ofEpochMilli(100000l); - private static final Instant iend = Instant.ofEpochMilli(200000l); - - /** - * Test method for {@link EventData#EventData()}. - */ - @Test - public void testEventData() { - EventData d = new EventData(); - - assertNull(d.getEndTime()); - assertNull(d.getRequestID()); - assertNull(d.getStartTime()); - } - - /** - * Test method for {@link EventData#EventData(String, Instant, Instant)}. - */ - @Test - public void testEventDataStringInstantInstant() { - EventData d = new EventData("myreq", istart, iend); - - assertEquals("myreq", d.getRequestID()); - assertEquals(istart, d.getStartTime()); - assertEquals(iend, d.getEndTime()); - } - - /** - * Test method for {@link EventData#getRequestID()} and - * {@link EventData#setRequestID(String)}. - */ - @Test - public void testGetSetRequestID() { - EventData d = new EventData(); - assertNull(d.getRequestID()); - - d.setRequestID("abc"); - assertEquals("abc", d.getRequestID()); - - d.setRequestID("def"); - assertEquals("def", d.getRequestID()); - } - - /** - * Test method for {@link EventData#getStartTime()} and - * {@link EventData#setStartTime(Instant)}. - */ - @Test - public void testGetSetStartTime() { - EventData d = new EventData(); - assertNull(d.getStartTime()); - - d.setStartTime(istart); - assertEquals(istart, d.getStartTime()); - - d.setStartTime(iend); - assertEquals(iend, d.getStartTime()); - - // setting end-time should not effect start-time - d.setEndTime(istart); - assertEquals(iend, d.getStartTime()); - } - - /** - * Test method for {@link EventData#getEndTime()} and - * {@link EventData#setEndTime(Instant)}. - */ - @Test - public void testGetSetEndTime() { - EventData d = new EventData(); - assertNull(d.getEndTime()); - - d.setEndTime(iend); - assertEquals(iend, d.getEndTime()); - - d.setEndTime(istart); - assertEquals(istart, d.getEndTime()); - - // setting start-time should not effect end-time - d.setStartTime(iend); - assertEquals(istart, d.getEndTime()); - } - - /** - * Test method for {@link EventData#toString()}. - */ - @Test - public void testToString() { - EventData d = new EventData("myreq", istart, iend); - assertEquals("myreq Starting Time : 1970-01-01T00:01:40Z Ending Time : 1970-01-01T00:03:20Z", d.toString()); - } - - /** - * Test method for {@link EventData#hashCode()}. - */ - @Test - public void testHashCode() { - int hc1 = new EventData("abc", istart, iend).hashCode(); - - assertNotEquals(hc1, new EventData("abd", istart, iend).hashCode()); - assertEquals(hc1, new EventData("abc", iend, istart).hashCode()); - } - - /** - * Test method for {@link EventData#equals(Object)}. - */ - @Test - public void testEqualsObject() { - EventData d1 = new EventData("abc", istart, iend); - EventData d2 = new EventData("abd", istart, iend); - EventData d3 = new EventData("abc", iend, istart); - - // same object - assertTrue(d1.equals(d1)); - - // compare with null - assertFalse(d1.equals(null)); - - // compare with request id - assertTrue(d1.equals("abc")); - assertFalse(d1.equals("abd")); - - // compare with int - different class type - assertFalse(d1.equals(10)); - - // "this" has null request id - assertFalse(new EventData().equals(d1)); - - // both null - assertTrue(new EventData().equals(new EventData())); - - // this request id is not null, other is null - assertFalse(d1.equals(new EventData())); - - // neither null, same - assertTrue(d1.equals(d3)); - - // neither null, diff - assertFalse(d1.equals(d2)); - } + private static final Instant istart = Instant.ofEpochMilli(100000L); + private static final Instant iend = Instant.ofEpochMilli(200000L); + + /** + * Test method for {@link EventData#EventData()}. + */ + @Test + public void testEventData() { + EventData eventData = new EventData(); + + assertNull(eventData.getEndTime()); + assertNull(eventData.getRequestID()); + assertNull(eventData.getStartTime()); + } + + /** + * Test method for {@link EventData#EventData(String, Instant, Instant)}. + */ + @Test + public void testEventDataStringInstantInstant() { + EventData eventData = new EventData("myreq", istart, iend); + + assertEquals("myreq", eventData.getRequestID()); + assertEquals(istart, eventData.getStartTime()); + assertEquals(iend, eventData.getEndTime()); + } + + /** + * Test method for {@link EventData#getRequestID()} and {@link EventData#setRequestID(String)}. + */ + @Test + public void testGetSetRequestId() { + EventData eventData = new EventData(); + assertNull(eventData.getRequestID()); + + eventData.setRequestID("abc"); + assertEquals("abc", eventData.getRequestID()); + + eventData.setRequestID("def"); + assertEquals("def", eventData.getRequestID()); + } + + /** + * Test method for {@link EventData#getStartTime()} and {@link EventData#setStartTime(Instant)}. + */ + @Test + public void testGetSetStartTime() { + EventData eventData = new EventData(); + assertNull(eventData.getStartTime()); + + eventData.setStartTime(istart); + assertEquals(istart, eventData.getStartTime()); + + eventData.setStartTime(iend); + assertEquals(iend, eventData.getStartTime()); + + // setting end-time should not effect start-time + eventData.setEndTime(istart); + assertEquals(iend, eventData.getStartTime()); + } + + /** + * Test method for {@link EventData#getEndTime()} and {@link EventData#setEndTime(Instant)}. + */ + @Test + public void testGetSetEndTime() { + EventData eventData = new EventData(); + assertNull(eventData.getEndTime()); + + eventData.setEndTime(iend); + assertEquals(iend, eventData.getEndTime()); + + eventData.setEndTime(istart); + assertEquals(istart, eventData.getEndTime()); + + // setting start-time should not effect end-time + eventData.setStartTime(iend); + assertEquals(istart, eventData.getEndTime()); + } + + /** + * Test method for {@link EventData#toString()}. + */ + @Test + public void testToString() { + EventData eventData = new EventData("myreq", istart, iend); + assertEquals("myreq Starting Time : 1970-01-01T00:01:40Z Ending Time : 1970-01-01T00:03:20Z", + eventData.toString()); + } + + /** + * Test method for {@link EventData#hashCode()}. + */ + @Test + public void testHashCode() { + int hc1 = new EventData("abc", istart, iend).hashCode(); + + assertNotEquals(hc1, new EventData("abd", istart, iend).hashCode()); + assertEquals(hc1, new EventData("abc", iend, istart).hashCode()); + } + + /** + * Test method for {@link EventData#equals(Object)}. + */ + @Test + public void testEqualsObject() { + final EventData d1 = new EventData("abc", istart, iend); + final EventData d2 = new EventData("abd", istart, iend); + final EventData d3 = new EventData("abc", iend, istart); + + // same object + assertTrue(d1.equals(d1)); + + // compare with null + assertFalse(d1.equals(null)); + + // compare with request id + assertTrue(d1.equals("abc")); + assertFalse(d1.equals("abd")); + + // compare with int - different class type + assertFalse(d1.equals(10)); + + // "this" has null request id + assertFalse(new EventData().equals(d1)); + + // both null + assertTrue(new EventData().equals(new EventData())); + + // this request id is not null, other is null + assertFalse(d1.equals(new EventData())); + + // neither null, same + assertTrue(d1.equals(d3)); + + // neither null, diff + assertFalse(d1.equals(d2)); + } } diff --git a/common-logging/src/test/java/org/onap/policy/common/logging/eelf/EventTrackInfoHandlerTest.java b/common-logging/src/test/java/org/onap/policy/common/logging/eelf/EventTrackInfoHandlerTest.java index 68fd52de..d1d5983d 100644 --- a/common-logging/src/test/java/org/onap/policy/common/logging/eelf/EventTrackInfoHandlerTest.java +++ b/common-logging/src/test/java/org/onap/policy/common/logging/eelf/EventTrackInfoHandlerTest.java @@ -20,7 +20,7 @@ package org.onap.policy.common.logging.eelf; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import java.time.Instant; import java.util.concurrent.ConcurrentMap; @@ -29,102 +29,102 @@ import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -/** - * - */ public class EventTrackInfoHandlerTest { - - private static final Instant inow = Instant.now(); - private static final Instant iexpired = Instant.ofEpochMilli(10000l); - - private static final EventData data1 = new EventData("abc", inow, inow); - private static final EventData data2 = new EventData("def", inow, inow); - - private static EventTrackInfo tracker; - private static ConcurrentMap<String, EventData> info; - - private EventTrackInfoHandler hdlr; - - @BeforeClass - public static void setUpBeforeClass() { - tracker = PolicyLogger.getEventTracker(); - info = tracker.getEventInfo(); - } - - @Before - public void setUp() { - info.clear(); - - hdlr = new EventTrackInfoHandler(); - } - - @Test - public void testNoEvents() { - hdlr.run(); - assertEquals(0, info.size()); - } - - @Test - public void testNothingExpired() { - tracker.storeEventData(data1); - tracker.storeEventData(data2); - - hdlr.run(); - assertEquals(2, info.size()); - } - - @Test - public void testSomeExpired() { - // not expired - tracker.storeEventData(data1); - tracker.storeEventData(data2); - - // start time is expired - tracker.storeEventData(new EventData("expiredA", iexpired, inow)); - tracker.storeEventData(new EventData("expiredB", iexpired, inow)); - - // end time is expired, but that has no impact - these should be retained - EventData oka = new EventData("okA", inow, iexpired); - EventData okb = new EventData("okB", inow, iexpired); - - tracker.storeEventData(oka); - tracker.storeEventData(okb); - - hdlr.run(); - assertEquals(4, info.size()); - - assertEquals(data1, info.get("abc")); - assertEquals(data2, info.get("def")); - assertEquals(oka, info.get("okA")); - assertEquals(okb, info.get("okB")); - } - - @Test - public void testMultipleRuns() { - - hdlr.run(); - assertEquals(0, info.size()); - - // not expired - tracker.storeEventData(data1); - tracker.storeEventData(data2); - - hdlr.run(); - assertEquals(2, info.size()); - - // start time is expired - tracker.storeEventData(new EventData("expiredA", iexpired, inow)); - tracker.storeEventData(new EventData("expiredB", iexpired, inow)); - - // end time is expired, but that has no impact - these should be retained - tracker.storeEventData(new EventData("okA", inow, iexpired)); - tracker.storeEventData(new EventData("okB", inow, iexpired)); - - hdlr.run(); - assertEquals(4, info.size()); - - hdlr.run(); - assertEquals(4, info.size()); - } + + private static final Instant inow = Instant.now(); + private static final Instant iexpired = Instant.ofEpochMilli(10000L); + + private static final EventData data1 = new EventData("abc", inow, inow); + private static final EventData data2 = new EventData("def", inow, inow); + + private static EventTrackInfo tracker; + private static ConcurrentMap<String, EventData> info; + + private EventTrackInfoHandler hdlr; + + @BeforeClass + public static void setUpBeforeClass() { + tracker = PolicyLogger.getEventTracker(); + info = tracker.getEventInfo(); + } + + /** + * Perform set up for test cases. + */ + @Before + public void setUp() { + info.clear(); + + hdlr = new EventTrackInfoHandler(); + } + + @Test + public void testNoEvents() { + hdlr.run(); + assertEquals(0, info.size()); + } + + @Test + public void testNothingExpired() { + tracker.storeEventData(data1); + tracker.storeEventData(data2); + + hdlr.run(); + assertEquals(2, info.size()); + } + + @Test + public void testSomeExpired() { + // not expired + tracker.storeEventData(data1); + tracker.storeEventData(data2); + + // start time is expired + tracker.storeEventData(new EventData("expiredA", iexpired, inow)); + tracker.storeEventData(new EventData("expiredB", iexpired, inow)); + + // end time is expired, but that has no impact - these should be retained + EventData oka = new EventData("okA", inow, iexpired); + EventData okb = new EventData("okB", inow, iexpired); + + tracker.storeEventData(oka); + tracker.storeEventData(okb); + + hdlr.run(); + assertEquals(4, info.size()); + + assertEquals(data1, info.get("abc")); + assertEquals(data2, info.get("def")); + assertEquals(oka, info.get("okA")); + assertEquals(okb, info.get("okB")); + } + + @Test + public void testMultipleRuns() { + + hdlr.run(); + assertEquals(0, info.size()); + + // not expired + tracker.storeEventData(data1); + tracker.storeEventData(data2); + + hdlr.run(); + assertEquals(2, info.size()); + + // start time is expired + tracker.storeEventData(new EventData("expiredA", iexpired, inow)); + tracker.storeEventData(new EventData("expiredB", iexpired, inow)); + + // end time is expired, but that has no impact - these should be retained + tracker.storeEventData(new EventData("okA", inow, iexpired)); + tracker.storeEventData(new EventData("okB", inow, iexpired)); + + hdlr.run(); + assertEquals(4, info.size()); + + hdlr.run(); + assertEquals(4, info.size()); + } } diff --git a/common-logging/src/test/java/org/onap/policy/common/logging/eelf/EventTrackInfoTest.java b/common-logging/src/test/java/org/onap/policy/common/logging/eelf/EventTrackInfoTest.java index 3690bc5c..7dc8fddc 100644 --- a/common-logging/src/test/java/org/onap/policy/common/logging/eelf/EventTrackInfoTest.java +++ b/common-logging/src/test/java/org/onap/policy/common/logging/eelf/EventTrackInfoTest.java @@ -20,111 +20,111 @@ package org.onap.policy.common.logging.eelf; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; import java.time.Instant; import org.junit.Before; import org.junit.Test; -/** - * - */ public class EventTrackInfoTest { - - private static final Instant istart = Instant.ofEpochMilli(100000l); - private static final Instant iend = Instant.ofEpochMilli(200000l); - - private static final EventData data1 = new EventData("abc", istart, iend); - private static final EventData data2 = new EventData("def", iend, istart); - - private EventTrackInfo info; - - @Before - public void setUp() { - info = new EventTrackInfo(); - - } - - /** - * Test method for {@link EventTrackInfo#EventTrackInfo()}. - */ - @Test - public void testEventTrackInfo() { - assertNotNull(info.getEventInfo()); - } - - /** - * Test method for {@link EventTrackInfo#getEventDataByRequestID(String)}. - */ - @Test - public void testGetEventDataByRequestID() { - info.storeEventData(data1); - info.storeEventData(data2); - - assertTrue(data1 == info.getEventDataByRequestID("abc")); - assertTrue(data2 == info.getEventDataByRequestID("def")); - assertNull(info.getEventDataByRequestID("hello")); - } - - /** - * Test method for {@link EventTrackInfo#storeEventData(EventData)}. - */ - @Test - public void testStoreEventData() { - // should ignore null - info.storeEventData(null); - assertTrue(info.getEventInfo().isEmpty()); - - // should ignore if request id is null or empty - info.storeEventData(new EventData()); - info.storeEventData(new EventData("", istart, iend)); - assertTrue(info.getEventInfo().isEmpty()); - - info.storeEventData(data1); - info.storeEventData(data2); - assertEquals(2, info.getEventInfo().size()); - - // look-up by request id - assertTrue(data1 == info.getEventDataByRequestID("abc")); - assertTrue(data2 == info.getEventDataByRequestID("def")); - - // doesn't replace existing value - info.storeEventData(new EventData("abc", iend, istart)); - assertEquals(2, info.getEventInfo().size()); - assertTrue(data1 == info.getEventDataByRequestID("abc")); - assertTrue(data2 == info.getEventDataByRequestID("def")); - } - - /** - * Test method for {@link EventTrackInfo#remove(String)}. - */ - @Test - public void testRemove() { - info.storeEventData(data1); - info.storeEventData(data2); - - info.remove("abc"); - - // ensure only that item was removed - assertEquals(1, info.getEventInfo().size()); - - // look-up by request id - assertNull(info.getEventDataByRequestID("abc")); - assertTrue(data2 == info.getEventDataByRequestID("def")); - } - - /** - * Test method for {@link EventTrackInfo#getEventInfo()}. - */ - @Test - public void testGetEventInfo() { - info.storeEventData(data1); - info.storeEventData(data2); - - assertEquals(2, info.getEventInfo().size()); - assertTrue(data1 == info.getEventInfo().get("abc")); - assertTrue(data2 == info.getEventInfo().get("def")); - } + + private static final Instant istart = Instant.ofEpochMilli(100000L); + private static final Instant iend = Instant.ofEpochMilli(200000L); + + private static final EventData data1 = new EventData("abc", istart, iend); + private static final EventData data2 = new EventData("def", iend, istart); + + private EventTrackInfo info; + + @Before + public void setUp() { + info = new EventTrackInfo(); + + } + + /** + * Test method for {@link EventTrackInfo#EventTrackInfo()}. + */ + @Test + public void testEventTrackInfo() { + assertNotNull(info.getEventInfo()); + } + + /** + * Test method for {@link EventTrackInfo#getEventDataByRequestID(String)}. + */ + @Test + public void testGetEventDataByRequestID() { + info.storeEventData(data1); + info.storeEventData(data2); + + assertTrue(data1 == info.getEventDataByRequestID("abc")); + assertTrue(data2 == info.getEventDataByRequestID("def")); + assertNull(info.getEventDataByRequestID("hello")); + } + + /** + * Test method for {@link EventTrackInfo#storeEventData(EventData)}. + */ + @Test + public void testStoreEventData() { + // should ignore null + info.storeEventData(null); + assertTrue(info.getEventInfo().isEmpty()); + + // should ignore if request id is null or empty + info.storeEventData(new EventData()); + info.storeEventData(new EventData("", istart, iend)); + assertTrue(info.getEventInfo().isEmpty()); + + info.storeEventData(data1); + info.storeEventData(data2); + assertEquals(2, info.getEventInfo().size()); + + // look-up by request id + assertTrue(data1 == info.getEventDataByRequestID("abc")); + assertTrue(data2 == info.getEventDataByRequestID("def")); + + // doesn't replace existing value + info.storeEventData(new EventData("abc", iend, istart)); + assertEquals(2, info.getEventInfo().size()); + assertTrue(data1 == info.getEventDataByRequestID("abc")); + assertTrue(data2 == info.getEventDataByRequestID("def")); + } + + /** + * Test method for {@link EventTrackInfo#remove(String)}. + */ + @Test + public void testRemove() { + info.storeEventData(data1); + info.storeEventData(data2); + + info.remove("abc"); + + // ensure only that item was removed + assertEquals(1, info.getEventInfo().size()); + + // look-up by request id + assertNull(info.getEventDataByRequestID("abc")); + assertTrue(data2 == info.getEventDataByRequestID("def")); + } + + /** + * Test method for {@link EventTrackInfo#getEventInfo()}. + */ + @Test + public void testGetEventInfo() { + info.storeEventData(data1); + info.storeEventData(data2); + + assertEquals(2, info.getEventInfo().size()); + assertTrue(data1 == info.getEventInfo().get("abc")); + assertTrue(data2 == info.getEventInfo().get("def")); + } } diff --git a/common-logging/src/test/java/org/onap/policy/common/logging/eelf/PolicyLoggerTest.java b/common-logging/src/test/java/org/onap/policy/common/logging/eelf/PolicyLoggerTest.java index 18361ac1..8d6b6d68 100644 --- a/common-logging/src/test/java/org/onap/policy/common/logging/eelf/PolicyLoggerTest.java +++ b/common-logging/src/test/java/org/onap/policy/common/logging/eelf/PolicyLoggerTest.java @@ -17,6 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + + package org.onap.policy.common.logging.eelf; import static com.att.eelf.configuration.Configuration.MDC_ALERT_SEVERITY; @@ -27,27 +29,37 @@ import static com.att.eelf.configuration.Configuration.MDC_SERVER_FQDN; import static com.att.eelf.configuration.Configuration.MDC_SERVER_IP_ADDRESS; import static com.att.eelf.configuration.Configuration.MDC_SERVICE_INSTANCE_ID; import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; import static org.onap.policy.common.logging.eelf.Configuration.PARTNER_NAME; import static org.onap.policy.common.logging.eelf.Configuration.RESPONSE_CODE; import static org.onap.policy.common.logging.eelf.Configuration.RESPONSE_DESCRIPTION; import static org.onap.policy.common.logging.eelf.Configuration.SERVER_NAME; import static org.onap.policy.common.logging.eelf.Configuration.STATUS_CODE; -import static org.onap.policy.common.logging.util.TestUtils.*; +import static org.onap.policy.common.logging.util.TestUtils.overrideStaticField; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFLogger.Level; + import java.time.Instant; import java.util.Properties; import java.util.UUID; + import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import org.slf4j.MDC; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFLogger.Level; public class PolicyLoggerTest { - + + /** + * Perform set up for test cases. + */ @Before - public void setUp(){ + public void setUp() { Properties properties = new Properties(); properties.setProperty("policy.component", "XACML"); PolicyLogger.init(properties); @@ -72,9 +84,9 @@ public class PolicyLoggerTest { @Test public void testSetAndGetMetricsLevelLevel() { PolicyLogger.setMetricsLevel(Level.INFO); - assertEquals(Level.INFO, PolicyLogger.getMetricsLevel()); + assertEquals(Level.INFO, PolicyLogger.getMetricsLevel()); PolicyLogger.setMetricsLevel(Level.DEBUG); - assertEquals(Level.DEBUG, PolicyLogger.getMetricsLevel()); + assertEquals(Level.DEBUG, PolicyLogger.getMetricsLevel()); } @Test @@ -95,7 +107,7 @@ public class PolicyLoggerTest { @Test public void testPostMDCInfoForEventString() { PolicyLogger.postMDCInfoForEvent("transactionId"); - + assertEquals("", MDC.get(MDC_REMOTE_HOST)); assertEquals("transactionId", MDC.get(MDC_KEY_REQUEST_ID)); assertEquals("Policy.xacmlPdp", MDC.get(MDC_SERVICE_NAME)); @@ -107,15 +119,15 @@ public class PolicyLoggerTest { assertEquals("N/A", MDC.get(RESPONSE_CODE)); assertEquals("N/A", MDC.get(RESPONSE_DESCRIPTION)); } - + @Test public void testPostMDCInfoForEventStringDrools() { Properties properties = new Properties(); properties.setProperty("policy.component", "DROOLS"); PolicyLogger.init(properties); - + PolicyLogger.postMDCInfoForEvent("transactionId"); - + assertEquals("transactionId", MDC.get(MDC_KEY_REQUEST_ID)); assertEquals("Policy.droolsPdp", MDC.get(MDC_SERVICE_NAME)); assertEquals("Policy.droolsPdp.event", MDC.get(MDC_SERVICE_INSTANCE_ID)); @@ -130,7 +142,7 @@ public class PolicyLoggerTest { @Test public void testPostMDCInfoForEventObject() { PolicyLogger.postMDCInfoForEvent(1); - + assertEquals("", MDC.get(MDC_REMOTE_HOST)); assertEquals("1", MDC.get(MDC_KEY_REQUEST_ID)); assertEquals("Policy.xacmlPdp", MDC.get(MDC_SERVICE_NAME)); @@ -146,7 +158,7 @@ public class PolicyLoggerTest { @Test public void testPostMDCInfoForTriggeredRule() { PolicyLogger.postMDCInfoForTriggeredRule("transactionId"); - + assertEquals("", MDC.get(MDC_REMOTE_HOST)); assertEquals("transactionId", MDC.get(MDC_KEY_REQUEST_ID)); assertEquals("Policy.droolsPdp", MDC.get(MDC_SERVICE_NAME)); @@ -161,7 +173,7 @@ public class PolicyLoggerTest { @Test public void testPostMDCUUIDForTriggeredRule() { PolicyLogger.postMDCUUIDForTriggeredRule(1); - + assertEquals("", MDC.get(MDC_REMOTE_HOST)); assertEquals("1", MDC.get(MDC_KEY_REQUEST_ID)); assertEquals("Policy.droolsPdp", MDC.get(MDC_SERVICE_NAME)); @@ -187,7 +199,7 @@ public class PolicyLoggerTest { overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); PolicyLogger.info("str1", "str2"); Mockito.verify(mockLogger).info(MessageCodes.GENERAL_INFO, "str2"); - } + } @Test public void testInfoObject() { @@ -202,17 +214,20 @@ public class PolicyLoggerTest { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); PolicyLogger.info(MessageCodes.ERROR_DATA_ISSUE, new NullPointerException(), "str1", "str2"); - Mockito.verify(mockLogger).info((MessageCodes)Mockito.any(), Mockito.startsWith("str1:str2:java.lang.NullPointerException")); + Mockito.verify(mockLogger).info((MessageCodes) Mockito.any(), + Mockito.startsWith("str1:str2:java.lang.NullPointerException")); } @Test public void testInfoMessageCodesStringThrowableStringArray() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); - PolicyLogger.info(MessageCodes.ERROR_DATA_ISSUE, "PolicyLoggerTest", new NullPointerException(), "str1", "str2"); - Mockito.verify(mockLogger).info((MessageCodes)Mockito.any(), Mockito.startsWith("str1:str2:java.lang.NullPointerException")); + PolicyLogger.info(MessageCodes.ERROR_DATA_ISSUE, "PolicyLoggerTest", new NullPointerException(), "str1", + "str2"); + Mockito.verify(mockLogger).info((MessageCodes) Mockito.any(), + Mockito.startsWith("str1:str2:java.lang.NullPointerException")); } - + @Test public void testWarnMessageCodesStringStringArray() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); @@ -227,7 +242,7 @@ public class PolicyLoggerTest { overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); PolicyLogger.warn("str1", "str2"); Mockito.verify(mockLogger).warn(MessageCodes.GENERAL_INFO, "str2"); - } + } @Test public void testWarnObject() { @@ -242,15 +257,18 @@ public class PolicyLoggerTest { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); PolicyLogger.warn(MessageCodes.ERROR_DATA_ISSUE, new NullPointerException(), "str1", "str2"); - Mockito.verify(mockLogger).warn((MessageCodes)Mockito.any(), Mockito.startsWith("str1:str2:java.lang.NullPointerException")); + Mockito.verify(mockLogger).warn((MessageCodes) Mockito.any(), + Mockito.startsWith("str1:str2:java.lang.NullPointerException")); } @Test public void testWarnMessageCodesStringThrowableStringArray() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); - PolicyLogger.warn(MessageCodes.ERROR_DATA_ISSUE, "PolicyLoggerTest", new NullPointerException(), "str1", "str2"); - Mockito.verify(mockLogger).warn((MessageCodes)Mockito.any(), Mockito.startsWith("str1:str2:java.lang.NullPointerException")); + PolicyLogger.warn(MessageCodes.ERROR_DATA_ISSUE, "PolicyLoggerTest", new NullPointerException(), "str1", + "str2"); + Mockito.verify(mockLogger).warn((MessageCodes) Mockito.any(), + Mockito.startsWith("str1:str2:java.lang.NullPointerException")); } @Test @@ -268,7 +286,8 @@ public class PolicyLoggerTest { PolicyLogger.error("str1", "str2"); Mockito.verify(mockLogger).error(MessageCodes.GENERAL_ERROR, "str2"); assertEquals("POLICY-515E", MDC.get("ErrorCode")); - assertEquals("This is a general error message during the process. Please check the error message for detail information", MDC.get("ErrorDescription")); + assertEquals("This is a general error message during the process. Please check the error message for detail " + + "information", MDC.get("ErrorDescription")); } @Test @@ -279,7 +298,8 @@ public class PolicyLoggerTest { Mockito.verify(mockLogger).error(MessageCodes.GENERAL_ERROR, "str1"); assertEquals("ERROR", MDC.get("ErrorCategory")); assertEquals("POLICY-515E", MDC.get("ErrorCode")); - assertEquals("This is a general error message during the process. Please check the error message for detail information", MDC.get("ErrorDescription")); + assertEquals("This is a general error message during the process. Please check the error message for detail " + + "information", MDC.get("ErrorDescription")); } @Test @@ -290,7 +310,8 @@ public class PolicyLoggerTest { Mockito.verify(mockLogger).error(MessageCodes.GENERAL_ERROR, "1"); assertEquals("ERROR", MDC.get("ErrorCategory")); assertEquals("POLICY-515E", MDC.get("ErrorCode")); - assertEquals("This is a general error message during the process. Please check the error message for detail information", MDC.get("ErrorDescription")); + assertEquals("This is a general error message during the process. Please check the error message for detail " + + "information", MDC.get("ErrorDescription")); } @Test @@ -298,15 +319,18 @@ public class PolicyLoggerTest { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); overrideStaticField(PolicyLogger.class, "errorLogger", mockLogger); PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, new NullPointerException(), "str1", "str2"); - Mockito.verify(mockLogger).error((MessageCodes)Mockito.any(), Mockito.startsWith("str1:str2:java.lang.NullPointerException")); + Mockito.verify(mockLogger).error((MessageCodes) Mockito.any(), + Mockito.startsWith("str1:str2:java.lang.NullPointerException")); } @Test public void testErrorMessageCodesStringThrowableStringArray() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); overrideStaticField(PolicyLogger.class, "errorLogger", mockLogger); - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "PolicyLoggerTest", new NullPointerException(), "str1", "str2"); - Mockito.verify(mockLogger).error((MessageCodes)Mockito.any(), Mockito.startsWith("str1:str2:java.lang.NullPointerException")); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "PolicyLoggerTest", new NullPointerException(), "str1", + "str2"); + Mockito.verify(mockLogger).error((MessageCodes) Mockito.any(), + Mockito.startsWith("str1:str2:java.lang.NullPointerException")); } @Test @@ -374,15 +398,18 @@ public class PolicyLoggerTest { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); PolicyLogger.debug(MessageCodes.ERROR_DATA_ISSUE, new NullPointerException(), "str1", "str2"); - Mockito.verify(mockLogger).debug((MessageCodes)Mockito.any(), Mockito.startsWith("str1:str2:java.lang.NullPointerException")); + Mockito.verify(mockLogger).debug((MessageCodes) Mockito.any(), + Mockito.startsWith("str1:str2:java.lang.NullPointerException")); } @Test public void testDebugMessageCodesStringThrowableStringArray() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); - PolicyLogger.debug(MessageCodes.ERROR_DATA_ISSUE, "PolicyLoggerTest", new NullPointerException(), "str1", "str2"); - Mockito.verify(mockLogger).debug((MessageCodes)Mockito.any(), Mockito.startsWith("str1:str2:java.lang.NullPointerException")); + PolicyLogger.debug(MessageCodes.ERROR_DATA_ISSUE, "PolicyLoggerTest", new NullPointerException(), "str1", + "str2"); + Mockito.verify(mockLogger).debug((MessageCodes) Mockito.any(), + Mockito.startsWith("str1:str2:java.lang.NullPointerException")); } @Test @@ -411,7 +438,7 @@ public class PolicyLoggerTest { assertFalse(PolicyLogger.isWarnEnabled()); assertTrue(PolicyLogger.isWarnEnabled()); } - + @Test public void testIsInfoEnabled1() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); @@ -459,7 +486,7 @@ public class PolicyLoggerTest { public void testRecordAuditEventStartAndEnd() { PolicyLogger.recordAuditEventStart("eventId"); assertNotNull(PolicyLogger.getEventTracker().getEventInfo().get("eventId")); - + PolicyLogger.recordAuditEventEnd("eventId", "rule"); assertNull(PolicyLogger.getEventTracker().getEventInfo().get("eventId")); } @@ -479,7 +506,7 @@ public class PolicyLoggerTest { public void testRecordAuditEventEndStringStringString() { PolicyLogger.recordAuditEventStart("eventId"); assertNotNull(PolicyLogger.getEventTracker().getEventInfo().get("eventId")); - + PolicyLogger.recordAuditEventEnd("eventId", "rule", "policyVersion"); assertNull(PolicyLogger.getEventTracker().getEventInfo().get("eventId")); } @@ -499,7 +526,7 @@ public class PolicyLoggerTest { public void testCreatAuditEventTrackingRecordStringStringString() { PolicyLogger.recordAuditEventStart("eventId"); assertNotNull(PolicyLogger.getEventTracker().getEventInfo().get("eventId")); - + PolicyLogger.creatAuditEventTrackingRecord("eventId", "rule", "policyVersion"); assertNull(PolicyLogger.getEventTracker().getEventInfo().get("eventId")); } @@ -511,7 +538,7 @@ public class PolicyLoggerTest { assertNotNull(PolicyLogger.getEventTracker().getEventInfo().get(uuid.toString())); PolicyLogger.creatAuditEventTrackingRecord(uuid, "rule"); - assertNull(PolicyLogger.getEventTracker().getEventInfo().get(uuid.toString())); + assertNull(PolicyLogger.getEventTracker().getEventInfo().get(uuid.toString())); } @Test @@ -544,7 +571,8 @@ public class PolicyLoggerTest { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); overrideStaticField(PolicyLogger.class, "metricsLogger", mockLogger); PolicyLogger.recordMetricEvent("eventId"); - Mockito.verify(mockLogger).info(Mockito.eq(MessageCodes.RULE_METRICS_INFO), Mockito.anyString(), Mockito.eq("eventId")); + Mockito.verify(mockLogger).info(Mockito.eq(MessageCodes.RULE_METRICS_INFO), Mockito.anyString(), + Mockito.eq("eventId")); } @Test @@ -552,7 +580,8 @@ public class PolicyLoggerTest { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); overrideStaticField(PolicyLogger.class, "metricsLogger", mockLogger); PolicyLogger.metrics("str1"); - Mockito.verify(mockLogger).info(Mockito.eq(MessageCodes.RULE_METRICS_INFO), Mockito.anyString(), Mockito.eq("str1")); + Mockito.verify(mockLogger).info(Mockito.eq(MessageCodes.RULE_METRICS_INFO), Mockito.anyString(), + Mockito.eq("str1")); } @Test @@ -560,7 +589,8 @@ public class PolicyLoggerTest { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); overrideStaticField(PolicyLogger.class, "metricsLogger", mockLogger); PolicyLogger.metrics("PolicyLoggerTest", 1); - Mockito.verify(mockLogger).info(Mockito.eq(MessageCodes.RULE_METRICS_INFO), Mockito.anyString(), Mockito.eq("1")); + Mockito.verify(mockLogger).info(Mockito.eq(MessageCodes.RULE_METRICS_INFO), Mockito.anyString(), + Mockito.eq("1")); } @Test @@ -568,7 +598,8 @@ public class PolicyLoggerTest { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); overrideStaticField(PolicyLogger.class, "metricsLogger", mockLogger); PolicyLogger.metrics(1); - Mockito.verify(mockLogger).info(Mockito.eq(MessageCodes.RULE_METRICS_INFO), Mockito.anyString(), Mockito.eq("1")); + Mockito.verify(mockLogger).info(Mockito.eq(MessageCodes.RULE_METRICS_INFO), Mockito.anyString(), + Mockito.eq("1")); } @Test @@ -583,7 +614,7 @@ public class PolicyLoggerTest { public void testInitNullProperties() { PolicyLogger.init(null); } - + @Test public void testInit() { Properties properties = new Properties(); @@ -597,24 +628,24 @@ public class PolicyLoggerTest { properties.setProperty("concurrentHashMap.limit", "0"); properties.setProperty("stop.check.point", "0"); properties.setProperty("logger.property", "LOG4J"); - + PolicyLogger.init(properties); } - + @Test public void testSetDebugLevelString() { PolicyLogger.setOverrideLogbackLevel(true); PolicyLogger.setDebugLevel("TRACE"); assertEquals(Level.TRACE, PolicyLogger.getDebugLevel()); } - + @Test public void testSetErrorLevelStringOff() { PolicyLogger.setOverrideLogbackLevel(true); PolicyLogger.setErrorLevel("OFF"); assertEquals(Level.OFF, PolicyLogger.getErrorLevel()); } - + @Test public void testSetErrorLevelStringOther() { PolicyLogger.setOverrideLogbackLevel(true); @@ -628,7 +659,7 @@ public class PolicyLoggerTest { PolicyLogger.setMetricsLevel("OFF"); assertEquals(Level.OFF, PolicyLogger.getMetricsLevel()); } - + @Test public void testSetMetricsLevelStringOther() { PolicyLogger.setOverrideLogbackLevel(true); @@ -642,7 +673,7 @@ public class PolicyLoggerTest { PolicyLogger.setAuditLevel("OFF"); assertEquals(Level.OFF, PolicyLogger.getAuditLevel()); } - + @Test public void testSetAuditLevelStringOther() { PolicyLogger.setOverrideLogbackLevel(true); diff --git a/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/EelfLoggerTest.java b/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/EelfLoggerTest.java index 6d6399b2..a7e835ce 100644 --- a/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/EelfLoggerTest.java +++ b/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/EelfLoggerTest.java @@ -17,21 +17,29 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.common.logging.flexlogger; import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; import static org.onap.policy.common.logging.util.TestUtils.overrideStaticField; + +import com.att.eelf.configuration.EELFLogger; + import java.util.UUID; + import org.junit.Test; import org.mockito.Mockito; import org.onap.policy.common.logging.eelf.MessageCodes; import org.onap.policy.common.logging.eelf.PolicyLogger; import org.slf4j.MDC; -import com.att.eelf.configuration.EELFLogger; public class EelfLoggerTest { - + EelfLogger eelfLogger = new EelfLogger("EelfLoggerTest", "transactionId"); @Test @@ -72,7 +80,7 @@ public class EelfLoggerTest { public void testEelfLoggerStringString() { new EelfLogger("EelfLoggerTest", "transactionId"); assertEquals("transactionId", PolicyLogger.getTransId()); - } + } @Test public void testSetAndGetTransId() { @@ -128,7 +136,7 @@ public class EelfLoggerTest { Mockito.when(mockLogger.isDebugEnabled()).thenReturn(false).thenReturn(true); assertFalse(eelfLogger.isDebugEnabled()); assertTrue(eelfLogger.isDebugEnabled()); - + } @Test @@ -193,7 +201,8 @@ public class EelfLoggerTest { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); eelfLogger.debug("message", new NullPointerException()); - Mockito.verify(mockLogger).debug((MessageCodes)Mockito.any(), Mockito.startsWith("message:java.lang.NullPointerException")); + Mockito.verify(mockLogger).debug((MessageCodes) Mockito.any(), + Mockito.startsWith("message:java.lang.NullPointerException")); } @Test @@ -201,7 +210,8 @@ public class EelfLoggerTest { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); overrideStaticField(PolicyLogger.class, "errorLogger", mockLogger); eelfLogger.error("message", new NullPointerException()); - Mockito.verify(mockLogger).error((MessageCodes)Mockito.any(), Mockito.startsWith("message:java.lang.NullPointerException")); + Mockito.verify(mockLogger).error((MessageCodes) Mockito.any(), + Mockito.startsWith("message:java.lang.NullPointerException")); eelfLogger.error("message", new NullPointerException()); } @@ -210,7 +220,8 @@ public class EelfLoggerTest { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); eelfLogger.info("message", new NullPointerException()); - Mockito.verify(mockLogger).info((MessageCodes)Mockito.any(), Mockito.startsWith("message:java.lang.NullPointerException")); + Mockito.verify(mockLogger).info((MessageCodes) Mockito.any(), + Mockito.startsWith("message:java.lang.NullPointerException")); } @Test @@ -218,7 +229,8 @@ public class EelfLoggerTest { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); eelfLogger.warn("message", new NullPointerException()); - Mockito.verify(mockLogger).warn((MessageCodes)Mockito.any(), Mockito.startsWith("message:java.lang.NullPointerException")); + Mockito.verify(mockLogger).warn((MessageCodes) Mockito.any(), + Mockito.startsWith("message:java.lang.NullPointerException")); } @Test @@ -254,7 +266,7 @@ public class EelfLoggerTest { public void testRecordAuditEventEndStringStringString() { eelfLogger.recordAuditEventStart("eventId"); assertNotNull(PolicyLogger.getEventTracker().getEventInfo().get("eventId")); - + eelfLogger.recordAuditEventEnd("eventId", "rule", "policyVersion"); assertNull(PolicyLogger.getEventTracker().getEventInfo().get("eventId")); } @@ -273,7 +285,7 @@ public class EelfLoggerTest { public void testRecordAuditEventEndStringString() { eelfLogger.recordAuditEventStart("eventId"); assertNotNull(PolicyLogger.getEventTracker().getEventInfo().get("eventId")); - + eelfLogger.recordAuditEventEnd("eventId", "rule"); assertNull(PolicyLogger.getEventTracker().getEventInfo().get("eventId")); } @@ -306,7 +318,8 @@ public class EelfLoggerTest { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); overrideStaticField(PolicyLogger.class, "metricsLogger", mockLogger); eelfLogger.metrics(1); - Mockito.verify(mockLogger).info(Mockito.eq(MessageCodes.RULE_METRICS_INFO), Mockito.anyString(), Mockito.eq("1")); + Mockito.verify(mockLogger).info(Mockito.eq(MessageCodes.RULE_METRICS_INFO), Mockito.anyString(), + Mockito.eq("1")); } @Test @@ -314,7 +327,8 @@ public class EelfLoggerTest { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); overrideStaticField(PolicyLogger.class, "errorLogger", mockLogger); eelfLogger.error(MessageCodes.GENERAL_ERROR, new NullPointerException(), "str1", "str2"); - Mockito.verify(mockLogger).error((MessageCodes)Mockito.any(), Mockito.startsWith("str1:str2:java.lang.NullPointerException")); + Mockito.verify(mockLogger).error((MessageCodes) Mockito.any(), + Mockito.startsWith("str1:str2:java.lang.NullPointerException")); } @Test @@ -323,7 +337,7 @@ public class EelfLoggerTest { overrideStaticField(PolicyLogger.class, "errorLogger", mockLogger); eelfLogger.error(MessageCodes.GENERAL_ERROR, "str1", "str2"); Mockito.verify(mockLogger).error(MessageCodes.GENERAL_ERROR, "str1", "str2"); - + } @Test @@ -345,8 +359,9 @@ public class EelfLoggerTest { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); eelfLogger.warn(MessageCodes.GENERAL_ERROR, new NullPointerException(), "str1", "str2"); - Mockito.verify(mockLogger).warn((MessageCodes)Mockito.any(), Mockito.startsWith("str1:str2:java.lang.NullPointerException")); - + Mockito.verify(mockLogger).warn((MessageCodes) Mockito.any(), + Mockito.startsWith("str1:str2:java.lang.NullPointerException")); + } @Test diff --git a/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/FlexLoggerTest.java b/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/FlexLoggerTest.java index af7edcab..57afc9f7 100644 --- a/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/FlexLoggerTest.java +++ b/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/FlexLoggerTest.java @@ -17,13 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.common.logging.flexlogger; -import static org.junit.Assert.*; -import static org.onap.policy.common.logging.util.TestUtils.*; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertSame; +import static org.onap.policy.common.logging.util.TestUtils.overrideStaticField; + import java.io.IOException; import java.util.HashSet; import java.util.Set; + import org.junit.Test; import org.onap.policy.common.logging.flexlogger.FlexLogger.PropertiesCallBack; @@ -32,81 +36,81 @@ public class FlexLoggerTest { @Test public void testGetLoggerClassOfQEelf() { overrideStaticField(FlexLogger.class, "loggerType", LoggerType.EELF); - Logger logger = FlexLogger.getLogger((Class)null); - assertSame(logger, FlexLogger.getLogger((Class)null)); - assertNotEquals(logger, FlexLogger.getLogger(String.class)); + Logger logger = FlexLogger.getLogger((Class) null); + assertSame(logger, FlexLogger.getLogger((Class) null)); + assertNotEquals(logger, FlexLogger.getLogger(String.class)); } - + @Test public void testGetLoggerClassOfQLog4j() { overrideStaticField(FlexLogger.class, "loggerType", LoggerType.LOG4J); Logger logger = FlexLogger.getLogger(this.getClass()); assertSame(logger, FlexLogger.getLogger(this.getClass())); } - + @Test public void testGetLoggerClassOfQSystemOut() { overrideStaticField(FlexLogger.class, "loggerType", LoggerType.SYSTEMOUT); Logger logger = FlexLogger.getLogger(this.getClass()); assertSame(logger, FlexLogger.getLogger(this.getClass())); } - + @Test public void testGetLoggerStringEelf() { overrideStaticField(FlexLogger.class, "loggerType", LoggerType.EELF); Logger logger = FlexLogger.getLogger("str1"); assertSame(logger, FlexLogger.getLogger("str1")); } - + @Test public void testGetLoggerStringLog4j() { overrideStaticField(FlexLogger.class, "loggerType", LoggerType.LOG4J); Logger logger = FlexLogger.getLogger("str1"); assertSame(logger, FlexLogger.getLogger("str1")); } - + @Test public void testGetLoggerStringSystemOut() { overrideStaticField(FlexLogger.class, "loggerType", LoggerType.SYSTEMOUT); Logger logger = FlexLogger.getLogger("str1"); assertSame(logger, FlexLogger.getLogger("str1")); } - + @Test public void testGetLoggerClassOfQBooleanEelf() { overrideStaticField(FlexLogger.class, "loggerType", LoggerType.EELF); Logger logger = FlexLogger.getLogger(this.getClass(), true); assertSame(logger, FlexLogger.getLogger(this.getClass(), true)); } - + @Test public void testGetLoggerClassOfQBooleanLog4j() { overrideStaticField(FlexLogger.class, "loggerType", LoggerType.LOG4J); Logger logger = FlexLogger.getLogger(this.getClass(), true); assertSame(logger, FlexLogger.getLogger(this.getClass(), true)); } - + @Test public void testGetLoggerClassOfQBooleanSystemOut() { overrideStaticField(FlexLogger.class, "loggerType", LoggerType.SYSTEMOUT); Logger logger = FlexLogger.getLogger(this.getClass(), true); assertSame(logger, FlexLogger.getLogger(this.getClass(), true)); } - + @Test public void testGetLoggerStringBooleanEelf() { overrideStaticField(FlexLogger.class, "loggerType", LoggerType.EELF); Logger logger = FlexLogger.getLogger("str1", true); assertSame(logger, FlexLogger.getLogger("str1", true)); } - + @Test public void testGetLoggerStringBooleanLog4j() { overrideStaticField(FlexLogger.class, "loggerType", LoggerType.LOG4J); Logger logger = FlexLogger.getLogger("str1", true); assertSame(logger, FlexLogger.getLogger("str1", true)); } - + @Test public void testGetLoggerStringBooleanSystemOut() { overrideStaticField(FlexLogger.class, "loggerType", LoggerType.SYSTEMOUT); @@ -118,15 +122,15 @@ public class FlexLoggerTest { public void testGetClassName() { assertNotEquals("FlexLogger", new FlexLogger().getClassName()); } - + @Test - public void testPropertiesCallBack() throws IOException{ - PropertiesCallBack propertiesCallBack = new PropertiesCallBack("name"); + public void testPropertiesCallBack() throws IOException { Set<String> changedKeys = new HashSet<>(); changedKeys.add("debugLogger.level"); changedKeys.add("metricsLogger.level"); changedKeys.add("error.level"); changedKeys.add("audit.level"); + PropertiesCallBack propertiesCallBack = new PropertiesCallBack("name"); propertiesCallBack.propertiesChanged(PropertyUtil.getProperties("config/policyLogger.properties"), changedKeys); } diff --git a/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/Logger4JTest.java b/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/Logger4JTest.java index 3650b18a..852e7f1b 100644 --- a/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/Logger4JTest.java +++ b/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/Logger4JTest.java @@ -17,10 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.common.logging.flexlogger; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + import java.util.UUID; + import org.apache.log4j.Logger; import org.apache.log4j.Priority; import org.junit.Test; @@ -29,7 +36,7 @@ import org.onap.policy.common.logging.eelf.MessageCodes; import org.onap.policy.common.logging.util.TestUtils; public class Logger4JTest { - + private Logger4J logger4J = new Logger4J("str1", "Logger4JTest"); @Test @@ -215,7 +222,8 @@ public class Logger4JTest { TestUtils.overrideField(Logger4J.class, logger4J, "log", logger); logger4J.setTransId("transactionId"); logger4J.error(MessageCodes.GENERAL_ERROR, new NullPointerException(), "str1", "str2"); - Mockito.verify(logger).error("transactionId|Logger4JTest|MessageCodes :" + MessageCodes.GENERAL_ERROR + "[str1, str2]"); + Mockito.verify(logger) + .error("transactionId|Logger4JTest|MessageCodes :" + MessageCodes.GENERAL_ERROR + "[str1, str2]"); } @Test @@ -224,7 +232,8 @@ public class Logger4JTest { TestUtils.overrideField(Logger4J.class, logger4J, "log", logger); logger4J.setTransId("transactionId"); logger4J.error(MessageCodes.GENERAL_ERROR, "str1", "str2"); - Mockito.verify(logger).error("transactionId|Logger4JTest|MessageCode:" + MessageCodes.GENERAL_ERROR + "[str1, str2]"); + Mockito.verify(logger) + .error("transactionId|Logger4JTest|MessageCode:" + MessageCodes.GENERAL_ERROR + "[str1, str2]"); } @Test @@ -232,7 +241,7 @@ public class Logger4JTest { String returnedTransactionId = logger4J.postMDCInfoForEvent("transactionId"); assertEquals("transactionId", returnedTransactionId); } - + @Test public void testPostMDCInfoForEventEmptyString() { String returnedTransactionId = logger4J.postMDCInfoForEvent(""); diff --git a/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/PropertyUtilTest.java b/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/PropertyUtilTest.java index b4fd5362..d97df4ce 100644 --- a/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/PropertyUtilTest.java +++ b/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/PropertyUtilTest.java @@ -17,98 +17,105 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.common.logging.flexlogger; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; + import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; import java.util.Set; + import org.junit.After; import org.junit.Before; import org.junit.Test; import org.onap.policy.common.logging.flexlogger.PropertyUtil.Listener; public class PropertyUtilTest { - + private static final File FILE = new File("target/test.properties"); private TestListener testListener = new TestListener(); - + + /** + * Perform test case set up. + */ @Before - public void setUp() throws IOException{ + public void setUp() throws IOException { FileOutputStream fileOutputStream = new FileOutputStream(FILE); Properties properties = new Properties(); properties.put("testProperty", "testValue"); properties.store(fileOutputStream, ""); fileOutputStream.close(); } - + @After - public void tearDown() throws IOException{ + public void tearDown() throws IOException { PropertyUtil.stopListening(FILE, testListener); FILE.delete(); - } - + } + @Test - public void testGetProperties() throws IOException{ + public void testGetProperties() throws IOException { FileOutputStream fileOutputStream = new FileOutputStream(FILE); Properties properties = new Properties(); properties.put("testProperty", "testValue"); properties.store(fileOutputStream, ""); fileOutputStream.close(); - + Properties readProperties = PropertyUtil.getProperties(FILE, testListener); assertEquals("testValue", readProperties.getProperty("testProperty")); } - + @Test - public void testPropertiesChanged() throws IOException, InterruptedException{ + public void testPropertiesChanged() throws IOException, InterruptedException { PropertyUtil.getProperties(FILE, testListener); - + FileOutputStream fileOutputStream = new FileOutputStream(FILE); Properties newProperties = new Properties(); newProperties.put("testProperty", "testValueNew"); newProperties.store(fileOutputStream, ""); - + assertTrue(testListener.isPropertiesChangedInvoked()); - + } - + @Test - public void testStopListening() throws IOException{ + public void testStopListening() throws IOException { FileOutputStream fileOutputStream = new FileOutputStream(FILE); Properties properties = new Properties(); properties.put("testProperty", "testValue"); properties.store(fileOutputStream, ""); - + Properties readProperties = PropertyUtil.getProperties(FILE, testListener); assertEquals("testValue", readProperties.getProperty("testProperty")); - + PropertyUtil.stopListening(FILE, testListener); - + properties.put("testProperty", "testValueNew"); properties.store(fileOutputStream, ""); fileOutputStream.close(); readProperties = PropertyUtil.getProperties(FILE, testListener); - // If stopListening did not remove the listener, the properties file will not be re-read until poll expires and + // If stopListening did not remove the listener, the properties file will not be re-read + // until poll expires and // hence "testValue" will be returned here instead of "testNewValue" - assertEquals("testValueNew", readProperties.getProperty("testProperty")); + assertEquals("testValueNew", readProperties.getProperty("testProperty")); } - + private class TestListener implements Listener { - + boolean propertiesChangedInvoked = false; @Override public void propertiesChanged(Properties properties, Set<String> changedKeys) { propertiesChangedInvoked = true; } - - public boolean isPropertiesChangedInvoked() throws InterruptedException{ - for (int i =0; i<20; i++){ - if (propertiesChangedInvoked){ + + public boolean isPropertiesChangedInvoked() throws InterruptedException { + for (int i = 0; i < 20; i++) { + if (propertiesChangedInvoked) { return true; } Thread.sleep(1000); diff --git a/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/SystemOutLoggerTest.java b/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/SystemOutLoggerTest.java index ceec3cce..cd16a3fd 100644 --- a/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/SystemOutLoggerTest.java +++ b/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/SystemOutLoggerTest.java @@ -17,19 +17,25 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.common.logging.flexlogger; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import com.att.eelf.configuration.EELFLogger.Level; + import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.UUID; + import org.junit.Test; import org.onap.policy.common.logging.eelf.MessageCodes; import org.onap.policy.common.logging.eelf.PolicyLogger; -import com.att.eelf.configuration.EELFLogger.Level; public class SystemOutLoggerTest { - + SystemOutLogger systemOutLogger = new SystemOutLogger("SystemOutLoggerTest"); @Test @@ -48,7 +54,7 @@ public class SystemOutLoggerTest { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); PrintStream old = System.out; - try{ + try { systemOutLogger.setTransId("transactionId"); System.setOut(ps); systemOutLogger.debug("message"); @@ -64,7 +70,7 @@ public class SystemOutLoggerTest { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); PrintStream old = System.out; - try{ + try { systemOutLogger.setTransId("transactionId"); System.setOut(ps); systemOutLogger.error("message"); @@ -80,7 +86,7 @@ public class SystemOutLoggerTest { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); PrintStream old = System.out; - try{ + try { systemOutLogger.setTransId("transactionId"); System.setOut(ps); systemOutLogger.info("message"); @@ -96,7 +102,7 @@ public class SystemOutLoggerTest { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); PrintStream old = System.out; - try{ + try { systemOutLogger.setTransId("transactionId"); System.setOut(ps); systemOutLogger.warn("message"); @@ -112,7 +118,7 @@ public class SystemOutLoggerTest { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); PrintStream old = System.out; - try{ + try { systemOutLogger.setTransId("transactionId"); System.setOut(ps); systemOutLogger.trace("message"); @@ -188,7 +194,7 @@ public class SystemOutLoggerTest { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); PrintStream old = System.out; - try{ + try { systemOutLogger.setTransId("transactionId"); System.setOut(ps); systemOutLogger.audit("message"); @@ -204,7 +210,7 @@ public class SystemOutLoggerTest { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); PrintStream old = System.out; - try{ + try { systemOutLogger.setTransId("transactionId"); System.setOut(ps); systemOutLogger.recordAuditEventStart("eventId"); @@ -220,7 +226,7 @@ public class SystemOutLoggerTest { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); PrintStream old = System.out; - try{ + try { UUID uuid = UUID.randomUUID(); System.setOut(ps); systemOutLogger.recordAuditEventStart(uuid); @@ -236,7 +242,7 @@ public class SystemOutLoggerTest { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); PrintStream old = System.out; - try{ + try { System.setOut(ps); systemOutLogger.recordAuditEventEnd("eventId", "rule", "policyVersion"); assertTrue(baos.toString().contains("SystemOutLoggerTest : eventId:rule:policyVersion")); @@ -251,7 +257,7 @@ public class SystemOutLoggerTest { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); PrintStream old = System.out; - try{ + try { UUID uuid = UUID.randomUUID(); System.setOut(ps); systemOutLogger.recordAuditEventEnd(uuid, "rule", "policyVersion"); @@ -267,7 +273,7 @@ public class SystemOutLoggerTest { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); PrintStream old = System.out; - try{ + try { System.setOut(ps); systemOutLogger.recordAuditEventEnd("eventId", "rule"); assertTrue(baos.toString().contains("SystemOutLoggerTest : eventId:rule")); @@ -282,7 +288,7 @@ public class SystemOutLoggerTest { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); PrintStream old = System.out; - try{ + try { UUID uuid = UUID.randomUUID(); System.setOut(ps); systemOutLogger.recordAuditEventEnd(uuid, "rule"); @@ -298,7 +304,7 @@ public class SystemOutLoggerTest { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); PrintStream old = System.out; - try{ + try { System.setOut(ps); systemOutLogger.recordMetricEvent("eventId", "rule"); assertTrue(baos.toString(), baos.toString().contains("SystemOutLoggerTest : eventId:eventIdmessage:rule")); @@ -313,7 +319,7 @@ public class SystemOutLoggerTest { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); PrintStream old = System.out; - try{ + try { UUID uuid = UUID.randomUUID(); System.setOut(ps); systemOutLogger.recordMetricEvent(uuid, "str1"); @@ -329,7 +335,7 @@ public class SystemOutLoggerTest { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); PrintStream old = System.out; - try{ + try { System.setOut(ps); systemOutLogger.metrics("message"); assertTrue(baos.toString().contains("SystemOutLoggerTest : message")); @@ -344,10 +350,11 @@ public class SystemOutLoggerTest { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); PrintStream old = System.out; - try{ + try { System.setOut(ps); systemOutLogger.error(MessageCodes.ERROR_DATA_ISSUE, new NullPointerException(), "str1", "str2"); - assertTrue(baos.toString().contains("SystemOutLoggerTest : MessageCodes :" + MessageCodes.ERROR_DATA_ISSUE + "[str1, str2]")); + assertTrue(baos.toString() + .contains("SystemOutLoggerTest : MessageCodes :" + MessageCodes.ERROR_DATA_ISSUE + "[str1, str2]")); } finally { System.out.flush(); System.setOut(old); @@ -359,11 +366,12 @@ public class SystemOutLoggerTest { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); PrintStream old = System.out; - try{ + try { System.setOut(ps); systemOutLogger.setTransId("transactionId"); systemOutLogger.error(MessageCodes.ERROR_DATA_ISSUE, "str1", "str2"); - assertTrue(baos.toString().contains("transactionId|SystemOutLoggerTest : MessageCode:" + MessageCodes.ERROR_DATA_ISSUE + "[str1, str2]")); + assertTrue(baos.toString().contains("transactionId|SystemOutLoggerTest : MessageCode:" + + MessageCodes.ERROR_DATA_ISSUE + "[str1, str2]")); } finally { System.out.flush(); System.setOut(old); @@ -380,11 +388,12 @@ public class SystemOutLoggerTest { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); PrintStream old = System.out; - try{ + try { System.setOut(ps); systemOutLogger.setTransId("transactionId"); systemOutLogger.warn(MessageCodes.ERROR_DATA_ISSUE, "str1", "str2"); - assertTrue(baos.toString().contains("transactionId|SystemOutLoggerTest : MessageCodes:" + MessageCodes.ERROR_DATA_ISSUE + "[str1, str2]")); + assertTrue(baos.toString().contains("transactionId|SystemOutLoggerTest : MessageCodes:" + + MessageCodes.ERROR_DATA_ISSUE + "[str1, str2]")); } finally { System.out.flush(); System.setOut(old); @@ -396,11 +405,12 @@ public class SystemOutLoggerTest { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); PrintStream old = System.out; - try{ + try { System.setOut(ps); systemOutLogger.setTransId("transactionId"); systemOutLogger.warn(MessageCodes.ERROR_DATA_ISSUE, new NullPointerException(), "str1", "str2"); - assertTrue(baos.toString().contains("transactionId|SystemOutLoggerTest : MessageCodes:" + MessageCodes.ERROR_DATA_ISSUE + "[str1, str2]")); + assertTrue(baos.toString().contains("transactionId|SystemOutLoggerTest : MessageCodes:" + + MessageCodes.ERROR_DATA_ISSUE + "[str1, str2]")); } finally { System.out.flush(); System.setOut(old); @@ -412,15 +422,16 @@ public class SystemOutLoggerTest { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); PrintStream old = System.out; - try{ + try { System.setOut(ps); systemOutLogger.setTransId("transactionId"); systemOutLogger.debug(1, new NullPointerException()); - assertTrue(baos.toString(), baos.toString().contains("transactionId|SystemOutLoggerTest : 1:java.lang.NullPointerException")); + assertTrue(baos.toString(), + baos.toString().contains("transactionId|SystemOutLoggerTest : 1:java.lang.NullPointerException")); } finally { System.out.flush(); System.setOut(old); - } + } } @Test @@ -428,11 +439,12 @@ public class SystemOutLoggerTest { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); PrintStream old = System.out; - try{ + try { System.setOut(ps); systemOutLogger.setTransId("transactionId"); systemOutLogger.error(1, new NullPointerException()); - assertTrue(baos.toString(), baos.toString().contains("transactionId|SystemOutLoggerTest : 1:java.lang.NullPointerException")); + assertTrue(baos.toString(), + baos.toString().contains("transactionId|SystemOutLoggerTest : 1:java.lang.NullPointerException")); } finally { System.out.flush(); System.setOut(old); @@ -444,11 +456,12 @@ public class SystemOutLoggerTest { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); PrintStream old = System.out; - try{ + try { System.setOut(ps); systemOutLogger.setTransId("transactionId"); systemOutLogger.info(1, new NullPointerException()); - assertTrue(baos.toString(), baos.toString().contains("transactionId|SystemOutLoggerTest : 1:java.lang.NullPointerException")); + assertTrue(baos.toString(), + baos.toString().contains("transactionId|SystemOutLoggerTest : 1:java.lang.NullPointerException")); } finally { System.out.flush(); System.setOut(old); @@ -460,11 +473,12 @@ public class SystemOutLoggerTest { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); PrintStream old = System.out; - try{ + try { System.setOut(ps); systemOutLogger.setTransId("transactionId"); systemOutLogger.warn(1, new NullPointerException()); - assertTrue(baos.toString(), baos.toString().contains("transactionId|SystemOutLoggerTest : 1:java.lang.NullPointerException")); + assertTrue(baos.toString(), + baos.toString().contains("transactionId|SystemOutLoggerTest : 1:java.lang.NullPointerException")); } finally { System.out.flush(); System.setOut(old); @@ -476,11 +490,12 @@ public class SystemOutLoggerTest { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); PrintStream old = System.out; - try{ + try { System.setOut(ps); systemOutLogger.setTransId("transactionId"); systemOutLogger.trace(1, new NullPointerException()); - assertTrue(baos.toString(), baos.toString().contains("transactionId|SystemOutLoggerTest : 1:java.lang.NullPointerException")); + assertTrue(baos.toString(), + baos.toString().contains("transactionId|SystemOutLoggerTest : 1:java.lang.NullPointerException")); } finally { System.out.flush(); System.setOut(old); @@ -492,11 +507,12 @@ public class SystemOutLoggerTest { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); PrintStream old = System.out; - try{ + try { System.setOut(ps); systemOutLogger.setTransId("transactionId"); systemOutLogger.audit(1, new NullPointerException()); - assertTrue(baos.toString(), baos.toString().contains("transactionId|SystemOutLoggerTest : 1:java.lang.NullPointerException")); + assertTrue(baos.toString(), + baos.toString().contains("transactionId|SystemOutLoggerTest : 1:java.lang.NullPointerException")); } finally { System.out.flush(); System.setOut(old); @@ -513,7 +529,7 @@ public class SystemOutLoggerTest { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); PrintStream old = System.out; - try{ + try { System.setOut(ps); systemOutLogger.postMDCInfoForTriggeredRule("transactionId"); assertTrue(baos.toString(), baos.toString().contains("transactionId")); @@ -528,7 +544,7 @@ public class SystemOutLoggerTest { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); PrintStream old = System.out; - try{ + try { System.setOut(ps); systemOutLogger.postMDCInfoForEvent(1); assertTrue(baos.toString(), baos.toString().contains("1")); diff --git a/common-logging/src/test/java/org/onap/policy/common/logging/util/TestUtils.java b/common-logging/src/test/java/org/onap/policy/common/logging/util/TestUtils.java index 17eee02a..94bfbb74 100644 --- a/common-logging/src/test/java/org/onap/policy/common/logging/util/TestUtils.java +++ b/common-logging/src/test/java/org/onap/policy/common/logging/util/TestUtils.java @@ -17,15 +17,27 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + + package org.onap.policy.common.logging.util; import static org.junit.Assert.fail; + import java.lang.reflect.Field; import java.lang.reflect.Modifier; public class TestUtils { - - public static void overrideField(@SuppressWarnings("rawtypes") final Class clazz, final Object object, final String fieldName, final Object newValue) { + + /** + * Override a field. + * + * @param clazz the class the field belongs to + * @param object the instance of the class + * @param fieldName the name of the field + * @param newValue the value to set the field to + */ + public static void overrideField(@SuppressWarnings("rawtypes") final Class clazz, final Object object, + final String fieldName, final Object newValue) { try { final Field field = clazz.getDeclaredField(fieldName); field.setAccessible(true); @@ -38,8 +50,16 @@ public class TestUtils { fail(e.toString()); } } - - public static void overrideStaticField(@SuppressWarnings("rawtypes") final Class clazz, final String fieldName, final Object newValue) { + + /** + * Override a static field. + * + * @param clazz the class the field belongs to + * @param fieldName the name of the field + * @param newValue the value to set the field to + */ + public static void overrideStaticField(@SuppressWarnings("rawtypes") final Class clazz, final String fieldName, + final Object newValue) { try { final Field field = clazz.getDeclaredField(fieldName); field.setAccessible(true); |