From 02ba37e23bebc5fc8831feaa4ce073295c3c93d8 Mon Sep 17 00:00:00 2001 From: Jim Hahn Date: Fri, 5 Jul 2019 13:03:06 -0400 Subject: Fix sonar issues in policy ONAP logging Sonar fixes, other than code coverage. These changes are disruptive and will likely cause breakage in a number of policy repos. Renamed constants. Moved constants/factories from interfaces to classes. Also fixed remaining checkstyle issues, which was equally disruptive, as it required renaming of methods and classes. Split out Onap config properties from EELF config properties, in case changes are made in the future such that Onap properties can no longer subclass from EELF properties (e.g., if EELF properties are converted from a interface to a utility class with a private constructor). Attempted to eliminate some duplicate blocks of code by refactoring out common methods. Change-Id: Ie038d2d4ed553037a9af3f0ddf31baf2b3628fa3 Issue-ID: POLICY-1791 Signed-off-by: Jim Hahn --- .../policy/common/logging/ONAPLoggingContext.java | 568 --------------------- .../policy/common/logging/ONAPLoggingUtils.java | 62 --- .../policy/common/logging/OnapLoggingContext.java | 568 +++++++++++++++++++++ .../policy/common/logging/OnapLoggingUtils.java | 62 +++ .../policy/common/logging/eelf/Configuration.java | 82 --- .../common/logging/eelf/DroolsPDPMDCInfo.java | 52 -- .../common/logging/eelf/DroolsPdpMdcInfo.java | 53 ++ .../onap/policy/common/logging/eelf/EventData.java | 16 +- .../policy/common/logging/eelf/EventTrackInfo.java | 20 +- .../common/logging/eelf/EventTrackInfoHandler.java | 4 +- .../onap/policy/common/logging/eelf/MDCInfo.java | 37 -- .../onap/policy/common/logging/eelf/MdcInfo.java | 37 ++ .../common/logging/eelf/OnapConfigProperties.java | 87 ++++ .../policy/common/logging/eelf/PolicyLogger.java | 421 +++++---------- .../common/logging/flexlogger/DisplayUtils.java | 41 ++ .../common/logging/flexlogger/EelfLogger.java | 114 ++--- .../common/logging/flexlogger/FlexLogger.java | 70 ++- .../policy/common/logging/flexlogger/Logger.java | 12 +- .../policy/common/logging/flexlogger/Logger4J.java | 92 ++-- .../common/logging/flexlogger/PropertyUtil.java | 28 +- .../common/logging/flexlogger/SystemOutLogger.java | 149 +++--- .../common/logging/nsa/LoggingContextFactory.java | 12 +- .../common/logging/eelf/DroolsPDPMDCInfoTest.java | 41 -- .../common/logging/eelf/DroolsPdpMdcInfoTest.java | 42 ++ .../policy/common/logging/eelf/EventDataTest.java | 22 +- .../common/logging/eelf/EventTrackInfoTest.java | 28 +- .../common/logging/eelf/PolicyLoggerTest.java | 121 ++--- .../common/logging/flexlogger/EelfLoggerTest.java | 71 ++- .../common/logging/flexlogger/FlexLoggerTest.java | 32 +- .../common/logging/flexlogger/Logger4JTest.java | 96 ++-- .../logging/flexlogger/SystemOutLoggerTest.java | 25 +- .../onap/policy/common/logging/util/TestUtils.java | 77 --- 32 files changed, 1486 insertions(+), 1656 deletions(-) delete mode 100644 common-logging/src/main/java/org/onap/policy/common/logging/ONAPLoggingContext.java delete mode 100644 common-logging/src/main/java/org/onap/policy/common/logging/ONAPLoggingUtils.java create mode 100644 common-logging/src/main/java/org/onap/policy/common/logging/OnapLoggingContext.java create mode 100644 common-logging/src/main/java/org/onap/policy/common/logging/OnapLoggingUtils.java delete mode 100644 common-logging/src/main/java/org/onap/policy/common/logging/eelf/Configuration.java delete mode 100644 common-logging/src/main/java/org/onap/policy/common/logging/eelf/DroolsPDPMDCInfo.java create mode 100644 common-logging/src/main/java/org/onap/policy/common/logging/eelf/DroolsPdpMdcInfo.java delete mode 100644 common-logging/src/main/java/org/onap/policy/common/logging/eelf/MDCInfo.java create mode 100644 common-logging/src/main/java/org/onap/policy/common/logging/eelf/MdcInfo.java create mode 100644 common-logging/src/main/java/org/onap/policy/common/logging/eelf/OnapConfigProperties.java create mode 100644 common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/DisplayUtils.java delete mode 100644 common-logging/src/test/java/org/onap/policy/common/logging/eelf/DroolsPDPMDCInfoTest.java create mode 100644 common-logging/src/test/java/org/onap/policy/common/logging/eelf/DroolsPdpMdcInfoTest.java delete mode 100644 common-logging/src/test/java/org/onap/policy/common/logging/util/TestUtils.java (limited to 'common-logging/src') 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 deleted file mode 100644 index 92bc6236..00000000 --- a/common-logging/src/main/java/org/onap/policy/common/logging/ONAPLoggingContext.java +++ /dev/null @@ -1,568 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP-Logging - * ================================================================================ - * 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. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.logging; - -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 - * 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. - * - */ -public class ONAPLoggingContext { - - private static final String REQUEST_ID = "requestId"; - private static final String SERVICE_INSTANCE_ID = "serviceInstanceId"; - private static final String THREAD_ID = "threadId"; - private static final String SERVER_NAME = "serverName"; - private static final String SERVICE_NAME = "serviceName"; - private static final String PARTNER_NAME = "partnerName"; - private static final String STATUS_CODE = "statusCode"; - private static final String TARGET_ENTITY = "targetEntity"; - private static final String TARGET_SERVICE_NAME = "targetServiceName"; - private static final String INSTANCE_UUID = "instanceUuid"; - private static final String SEVERITY = "severity"; - private static final String SERVER_IP_ADDRESS = "serverIpAddress"; - private static final String SERVER = "server"; - private static final String CLIENT_IP_ADDRESS = "clientIpAddress"; - private static final String CLASSNAME = "classname"; - private static final String TRANSACTION_BEGIN_TIME_STAMP = "TransactionBeginTimestamp"; - private static final String TRANSACTION_END_TIME_STAMP = "TransactionEndTimestamp"; - private static final String TRANSACTION_ELAPSED_TIME = "TransactionElapsedTime"; - private static final String METRIC_BEGIN_TIME_STAMP = "MetricBeginTimestamp"; - private static final String METRIC_END_TIME_STAMP = "MetricEndTimestamp"; - private static final String METRIC_ELAPSED_TIME = "MetricElapsedTime"; - private static final String POLICY = "POLICY"; - private static final String USER = "USER"; - private static final String COMPLETE = "COMPLETE"; - private static final String PE_PROCESS = "PE Process"; - private static final String TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS+00:00"; - private static final String EMPTY_STRING = ""; - private static final int DEFAULT_VALUE = 0; - - - private static LoggingContextFactory.Builder loggingContextBuilder = new LoggingContextFactory.Builder(); - - protected SharedLoggingContext context = null; - private Instant transactionStartTime; - private Instant metricStartTime; - - /** - * Create a new ONAPLoggingContext with no base context. - */ - public ONAPLoggingContext() { - context = (SharedLoggingContext) loggingContextBuilder.forSharing().build(); - } - - /** - * 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) { - context = (SharedLoggingContext) loggingContextBuilder.forSharing().build(); - // a logging context could be passed into a thread (e.g. one that is servicing a queue) - // that already had a logging context established, so the MDC hashmap could contain - // entries that are no longer appropriate; so clear out the MDC hashmap before - // transferring the new logging context values. - // x - MDC.clear(); - baseContext.context.transferTo(context); - transactionStartTime = baseContext.transactionStartTime; - setServiceName(POLICY); - setPartnerName(USER); - setStatusCode(COMPLETE); - setTargetEntity(POLICY); - setTargetServiceName(PE_PROCESS); - } - - /** - * Indicate the start of transaction processing. The current system time will be recorded for - * use by transactionEnded() to calculate the duration of the transaction. - */ - public void transactionStarted() { - transactionStartTime = Instant.now(); - setTransactionBeginTimestamp(transactionStartTime); - } - - /** - * Indicate the end of transaction processing. The difference between the current system time - * and the time recorded by transactionStarted() will be recorded in the data item - * with key "TransactionElapsedTime". - */ - public void transactionEnded() { - Instant transactionEndTime = Instant.now(); - setTransactionEndTimestamp(transactionEndTime); - setTransactionElapsedTime(transactionEndTime); - } - - /** - * Indicate the start of metric processing. The current system time will be recorded for use by - * metricEnded() to calculate the duration of the metric. - */ - public void metricStarted() { - metricStartTime = Instant.now(); - setMetricBeginTimestamp(metricStartTime); - } - - /** - * Indicate the end of metric processing. The difference between the current system time and the - * time recorded by metricStarted() will be recorded in the data item with key - * "MetricElapsedTime". - */ - public void metricEnded() { - Instant metricEndTime = Instant.now(); - setMetricEndTimestamp(metricEndTime); - setMetricElapsedTime(metricEndTime); - } - - /** - * Set the value for the data item with key "requestId". - * - * @param id request identifier - */ - public void setRequestID(String id) { - context.put(REQUEST_ID, id); - } - - /** - * Get the value for the data item with key "requestId". - * - * @return current value, or empty string if not set - */ - public String getRequestID() { - return context.get(REQUEST_ID, EMPTY_STRING); - } - - /** - * Set the value for the data item with key "serviceInstanceId". - * - * @param id service identifier - */ - public void setServiceInstanceID(String id) { - context.put(SERVICE_INSTANCE_ID, id); - } - - /** - * Get the value for the data item with key "serviceInstanceId". - * - * @return current value, or empty string if not set - */ - public String getServiceInstanceID() { - return context.get(SERVICE_INSTANCE_ID, EMPTY_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 - */ - public void setThreadID(String id) { - context.put(THREAD_ID, id); - } - - /** - * Get the value for the data item with key "threadId". - * - * @return current value, or empty string if not set - */ - public String getThreadID() { - return context.get(THREAD_ID, EMPTY_STRING); - } - - /** - * Set the value for the data item with key "serverName". - * - * @param name server name - */ - public void setServerName(String name) { - context.put(SERVER_NAME, name); - } - - /** - * Get the value for the data item with key "serverName". - * - * @return current value, or empty string if not set - */ - public String getServerName() { - return context.get(SERVER_NAME, EMPTY_STRING); - } - - /** - * Set the value for the data item with key "serviceName". - * - * @param name service name - */ - public void setServiceName(String name) { - context.put(SERVICE_NAME, name); - } - - /** - * Get the value for the data item with key "serviceName". - * - * @return current value, or empty string if not set - */ - public String getServiceName() { - return context.get(SERVICE_NAME, EMPTY_STRING); - } - - /** - * Set the value for the data item with key "partnerName". - * - * @param name partner name - */ - public void setPartnerName(String name) { - context.put(PARTNER_NAME, name); - } - - /** - * Get the value for the data item with key "partnerName". - * - * @return current value, or empty string if not set - */ - public String getPartnerName() { - return context.get(PARTNER_NAME, EMPTY_STRING); - } - - /** - * Set the value for the data item with key "statusCode". - * - * @param name status code - */ - public void setStatusCode(String name) { - context.put(STATUS_CODE, name); - } - - /** - * Get the value for the data item with key "statusCode". - * - * @return current value, or empty string if not set - */ - public String getStatusCode() { - return context.get(STATUS_CODE, EMPTY_STRING); - } - - /** - * Set the value for the data item with key "targetEntity". - * - * @param name target entity - */ - public void setTargetEntity(String name) { - context.put(TARGET_ENTITY, name); - } - - /** - * Get the value for the data item with key "targetEntity". - * - * @return current value, or empty string if not set - */ - public String getTargetEntity() { - return context.get(TARGET_ENTITY, EMPTY_STRING); - } - - /** - * Set the value for the data item with key "targetServiceName". - * - * @param name target service name - */ - public void setTargetServiceName(String name) { - context.put(TARGET_SERVICE_NAME, name); - } - - /** - * Get the value for the data item with key "targetServiceName". - * - * @return current value, or empty string if not set - */ - public String getTargetServiceName() { - return context.get(TARGET_SERVICE_NAME, EMPTY_STRING); - } - - /** - * Set the value for the data item with key "instanceUuid". - * - * @param uuid instance uuid - */ - public void setInstanceUUID(String uuid) { - context.put(INSTANCE_UUID, uuid); - } - - /** - * Get the value for the data item with key "instanceUuid". - * - * @return current value, or empty string if not set - */ - public String getInstanceUUID() { - return context.get(INSTANCE_UUID, EMPTY_STRING); - } - - /** - * Set the value for the data item with key "severity". - * - * @param severity severity - */ - public void setSeverity(Long severity) { - context.put(SEVERITY, severity); - } - - /** - * Get the value for the data item with key "severity". - * - * @return current value, or empty string if not set - */ - public String getSeverity() { - return context.get(SEVERITY, EMPTY_STRING); - } - - /** - * Set the value for the data item with key "serverIp". - * - * @param serverIP server ip address - */ - public void setServerIPAddress(String serverIP) { - context.put(SERVER_IP_ADDRESS, serverIP); - } - - /** - * Get the value for the data item with key "serverIp". - * - * @return current value, or empty string if not set - */ - public String getServerIPAddress() { - return context.get(SERVER_IP_ADDRESS, EMPTY_STRING); - } - - /** - * Set the value for the data item with key "server". - * - * @param server server - */ - public void setServer(String server) { - context.put(SERVER, server); - } - - /** - * Get the value for the data item with key "server". - * - * @return current value, or empty string if not set - */ - public String getServer() { - return context.get(SERVER, EMPTY_STRING); - } - - /** - * Set the value for the data item with key "clientIp". - * - * @param clientIP client ip address - */ - public void setClientIPAddress(String clientIP) { - context.put(CLIENT_IP_ADDRESS, clientIP); - } - - /** - * Get the value for the data item with key "clientIp". - * - * @return current value, or empty string if not set - */ - public String getClientIPAddress() { - return context.get(CLIENT_IP_ADDRESS, EMPTY_STRING); - } - - /** - * 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 - */ - public void setClassname(String classname) { - context.put(CLASSNAME, classname); - } - - /** - * Get the value for the data item with key "classname". - * - * @return current value, or empty string if not set - */ - public String getClassname() { - return context.get(CLASSNAME, EMPTY_STRING); - } - - /** - * Set the value for the data item with key "TransactionBeginTimestamp". - * - * @param transactionStartTime transaction start time - */ - public void setTransactionBeginTimestamp(Instant transactionStartTime) { - SimpleDateFormat sdf = new SimpleDateFormat(TIME_FORMAT); - context.put(TRANSACTION_BEGIN_TIME_STAMP, sdf.format(Date.from(transactionStartTime))); - } - - /** - * Get the value for the data item with key "TransactionBeginTimestamp". - * - * @return current value, or 0 if not set - */ - public long getTransactionBeginTimestamp() { - return context.get(TRANSACTION_BEGIN_TIME_STAMP, DEFAULT_VALUE); - } - - /** - * Set the value for the data item with key "TransactionEndTimestamp". - * - * @param transactionEndTime transaction end time - */ - public void setTransactionEndTimestamp(Instant transactionEndTime) { - SimpleDateFormat sdf = new SimpleDateFormat(TIME_FORMAT); - context.put(TRANSACTION_END_TIME_STAMP, sdf.format(Date.from(transactionEndTime))); - } - - /** - * Get the value for the data item with key "TransactionEndTimestamp". - * - * @return current value, or 0 if not set - */ - public long getTransactionEndTimestamp() { - return context.get(TRANSACTION_END_TIME_STAMP, DEFAULT_VALUE); - } - - /** - * Set the value for the data item with key "TransactionElapsedTime". An alternative to calling - * this method directly is to call transactionStarted() at the start of transaction - * processing and transactionEnded() at the end, which will compute the time - * difference in milliseconds and store the result as the "ns" value. - * - * @param transactionEndTime transaction end time - */ - - public void setTransactionElapsedTime(Instant transactionEndTime) { - long ns = Duration.between(transactionStartTime, transactionEndTime).toMillis(); - context.put(TRANSACTION_ELAPSED_TIME, ns); - } - - /** - * Get the value for the data item with key "TransactionElapsedTime". - * - * @return current value, or 0 if not set - */ - public long getTransactionElapsedTime() { - return context.get(TRANSACTION_ELAPSED_TIME, DEFAULT_VALUE); - } - - /** - * Set the value for the data item with key "MetricBeginTimestamp". - * - * @param metricStartTime metric start time - */ - public void setMetricBeginTimestamp(Instant metricStartTime) { - SimpleDateFormat sdf = new SimpleDateFormat(TIME_FORMAT); - context.put(METRIC_BEGIN_TIME_STAMP, sdf.format(Date.from(metricStartTime))); - } - - /** - * Get the value for the data item with key "MetricBeginTimestamp". - * - * @return current value, or 0 if not set - */ - public long getMetricBeginTimestamp() { - return context.get(METRIC_BEGIN_TIME_STAMP, DEFAULT_VALUE); - } - - /** - * Set the value for the data item with key "MetricEndTimestamp". - * - * @param metricEndTime metric end time - */ - public void setMetricEndTimestamp(Instant metricEndTime) { - SimpleDateFormat sdf = new SimpleDateFormat(TIME_FORMAT); - context.put(METRIC_END_TIME_STAMP, sdf.format(Date.from(metricEndTime))); - } - - /** - * Get the value for the data item with key "MetricEndTimestamp". - * - * @return current value, or 0 if not set - */ - public long getMetricEndTimestamp() { - return context.get(METRIC_END_TIME_STAMP, DEFAULT_VALUE); - } - - /** - * Set the value for the data item with key "MetricElapsedTime". An alternative to calling this - * method directly is to call metricStarted() at the start of metric processing and - * metricEnded() at the end, which will compute the time difference in milliseconds - * and store the result as the "ns" value. - * - * @param metricEndTime metric end time - */ - - public void setMetricElapsedTime(Instant metricEndTime) { - long ns = Duration.between(metricStartTime, metricEndTime).toMillis(); - context.put(METRIC_ELAPSED_TIME, ns); - } - - /** - * Get the value for the data item with key "MetricElapsedTime". - * - * @return current value, or 0 if not set - */ - public long getMetricElapsedTime() { - return context.get(METRIC_ELAPSED_TIME, DEFAULT_VALUE); - } -} 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 deleted file mode 100644 index 0983ed6f..00000000 --- a/common-logging/src/main/java/org/onap/policy/common/logging/ONAPLoggingUtils.java +++ /dev/null @@ -1,62 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP-Logging - * ================================================================================ - * 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. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.logging; - -import javax.servlet.http.HttpServletRequest; - -public class ONAPLoggingUtils { - - 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/OnapLoggingContext.java b/common-logging/src/main/java/org/onap/policy/common/logging/OnapLoggingContext.java new file mode 100644 index 00000000..0373abfe --- /dev/null +++ b/common-logging/src/main/java/org/onap/policy/common/logging/OnapLoggingContext.java @@ -0,0 +1,568 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-Logging + * ================================================================================ + * Copyright (C) 2017-2019 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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.common.logging; + +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 + * 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. + * + */ +public class OnapLoggingContext { + + private static final String REQUEST_ID = "requestId"; + private static final String SERVICE_INSTANCE_ID = "serviceInstanceId"; + private static final String THREAD_ID = "threadId"; + private static final String SERVER_NAME = "serverName"; + private static final String SERVICE_NAME = "serviceName"; + private static final String PARTNER_NAME = "partnerName"; + private static final String STATUS_CODE = "statusCode"; + private static final String TARGET_ENTITY = "targetEntity"; + private static final String TARGET_SERVICE_NAME = "targetServiceName"; + private static final String INSTANCE_UUID = "instanceUuid"; + private static final String SEVERITY = "severity"; + private static final String SERVER_IP_ADDRESS = "serverIpAddress"; + private static final String SERVER = "server"; + private static final String CLIENT_IP_ADDRESS = "clientIpAddress"; + private static final String CLASSNAME = "classname"; + private static final String TRANSACTION_BEGIN_TIME_STAMP = "TransactionBeginTimestamp"; + private static final String TRANSACTION_END_TIME_STAMP = "TransactionEndTimestamp"; + private static final String TRANSACTION_ELAPSED_TIME = "TransactionElapsedTime"; + private static final String METRIC_BEGIN_TIME_STAMP = "MetricBeginTimestamp"; + private static final String METRIC_END_TIME_STAMP = "MetricEndTimestamp"; + private static final String METRIC_ELAPSED_TIME = "MetricElapsedTime"; + private static final String POLICY = "POLICY"; + private static final String USER = "USER"; + private static final String COMPLETE = "COMPLETE"; + private static final String PE_PROCESS = "PE Process"; + private static final String TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS+00:00"; + private static final String EMPTY_STRING = ""; + private static final int DEFAULT_VALUE = 0; + + + private static LoggingContextFactory.Builder loggingContextBuilder = new LoggingContextFactory.Builder(); + + protected SharedLoggingContext context = null; + private Instant transactionStartTime; + private Instant metricStartTime; + + /** + * Create a new ONAPLoggingContext with no base context. + */ + public OnapLoggingContext() { + context = (SharedLoggingContext) loggingContextBuilder.forSharing().build(); + } + + /** + * 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) { + context = (SharedLoggingContext) loggingContextBuilder.forSharing().build(); + // a logging context could be passed into a thread (e.g. one that is servicing a queue) + // that already had a logging context established, so the MDC hashmap could contain + // entries that are no longer appropriate; so clear out the MDC hashmap before + // transferring the new logging context values. + // x + MDC.clear(); + baseContext.context.transferTo(context); + transactionStartTime = baseContext.transactionStartTime; + setServiceName(POLICY); + setPartnerName(USER); + setStatusCode(COMPLETE); + setTargetEntity(POLICY); + setTargetServiceName(PE_PROCESS); + } + + /** + * Indicate the start of transaction processing. The current system time will be recorded for + * use by transactionEnded() to calculate the duration of the transaction. + */ + public void transactionStarted() { + transactionStartTime = Instant.now(); + setTransactionBeginTimestamp(transactionStartTime); + } + + /** + * Indicate the end of transaction processing. The difference between the current system time + * and the time recorded by transactionStarted() will be recorded in the data item + * with key "TransactionElapsedTime". + */ + public void transactionEnded() { + Instant transactionEndTime = Instant.now(); + setTransactionEndTimestamp(transactionEndTime); + setTransactionElapsedTime(transactionEndTime); + } + + /** + * Indicate the start of metric processing. The current system time will be recorded for use by + * metricEnded() to calculate the duration of the metric. + */ + public void metricStarted() { + metricStartTime = Instant.now(); + setMetricBeginTimestamp(metricStartTime); + } + + /** + * Indicate the end of metric processing. The difference between the current system time and the + * time recorded by metricStarted() will be recorded in the data item with key + * "MetricElapsedTime". + */ + public void metricEnded() { + Instant metricEndTime = Instant.now(); + setMetricEndTimestamp(metricEndTime); + setMetricElapsedTime(metricEndTime); + } + + /** + * Set the value for the data item with key "requestId". + * + * @param id request identifier + */ + public void setRequestId(String id) { + context.put(REQUEST_ID, id); + } + + /** + * Get the value for the data item with key "requestId". + * + * @return current value, or empty string if not set + */ + public String getRequestId() { + return context.get(REQUEST_ID, EMPTY_STRING); + } + + /** + * Set the value for the data item with key "serviceInstanceId". + * + * @param id service identifier + */ + public void setServiceInstanceId(String id) { + context.put(SERVICE_INSTANCE_ID, id); + } + + /** + * Get the value for the data item with key "serviceInstanceId". + * + * @return current value, or empty string if not set + */ + public String getServiceInstanceId() { + return context.get(SERVICE_INSTANCE_ID, EMPTY_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 + */ + public void setThreadId(String id) { + context.put(THREAD_ID, id); + } + + /** + * Get the value for the data item with key "threadId". + * + * @return current value, or empty string if not set + */ + public String getThreadId() { + return context.get(THREAD_ID, EMPTY_STRING); + } + + /** + * Set the value for the data item with key "serverName". + * + * @param name server name + */ + public void setServerName(String name) { + context.put(SERVER_NAME, name); + } + + /** + * Get the value for the data item with key "serverName". + * + * @return current value, or empty string if not set + */ + public String getServerName() { + return context.get(SERVER_NAME, EMPTY_STRING); + } + + /** + * Set the value for the data item with key "serviceName". + * + * @param name service name + */ + public void setServiceName(String name) { + context.put(SERVICE_NAME, name); + } + + /** + * Get the value for the data item with key "serviceName". + * + * @return current value, or empty string if not set + */ + public String getServiceName() { + return context.get(SERVICE_NAME, EMPTY_STRING); + } + + /** + * Set the value for the data item with key "partnerName". + * + * @param name partner name + */ + public void setPartnerName(String name) { + context.put(PARTNER_NAME, name); + } + + /** + * Get the value for the data item with key "partnerName". + * + * @return current value, or empty string if not set + */ + public String getPartnerName() { + return context.get(PARTNER_NAME, EMPTY_STRING); + } + + /** + * Set the value for the data item with key "statusCode". + * + * @param name status code + */ + public void setStatusCode(String name) { + context.put(STATUS_CODE, name); + } + + /** + * Get the value for the data item with key "statusCode". + * + * @return current value, or empty string if not set + */ + public String getStatusCode() { + return context.get(STATUS_CODE, EMPTY_STRING); + } + + /** + * Set the value for the data item with key "targetEntity". + * + * @param name target entity + */ + public void setTargetEntity(String name) { + context.put(TARGET_ENTITY, name); + } + + /** + * Get the value for the data item with key "targetEntity". + * + * @return current value, or empty string if not set + */ + public String getTargetEntity() { + return context.get(TARGET_ENTITY, EMPTY_STRING); + } + + /** + * Set the value for the data item with key "targetServiceName". + * + * @param name target service name + */ + public void setTargetServiceName(String name) { + context.put(TARGET_SERVICE_NAME, name); + } + + /** + * Get the value for the data item with key "targetServiceName". + * + * @return current value, or empty string if not set + */ + public String getTargetServiceName() { + return context.get(TARGET_SERVICE_NAME, EMPTY_STRING); + } + + /** + * Set the value for the data item with key "instanceUuid". + * + * @param uuid instance uuid + */ + public void setInstanceUuid(String uuid) { + context.put(INSTANCE_UUID, uuid); + } + + /** + * Get the value for the data item with key "instanceUuid". + * + * @return current value, or empty string if not set + */ + public String getInstanceUuid() { + return context.get(INSTANCE_UUID, EMPTY_STRING); + } + + /** + * Set the value for the data item with key "severity". + * + * @param severity severity + */ + public void setSeverity(Long severity) { + context.put(SEVERITY, severity); + } + + /** + * Get the value for the data item with key "severity". + * + * @return current value, or empty string if not set + */ + public String getSeverity() { + return context.get(SEVERITY, EMPTY_STRING); + } + + /** + * Set the value for the data item with key "serverIp". + * + * @param serverIp server ip address + */ + public void setServerIpAddress(String serverIp) { + context.put(SERVER_IP_ADDRESS, serverIp); + } + + /** + * Get the value for the data item with key "serverIp". + * + * @return current value, or empty string if not set + */ + public String getServerIpAddress() { + return context.get(SERVER_IP_ADDRESS, EMPTY_STRING); + } + + /** + * Set the value for the data item with key "server". + * + * @param server server + */ + public void setServer(String server) { + context.put(SERVER, server); + } + + /** + * Get the value for the data item with key "server". + * + * @return current value, or empty string if not set + */ + public String getServer() { + return context.get(SERVER, EMPTY_STRING); + } + + /** + * Set the value for the data item with key "clientIp". + * + * @param clientIp client ip address + */ + public void setClientIpAddress(String clientIp) { + context.put(CLIENT_IP_ADDRESS, clientIp); + } + + /** + * Get the value for the data item with key "clientIp". + * + * @return current value, or empty string if not set + */ + public String getClientIpAddress() { + return context.get(CLIENT_IP_ADDRESS, EMPTY_STRING); + } + + /** + * 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 + */ + public void setClassname(String classname) { + context.put(CLASSNAME, classname); + } + + /** + * Get the value for the data item with key "classname". + * + * @return current value, or empty string if not set + */ + public String getClassname() { + return context.get(CLASSNAME, EMPTY_STRING); + } + + /** + * Set the value for the data item with key "TransactionBeginTimestamp". + * + * @param transactionStartTime transaction start time + */ + public void setTransactionBeginTimestamp(Instant transactionStartTime) { + SimpleDateFormat sdf = new SimpleDateFormat(TIME_FORMAT); + context.put(TRANSACTION_BEGIN_TIME_STAMP, sdf.format(Date.from(transactionStartTime))); + } + + /** + * Get the value for the data item with key "TransactionBeginTimestamp". + * + * @return current value, or 0 if not set + */ + public long getTransactionBeginTimestamp() { + return context.get(TRANSACTION_BEGIN_TIME_STAMP, DEFAULT_VALUE); + } + + /** + * Set the value for the data item with key "TransactionEndTimestamp". + * + * @param transactionEndTime transaction end time + */ + public void setTransactionEndTimestamp(Instant transactionEndTime) { + SimpleDateFormat sdf = new SimpleDateFormat(TIME_FORMAT); + context.put(TRANSACTION_END_TIME_STAMP, sdf.format(Date.from(transactionEndTime))); + } + + /** + * Get the value for the data item with key "TransactionEndTimestamp". + * + * @return current value, or 0 if not set + */ + public long getTransactionEndTimestamp() { + return context.get(TRANSACTION_END_TIME_STAMP, DEFAULT_VALUE); + } + + /** + * Set the value for the data item with key "TransactionElapsedTime". An alternative to calling + * this method directly is to call transactionStarted() at the start of transaction + * processing and transactionEnded() at the end, which will compute the time + * difference in milliseconds and store the result as the "ns" value. + * + * @param transactionEndTime transaction end time + */ + + public void setTransactionElapsedTime(Instant transactionEndTime) { + long ns = Duration.between(transactionStartTime, transactionEndTime).toMillis(); + context.put(TRANSACTION_ELAPSED_TIME, ns); + } + + /** + * Get the value for the data item with key "TransactionElapsedTime". + * + * @return current value, or 0 if not set + */ + public long getTransactionElapsedTime() { + return context.get(TRANSACTION_ELAPSED_TIME, DEFAULT_VALUE); + } + + /** + * Set the value for the data item with key "MetricBeginTimestamp". + * + * @param metricStartTime metric start time + */ + public void setMetricBeginTimestamp(Instant metricStartTime) { + SimpleDateFormat sdf = new SimpleDateFormat(TIME_FORMAT); + context.put(METRIC_BEGIN_TIME_STAMP, sdf.format(Date.from(metricStartTime))); + } + + /** + * Get the value for the data item with key "MetricBeginTimestamp". + * + * @return current value, or 0 if not set + */ + public long getMetricBeginTimestamp() { + return context.get(METRIC_BEGIN_TIME_STAMP, DEFAULT_VALUE); + } + + /** + * Set the value for the data item with key "MetricEndTimestamp". + * + * @param metricEndTime metric end time + */ + public void setMetricEndTimestamp(Instant metricEndTime) { + SimpleDateFormat sdf = new SimpleDateFormat(TIME_FORMAT); + context.put(METRIC_END_TIME_STAMP, sdf.format(Date.from(metricEndTime))); + } + + /** + * Get the value for the data item with key "MetricEndTimestamp". + * + * @return current value, or 0 if not set + */ + public long getMetricEndTimestamp() { + return context.get(METRIC_END_TIME_STAMP, DEFAULT_VALUE); + } + + /** + * Set the value for the data item with key "MetricElapsedTime". An alternative to calling this + * method directly is to call metricStarted() at the start of metric processing and + * metricEnded() at the end, which will compute the time difference in milliseconds + * and store the result as the "ns" value. + * + * @param metricEndTime metric end time + */ + + public void setMetricElapsedTime(Instant metricEndTime) { + long ns = Duration.between(metricStartTime, metricEndTime).toMillis(); + context.put(METRIC_ELAPSED_TIME, ns); + } + + /** + * Get the value for the data item with key "MetricElapsedTime". + * + * @return current value, or 0 if not set + */ + public long getMetricElapsedTime() { + return context.get(METRIC_ELAPSED_TIME, DEFAULT_VALUE); + } +} 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 new file mode 100644 index 00000000..dddd3c4d --- /dev/null +++ b/common-logging/src/main/java/org/onap/policy/common/logging/OnapLoggingUtils.java @@ -0,0 +1,62 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-Logging + * ================================================================================ + * Copyright (C) 2017-2019 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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.common.logging; + +import javax.servlet.http.HttpServletRequest; + +public class OnapLoggingUtils { + + 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 deleted file mode 100644 index 0752b188..00000000 --- a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/Configuration.java +++ /dev/null @@ -1,82 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP-Logging - * ================================================================================ - * 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. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -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. - */ - String BEGIN_TIME_STAMP = "BeginTimestamp"; - - /** - * The Date-time of the end of transaction. - */ - String END_TIME_STAMP = "EndTimestamp"; - - /** - * Externally advertised API invoked by clients of this component. - */ - String SERVICE_NAME = "ServiceName"; - - /** - * Client or user invoking the API. - */ - String PARTNER_NAME = "PartnerName"; - - String TARGET_ENTITY = "TargetEntity"; - - String TARGET_SERVICE_NAME = "TargetServiceName"; - - /** - * High level success or failure (COMPLETE or ERROR). - */ - String STATUS_CODE = "StatusCode"; - - /** - * Application specific response code. - */ - String RESPONSE_CODE = "ResponseCode"; - - /** - * Human readable description of the application specific response code. - */ - String RESPONSE_DESCRIPTION = "ResponseDescription"; - - /** - * Externally advertised API invoked by clients of this component. - */ - String ELAPSED_TIME = "ElapsedTime"; - - /** - * High level failure (ERROR). - */ - String ERROR_CATEGORY = "ErrorCategory"; - - String ERROR_CODE = "ErrorCode"; - - String ERROR_DESCRIPTION = "ErrorDescription"; - - String CLASS_NAME = "ClassName"; - - 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 deleted file mode 100644 index f5ab4c79..00000000 --- a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/DroolsPDPMDCInfo.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * ONAP-Logging - * ================================================================================ - * 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. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.logging.eelf; - -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -public class DroolsPDPMDCInfo implements MDCInfo { - - private static ConcurrentHashMap mdcMap = new ConcurrentHashMap<>(); - - static { - - mdcMap.put(Configuration.MDC_REMOTE_HOST, ""); - mdcMap.put(Configuration.MDC_SERVICE_NAME, "Policy.droolsPdp"); - mdcMap.put(Configuration.MDC_SERVICE_INSTANCE_ID, "Policy.droolsPdp.event"); - mdcMap.put(Configuration.MDC_INSTANCE_UUID, ""); - mdcMap.put(Configuration.MDC_ALERT_SEVERITY, ""); - mdcMap.put(Configuration.PARTNER_NAME, "N/A"); - mdcMap.put(Configuration.STATUS_CODE, "N/A"); - mdcMap.put(Configuration.RESPONSE_CODE, "N/A"); - mdcMap.put(Configuration.RESPONSE_DESCRIPTION, "N/A"); - } - - /** - * Get the MMDC Info. - * - * @return the instance of ConcurrentHashMap. - */ - @Override - public ConcurrentMap getMDCInfo() { - return mdcMap; - } -} 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 new file mode 100644 index 00000000..6086a642 --- /dev/null +++ b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/DroolsPdpMdcInfo.java @@ -0,0 +1,53 @@ +/* + * ============LICENSE_START======================================================= + * ONAP-Logging + * ================================================================================ + * Copyright (C) 2017-2019 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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.common.logging.eelf; + +import com.att.eelf.configuration.Configuration; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +public class DroolsPdpMdcInfo implements MdcInfo { + + private static ConcurrentHashMap mdcMap = new ConcurrentHashMap<>(); + + static { + + mdcMap.put(Configuration.MDC_REMOTE_HOST, ""); + mdcMap.put(Configuration.MDC_SERVICE_NAME, "Policy.droolsPdp"); + mdcMap.put(Configuration.MDC_SERVICE_INSTANCE_ID, "Policy.droolsPdp.event"); + mdcMap.put(Configuration.MDC_INSTANCE_UUID, ""); + mdcMap.put(Configuration.MDC_ALERT_SEVERITY, ""); + mdcMap.put(OnapConfigProperties.PARTNER_NAME, "N/A"); + mdcMap.put(OnapConfigProperties.STATUS_CODE, "N/A"); + mdcMap.put(OnapConfigProperties.RESPONSE_CODE, "N/A"); + mdcMap.put(OnapConfigProperties.RESPONSE_DESCRIPTION, "N/A"); + } + + /** + * Get the MMDC Info. + * + * @return the instance of ConcurrentHashMap. + */ + @Override + public ConcurrentMap getMdcInfo() { + return mdcMap; + } +} 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 a8d90ad7..1ed11344 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,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-Logging * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,10 +21,14 @@ package org.onap.policy.common.logging.eelf; import java.time.Instant; +import lombok.Getter; +import lombok.Setter; /** * EventData can be used for logging a rule event. */ +@Getter +@Setter public class EventData { private String requestId = null; @@ -40,7 +44,7 @@ public class EventData { /** * Create an instance. - * + * * @param requestId the request ID * @param startTime the start time * @param endTime the end time @@ -51,11 +55,11 @@ public class EventData { this.endTime = endTime; } - public String getRequestID() { + public String getRequestId() { return requestId; } - public void setRequestID(String requestId) { + public void setRequestId(String requestId) { this.requestId = requestId; } 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 46401e9e..71476c6a 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 @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-Logging * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -45,23 +45,23 @@ public class EventTrackInfo { /** * Returns an instance of EventData associated to this requestID. - * - * @param requestID request id + * + * @param requestId request id * @return EventData */ - public EventData getEventDataByRequestID(String requestID) { - return eventInfo.get(requestID); + public EventData getEventDataByRequestId(String requestId) { + return eventInfo.get(requestId); } /** * Stores an EventData object in a ConcurrentHashMap using its requestID as key. - * + * * @param event event data */ public void storeEventData(EventData event) { if (event != null) { - String id = event.getRequestID(); + String id = event.getRequestId(); if (id == null || id.isEmpty()) { return; } @@ -74,7 +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) { 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 5f97c365..4b5c57a8 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 @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-Logging * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. @@ -80,7 +80,7 @@ public class EventTrackInfoHandler extends TimerTask { } expiredEvents.add(entry.getKey()); - PolicyLogger.info(className + " add expired event request ID: " + event.getRequestID()); + PolicyLogger.info(className + " add expired event request ID: " + event.getRequestId()); } } 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 deleted file mode 100644 index f7832271..00000000 --- a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/MDCInfo.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * ONAP-Logging - * ================================================================================ - * 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. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.logging.eelf; - -import java.util.concurrent.ConcurrentMap; - -/** - * Interface needs to be implemented by DroolsPDPMDCInfo. - */ -@FunctionalInterface -public interface MDCInfo { - - /** - * Returns MDC info. - * - * @return MDC info - */ - ConcurrentMap getMDCInfo(); -} 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 new file mode 100644 index 00000000..59b8e8c3 --- /dev/null +++ b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/MdcInfo.java @@ -0,0 +1,37 @@ +/* + * ============LICENSE_START======================================================= + * ONAP-Logging + * ================================================================================ + * Copyright (C) 2017-2019 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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.common.logging.eelf; + +import java.util.concurrent.ConcurrentMap; + +/** + * Interface needs to be implemented by DroolsPDPMDCInfo. + */ +@FunctionalInterface +public interface MdcInfo { + + /** + * Returns MDC info. + * + * @return MDC info + */ + ConcurrentMap getMdcInfo(); +} diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/OnapConfigProperties.java b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/OnapConfigProperties.java new file mode 100644 index 00000000..8d2031db --- /dev/null +++ b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/OnapConfigProperties.java @@ -0,0 +1,87 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-Logging + * ================================================================================ + * 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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.common.logging.eelf; + + +public class OnapConfigProperties { + + /** + * The Date-time of the start of a transaction. + */ + public static final String BEGIN_TIME_STAMP = "BeginTimestamp"; + + /** + * The Date-time of the end of transaction. + */ + public static final String END_TIME_STAMP = "EndTimestamp"; + + /** + * Externally advertised API invoked by clients of this component. + */ + public static final String SERVICE_NAME = "ServiceName"; + + /** + * Client or user invoking the API. + */ + public static final String PARTNER_NAME = "PartnerName"; + + public static final String TARGET_ENTITY = "TargetEntity"; + + public static final String TARGET_SERVICE_NAME = "TargetServiceName"; + + /** + * High level success or failure (COMPLETE or ERROR). + */ + public static final String STATUS_CODE = "StatusCode"; + + /** + * Application specific response code. + */ + public static final String RESPONSE_CODE = "ResponseCode"; + + /** + * Human readable description of the application specific response code. + */ + public static final String RESPONSE_DESCRIPTION = "ResponseDescription"; + + /** + * Externally advertised API invoked by clients of this component. + */ + public static final String ELAPSED_TIME = "ElapsedTime"; + + /** + * High level failure (ERROR). + */ + public static final String ERROR_CATEGORY = "ErrorCategory"; + + public static final String ERROR_CODE = "ErrorCode"; + + public static final String ERROR_DESCRIPTION = "ErrorDescription"; + + public static final String CLASS_NAME = "ClassName"; + + public static final String SERVER_NAME = "ServerName"; + + + private OnapConfigProperties() { + // do nothing + } +} 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 87c4c571..cf0cfb3e 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 @@ -28,24 +28,24 @@ 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 static org.onap.policy.common.logging.eelf.OnapConfigProperties.BEGIN_TIME_STAMP; +import static org.onap.policy.common.logging.eelf.OnapConfigProperties.ELAPSED_TIME; +import static org.onap.policy.common.logging.eelf.OnapConfigProperties.END_TIME_STAMP; +import static org.onap.policy.common.logging.eelf.OnapConfigProperties.ERROR_CATEGORY; +import static org.onap.policy.common.logging.eelf.OnapConfigProperties.ERROR_CODE; +import static org.onap.policy.common.logging.eelf.OnapConfigProperties.ERROR_DESCRIPTION; +import static org.onap.policy.common.logging.eelf.OnapConfigProperties.PARTNER_NAME; +import static org.onap.policy.common.logging.eelf.OnapConfigProperties.RESPONSE_CODE; +import static org.onap.policy.common.logging.eelf.OnapConfigProperties.RESPONSE_DESCRIPTION; +import static org.onap.policy.common.logging.eelf.OnapConfigProperties.SERVER_NAME; +import static org.onap.policy.common.logging.eelf.OnapConfigProperties.STATUS_CODE; +import static org.onap.policy.common.logging.eelf.OnapConfigProperties.TARGET_ENTITY; +import static org.onap.policy.common.logging.eelf.OnapConfigProperties.TARGET_SERVICE_NAME; +import static org.onap.policy.common.logging.flexlogger.DisplayUtils.displayErrorMessage; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFLogger.Level; import com.att.eelf.configuration.EELFManager; - import java.io.PrintWriter; import java.io.StringWriter; import java.net.InetAddress; @@ -60,7 +60,8 @@ import java.util.Timer; import java.util.TimerTask; import java.util.UUID; import java.util.concurrent.ConcurrentMap; - +import java.util.function.Consumer; +import org.apache.commons.lang3.StringUtils; import org.onap.policy.common.logging.flexlogger.LoggerType; import org.slf4j.MDC; @@ -246,7 +247,7 @@ public class PolicyLogger { * @param transId the transaction ID * @return String */ - public static String postMDCInfoForEvent(String transId) { + public static String postMdcInfoForEvent(String transId) { MDC.clear(); String transactionId = transId; @@ -258,7 +259,7 @@ public class PolicyLogger { if ("DROOLS".equalsIgnoreCase(component)) { MDC.put(TARGET_ENTITY, "POLICY"); MDC.put(TARGET_SERVICE_NAME, "drools evaluate rule"); - return postMDCInfoForEvent(transactionId, new DroolsPDPMDCInfo()); + return postMdcInfoForEvent(transactionId, new DroolsPdpMdcInfo()); } else { // For Xacml MDC.put(TARGET_ENTITY, "POLICY"); @@ -269,38 +270,11 @@ public class PolicyLogger { 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"); + setMdcHostInfo(); + seTimeStamps(); return transactionId; - } /** @@ -310,12 +284,12 @@ public class PolicyLogger { * @param mdcInfo the MDC info * @return String */ - private static String postMDCInfoForEvent(String transId, MDCInfo mdcInfo) { + private static String postMdcInfoForEvent(String transId, MdcInfo mdcInfo) { MDC.put(MDC_KEY_REQUEST_ID, transId); - if (mdcInfo != null && mdcInfo.getMDCInfo() != null && !mdcInfo.getMDCInfo().isEmpty()) { + if (mdcInfo != null && mdcInfo.getMdcInfo() != null && !mdcInfo.getMdcInfo().isEmpty()) { - ConcurrentMap mdcMap = mdcInfo.getMDCInfo(); + ConcurrentMap mdcMap = mdcInfo.getMdcInfo(); Iterator keyIterator = mdcMap.keySet().iterator(); String key; @@ -325,24 +299,12 @@ public class PolicyLogger { } } - 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); - } + setMdcHostInfo(); + 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())); + seTimeStamps(startTime, endTime); return transId; } @@ -352,8 +314,17 @@ public class PolicyLogger { * * @param eventObject event object */ - public static void postMDCInfoForEvent(Object eventObject) { - postMDCInfoForEvent("" + eventObject); + public static void postMdcInfoForEvent(Object eventObject) { + postMdcInfoForEvent("" + eventObject); + } + + private static void setMdcHostInfo() { + 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); + } } /** @@ -364,18 +335,10 @@ public class PolicyLogger { 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())); + seTimeStamps(startTime, endTime); MDC.put(PARTNER_NAME, "N/A"); @@ -385,6 +348,18 @@ public class PolicyLogger { } + private static void seTimeStamps(Instant startTime, Instant endTime) { + 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())); + } + /** * Sets transaction Id to MDC. * @@ -411,7 +386,7 @@ public class PolicyLogger { * @param transId the transaction ID * @return String */ - public static String postMDCInfoForTriggeredRule(String transId) { + public static String postMdcInfoForTriggeredRule(String transId) { String transactionId = transId; @@ -424,12 +399,7 @@ public class PolicyLogger { 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); - } + setMdcHostInfo(); MDC.put(MDC_INSTANCE_UUID, ""); MDC.put(MDC_ALERT_SEVERITY, ""); MDC.put(STATUS_CODE, COMPLETE_STATUS); @@ -443,9 +413,9 @@ public class PolicyLogger { * * @param obj object */ - public static void postMDCUUIDForTriggeredRule(Object obj) { + public static void postMdcUuidForTriggeredRule(Object obj) { - postMDCInfoForTriggeredRule("" + obj); + postMdcInfoForTriggeredRule("" + obj); } @@ -864,13 +834,13 @@ public class PolicyLogger { public static void recordAuditEventStart(String eventId) { MDC.put(STATUS_CODE, COMPLETE_STATUS); - postMDCInfoForEvent(eventId); + postMdcInfoForEvent(eventId); if (eventTracker == null) { eventTracker = new EventTrackInfo(); } EventData event = new EventData(); - event.setRequestID(eventId); + event.setRequestId(eventId); event.setStartTime(Instant.now()); eventTracker.storeEventData(event); MDC.put(MDC_KEY_REQUEST_ID, eventId); @@ -1002,7 +972,7 @@ public class PolicyLogger { return; } - EventData event = eventTracker.getEventDataByRequestID(eventId); + EventData event = eventTracker.getEventDataByRequestId(eventId); if (event != null) { Instant endTime = event.getEndTime(); @@ -1030,7 +1000,7 @@ public class PolicyLogger { return; } - EventData event = eventTracker.getEventDataByRequestID(eventId.toString()); + EventData event = eventTracker.getEventDataByRequestId(eventId.toString()); if (event != null) { Instant endTime = event.getEndTime(); @@ -1065,27 +1035,18 @@ public class PolicyLogger { 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); + seTimeStamps(startTime, endTime); 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) { + if (eventTracker != null && eventTracker.getEventDataByRequestId(eventId) != null) { eventTracker.remove(eventId); debugLogger.info("eventTracker.remove(" + eventId + ")"); @@ -1258,227 +1219,124 @@ public class PolicyLogger { */ 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; + Properties loggerProperties = getLoggerProperties(properties); // fetch and verify definitions of some properties try { + setOverrideLogbackLevels(loggerProperties); - 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)); + setLoggerLevel(loggerProperties, "debugLogger.level", "INFO", PolicyLogger::setDebugLevel); - } - // 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 on or off + setLoggerOnOff(loggerProperties, "metricsLogger.level", PolicyLogger::setMetricsLevel); + setLoggerOnOff(loggerProperties, "audit.level", PolicyLogger::setAuditLevel); + setLoggerOnOff(loggerProperties, "error.level", PolicyLogger::setErrorLevel); - } - // 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); + timerDelayTime = getIntProp(loggerProperties, "timer.delay.time", timerDelayTime); + checkInterval = getIntProp(loggerProperties, "check.interval", checkInterval); + expiredTime = getIntProp(loggerProperties, "event.expired.time", expiredTime); + concurrentHashMapLimit = getIntProp(loggerProperties, "concurrentHashMap.limit", concurrentHashMapLimit); + stopCheckPoint = getIntProp(loggerProperties, "stop.check.point", stopCheckPoint); + component = loggerProperties.getProperty("policy.component", "DROOLS"); 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); - } + return detmLoggerType(loggerProperties); - if (checkIntervalProp > 0) { + } catch (Exception e) { + MDC.put(ERROR_CATEGORY, ERROR_CATEGORY_VALUE); - checkInterval = checkIntervalProp; + 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()); - } 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); } + errorLogger.error("failed to get the policyLogger.properties, so use their default values", e); - 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); - } + return LoggerType.EELF; + } - if (concurrentHashMapLimitProp > 0) { + } - concurrentHashMapLimit = concurrentHashMapLimitProp; + private static int getIntProp(Properties properties, String propName, int defaultValue) { + final int propValue = Integer.parseInt(properties.getProperty(propName, String.valueOf(defaultValue))); - } 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); - } + debugLogger.info(propName + " value: " + propValue); - if (stopCheckPointProp > 0) { + if (propValue > 0) { + return propValue; - 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()); - } 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); } + errorLogger.error("failed to get the " + propName + ", so use its default value: " + defaultValue); + return defaultValue; + } + } - 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; + private static Properties getLoggerProperties(Properties properties) { + if (properties != null) { + return properties; + } else { + displayErrorMessage("PolicyLogger cannot find its configuration - continue"); + return new Properties(); + } + } - } + private static void setLoggerLevel(Properties properties, String propName, String defaultValue, + Consumer setter) { - } + final String propValue = properties.getProperty(propName, defaultValue); - if (debugLevelProp != null && !debugLevelProp.isEmpty()) { + if (!StringUtils.isBlank(propValue)) { + debugLogger.info(propName + " level: " + propValue); + } - debugLevel = Level.valueOf(debugLevelProp); + setter.accept(propValue); + } - } - // Only check if it is to turn off or not - if (errorLevelProp != null && errorLevelProp.equalsIgnoreCase(Level.OFF.toString())) { + private static void setLoggerOnOff(Properties properties, String propName, Consumer setter) { + final String propValue = properties.getProperty(propName, "ON"); - errorLevel = Level.valueOf(errorLevelProp); + if (Level.OFF.toString().equalsIgnoreCase(propValue)) { + debugLogger.info(propName + " level: " + propValue); + } - } - // Only check if it is to turn off or not - if (metricsLevelProp != null && metricsLevelProp.equalsIgnoreCase(Level.OFF.toString())) { + setter.accept(propValue); + } - metricsLevel = Level.valueOf(metricsLevelProp); + private static void setOverrideLogbackLevels(Properties loggerProperties) { + final String overrideLogbackLevel = loggerProperties.getProperty("override.logback.level.setup"); - } - // Only check if it is to turn off or not - if (auditLevelProp != null && auditLevelProp.equalsIgnoreCase(Level.OFF.toString())) { + if (!StringUtils.isBlank(overrideLogbackLevel)) { + isOverrideLogbackLevel = "TRUE".equalsIgnoreCase(overrideLogbackLevel); + } + } - auditLevel = Level.valueOf(auditLevelProp); + private static LoggerType detmLoggerType(Properties loggerProperties) { + final String loggerTypeProp = loggerProperties.getProperty("logger.type", LoggerType.EELF.toString()); + debugLogger.info("loggerType value: " + loggerTypeProp); - } + switch (loggerTypeProp.toUpperCase()) { + case "EELF": + return LoggerType.EELF; - } catch (Exception e) { - MDC.put(ERROR_CATEGORY, ERROR_CATEGORY_VALUE); + case "LOG4J": + return LoggerType.LOG4J; - 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()); + case "SYSTEMOUT": + return LoggerType.SYSTEMOUT; - } - errorLogger.error("failed to get the policyLogger.properties, so use their default values", e); + default: + return LoggerType.EELF; } - - return loggerType; - } @@ -1505,5 +1363,4 @@ public class PolicyLogger { 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/DisplayUtils.java b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/DisplayUtils.java new file mode 100644 index 00000000..dc740440 --- /dev/null +++ b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/DisplayUtils.java @@ -0,0 +1,41 @@ +/* + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2019 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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.common.logging.flexlogger; + +/** + * Utilities to display messages. These are generally used while logging is being + * configured, or when logging being directed to System.out. As a result, it directly + * writes to System.out rather than to a logger. + */ +public class DisplayUtils { + + private DisplayUtils() { + // do nothing + } + + public static void displayMessage(Object message) { + System.out.println(message); + } + + public static void displayErrorMessage(Object msg) { + System.err.println(msg); + } +} 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 e0c4144b..a3e5cc8f 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 @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-Logging * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -40,31 +40,31 @@ public class EelfLogger implements Logger, Serializable { /** * Constructor. - * + * * @param clazz the class */ public EelfLogger(Class clazz) { if (clazz != null) { className = clazz.getName(); } - PolicyLogger.postMDCInfoForEvent(null); + PolicyLogger.postMdcInfoForEvent(null); } /** * Constructor. - * + * * @param className the class name */ public EelfLogger(String className) { if (className != null) { this.className = className; } - PolicyLogger.postMDCInfoForEvent(null); + PolicyLogger.postMdcInfoForEvent(null); } /** * Constructor. - * + * * @param clazz the class * @param isNewTransaction is a new transaction */ @@ -73,7 +73,7 @@ public class EelfLogger implements Logger, Serializable { className = clazz.getName(); } if (isNewTransaction) { - transId = PolicyLogger.postMDCInfoForEvent(null); + transId = PolicyLogger.postMdcInfoForEvent(null); } else { transId = PolicyLogger.getTransId(); } @@ -81,7 +81,7 @@ public class EelfLogger implements Logger, Serializable { /** * Constructor. - * + * * @param className the class name * @param isNewTransaction is a new transaction */ @@ -90,7 +90,7 @@ public class EelfLogger implements Logger, Serializable { this.className = className; } if (isNewTransaction) { - transId = PolicyLogger.postMDCInfoForEvent(null); + transId = PolicyLogger.postMdcInfoForEvent(null); } else { transId = PolicyLogger.getTransId(); } @@ -98,7 +98,7 @@ public class EelfLogger implements Logger, Serializable { /** * Constructor. - * + * * @param clazz the class * @param transId the transaction ID */ @@ -106,13 +106,13 @@ public class EelfLogger implements Logger, Serializable { if (clazz != null) { className = clazz.getName(); } - PolicyLogger.postMDCInfoForEvent(transId); + PolicyLogger.postMdcInfoForEvent(transId); this.transId = transId; } /** * Constructor. - * + * * @param className the class name * @param transId the transaction ID */ @@ -120,13 +120,13 @@ public class EelfLogger implements Logger, Serializable { if (className != null) { this.className = className; } - PolicyLogger.postMDCInfoForEvent(transId); + PolicyLogger.postMdcInfoForEvent(transId); this.transId = transId; } /** * Sets transaction Id for logging. - * + * * @param transId the transaction ID */ @Override @@ -146,7 +146,7 @@ public class EelfLogger implements Logger, Serializable { /** * Records a message. - * + * * @param message the message */ @Override @@ -156,7 +156,7 @@ public class EelfLogger implements Logger, Serializable { /** * Records a message. - * + * * @param message the message * @param throwable the throwable */ @@ -167,7 +167,7 @@ public class EelfLogger implements Logger, Serializable { /** * Records an error message. - * + * * @param message the message */ @Override @@ -177,7 +177,7 @@ public class EelfLogger implements Logger, Serializable { /** * Records an error message. - * + * * @param message the message * @param throwable the throwable */ @@ -188,7 +188,7 @@ public class EelfLogger implements Logger, Serializable { /** * Records an error message. - * + * * @param msg the message code * @param throwable the throwable * @param arguments the messages @@ -200,7 +200,7 @@ public class EelfLogger implements Logger, Serializable { /** * Records an error message. - * + * * @param msg the message code * @param arguments the messages */ @@ -211,7 +211,7 @@ public class EelfLogger implements Logger, Serializable { /** * Records a message. - * + * * @param message the message */ @Override @@ -221,7 +221,7 @@ public class EelfLogger implements Logger, Serializable { /** * Records a message. - * + * * @param message the message * @param throwable the throwable */ @@ -232,7 +232,7 @@ public class EelfLogger implements Logger, Serializable { /** * Records a message. - * + * * @param message the message */ @Override @@ -242,7 +242,7 @@ public class EelfLogger implements Logger, Serializable { /** * Records a message. - * + * * @param message the message * @param throwable the throwable */ @@ -253,7 +253,7 @@ public class EelfLogger implements Logger, Serializable { /** * Records a message. - * + * * @param msg the message codes * @param arguments the messages */ @@ -264,7 +264,7 @@ public class EelfLogger implements Logger, Serializable { /** * Records a message. - * + * * @param msg the message * @param throwable the throwable * @param arguments the messages @@ -276,7 +276,7 @@ public class EelfLogger implements Logger, Serializable { /** * Records a message. - * + * * @param message the message */ @Override @@ -286,7 +286,7 @@ public class EelfLogger implements Logger, Serializable { /** * Records a message. - * + * * @param message the message * @param throwable the throwable */ @@ -297,7 +297,7 @@ public class EelfLogger implements Logger, Serializable { /** * Returns true for debug enabled, or false for not. - * + * * @return boolean */ @Override @@ -307,7 +307,7 @@ public class EelfLogger implements Logger, Serializable { /** * Returns true for info enabled, or false for not. - * + * * @return boolean */ @Override @@ -317,7 +317,7 @@ public class EelfLogger implements Logger, Serializable { /** * Returns true for warn enabled, or false for not. - * + * * @return boolean */ @Override @@ -327,7 +327,7 @@ public class EelfLogger implements Logger, Serializable { /** * Returns true for error enabled, or false for not. - * + * * @return boolean */ @Override @@ -337,7 +337,7 @@ public class EelfLogger implements Logger, Serializable { /** * Returns true for audit enabled, or false for not. - * + * * @return boolean */ @Override @@ -347,7 +347,7 @@ public class EelfLogger implements Logger, Serializable { /** * Returns true for metrics enabled, or false for not. - * + * * @return boolean */ @Override @@ -357,7 +357,7 @@ public class EelfLogger implements Logger, Serializable { /** * Returns true for trace enabled, or false for not. - * + * * @return boolean */ @Override @@ -367,7 +367,7 @@ public class EelfLogger implements Logger, Serializable { /** * Records an audit message. - * + * * @param arg0 the message */ @Override @@ -377,7 +377,7 @@ public class EelfLogger implements Logger, Serializable { /** * Records an audit message. - * + * * @param message the message * @param throwable the throwable */ @@ -388,7 +388,7 @@ public class EelfLogger implements Logger, Serializable { /** * Records an audit message. - * + * * @param eventId the event ID */ @Override @@ -398,7 +398,7 @@ public class EelfLogger implements Logger, Serializable { /** * Records an audit message. - * + * * @param eventId the event ID */ @Override @@ -408,7 +408,7 @@ public class EelfLogger implements Logger, Serializable { /** * Records an audit message. - * + * * @param eventId the event ID * @param rule the rule * @param policyVersion the policy cersion @@ -420,7 +420,7 @@ public class EelfLogger implements Logger, Serializable { /** * Records an audit message. - * + * * @param eventId the event ID * @param rule the rule * @param policyVersion the policy version @@ -432,7 +432,7 @@ public class EelfLogger implements Logger, Serializable { /** * Records an audit message. - * + * * @param eventId the event ID * @param rule the rule */ @@ -443,7 +443,7 @@ public class EelfLogger implements Logger, Serializable { /** * Records an audit message. - * + * * @param eventId the event ID * @param rule the rule */ @@ -454,7 +454,7 @@ public class EelfLogger implements Logger, Serializable { /** * Records a metrics message. - * + * * @param eventId the event ID * @param message the message */ @@ -465,7 +465,7 @@ public class EelfLogger implements Logger, Serializable { /** * Records a metrics message. - * + * * @param eventId the event ID * @param message the message */ @@ -476,7 +476,7 @@ public class EelfLogger implements Logger, Serializable { /** * Records a metrics message. - * + * * @param message the message */ @Override @@ -486,32 +486,32 @@ public class EelfLogger implements Logger, Serializable { /** * Populates MDC Info. - * + * * @param transId the transaction ID */ @Override - public String postMDCInfoForEvent(String transId) { - return PolicyLogger.postMDCInfoForEvent(transId); + 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); + 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); + 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 90240a77..030363dc 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,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-Logging * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,6 +20,8 @@ package org.onap.policy.common.logging.flexlogger; +import static org.onap.policy.common.logging.flexlogger.DisplayUtils.displayMessage; + import java.io.IOException; import java.text.SimpleDateFormat; import java.time.Instant; @@ -49,12 +51,12 @@ public class FlexLogger extends SecurityManager { /** * 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); + displayMessage(GET_LOGGER_PREFIX + loggerType); switch (loggerType) { case EELF: @@ -75,12 +77,12 @@ public class FlexLogger extends SecurityManager { /** * 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); + displayMessage(GET_LOGGER_PREFIX + loggerType); switch (loggerType) { case EELF: @@ -101,13 +103,13 @@ public class FlexLogger extends SecurityManager { /** * 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); + displayMessage(GET_LOGGER_PREFIX + loggerType); switch (loggerType) { case EELF: @@ -128,13 +130,13 @@ public class FlexLogger extends SecurityManager { /** * 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); + displayMessage(GET_LOGGER_PREFIX + loggerType); switch (loggerType) { case EELF: @@ -156,7 +158,7 @@ public class FlexLogger extends SecurityManager { * Returns the calling class name. */ public String getClassName() { - System.out.println("getClassContext()[3].getName() " + getClassContext()[3].getName()); + displayMessage("getClassContext()[3].getName() " + getClassContext()[3].getName()); return getClassContext()[3].getName(); } @@ -177,7 +179,7 @@ public class FlexLogger extends SecurityManager { /** * Returns an instance of Logger4J. - * + * * @param name the name of the logger */ private static Logger4J getLog4JLogger(String name) { @@ -193,7 +195,7 @@ public class FlexLogger extends SecurityManager { /** * Returns an instance of EelfLogger. - * + * * @param clazz the class * @param isNewTransaction is a new transaction */ @@ -218,11 +220,11 @@ public class FlexLogger extends SecurityManager { } // installl already created but it is new transaction if (isNewTransaction) { - String transId = PolicyLogger.postMDCInfoForEvent(null); + String transId = PolicyLogger.postMdcInfoForEvent(null); logger.setTransId(transId); } } - System.out.println("eelfLoggerMap size : " + eelfLoggerMap.size() + " class name: " + className); + displayMessage("eelfLoggerMap size : " + eelfLoggerMap.size() + " class name: " + className); return logger; } @@ -246,37 +248,24 @@ public class FlexLogger extends SecurityManager { */ 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); + displayMessage("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); + String overrideLogbackLevel = properties.getProperty("override.logback.level.setup"); + displayMessage("FlexLogger:overrideLogbackLevel => " + overrideLogbackLevel); + String loggerTypeString = properties.getProperty("logger.type"); + if ("EELF".equalsIgnoreCase(loggerTypeString) && "TRUE".equalsIgnoreCase(overrideLogbackLevel)) { + displayMessage("FlexLogger: start listener."); + properties = PropertyUtil.getProperties("config/policyLogger.properties", + new PropertiesCallBack("FlexLogger-CallBack")); } } } catch (IOException e1) { - System.out.println("initlogger" + e1); + displayMessage("initlogger" + e1); } finally { // OK to pass no properties (null) loggerType = PolicyLogger.init(properties); @@ -309,8 +298,8 @@ public class FlexLogger extends SecurityManager { 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); + displayMessage("FlexLogger.propertiesChanged : called at time : " + formatedTime); + displayMessage("FlexLogger.propertiesChanged : debugLevel : " + debugLevel); if (changedKeys != null) { @@ -332,5 +321,4 @@ public class FlexLogger extends SecurityManager { } } } - } 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 f74aca14..d6f020e0 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,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-Logging * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -195,12 +195,12 @@ public interface Logger { /** * Populates MDC info. */ - public String postMDCInfoForEvent(String transId); + public String postMdcInfoForEvent(String transId); /** * Populates MDC Info. */ - public void postMDCInfoForEvent(Object obj); + public void postMdcInfoForEvent(Object obj); /** * Sets transaction Id. @@ -215,6 +215,6 @@ public interface Logger { /** * Populates MDC Info for the rule triggered. */ - public void postMDCInfoForTriggeredRule(String transId); + 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 88d3800a..8802d17e 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 @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-Logging * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,6 +20,8 @@ package org.onap.policy.common.logging.flexlogger; +import static org.onap.policy.common.logging.flexlogger.DisplayUtils.displayMessage; + import com.att.eelf.configuration.EELFLogger.Level; import java.io.IOException; @@ -47,11 +49,11 @@ public class Logger4J implements org.onap.policy.common.logging.flexlogger.Logge /** * Constructor. - * + * * @param clazz the class */ public Logger4J(Class clazz) { - System.out.println("create instance of Logger4J"); + displayMessage("create instance of Logger4J"); if (clazz != null) { log = Logger.getLogger(clazz); className = clazz.getName(); @@ -60,12 +62,12 @@ public class Logger4J implements org.onap.policy.common.logging.flexlogger.Logge /** * 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"); + displayMessage("create instance of Logger4J"); if (name != null) { log = Logger.getLogger(name); } @@ -91,7 +93,7 @@ public class Logger4J implements org.onap.policy.common.logging.flexlogger.Logge /** * Records a message. - * + * * @param message the message */ @Override @@ -103,7 +105,7 @@ public class Logger4J implements org.onap.policy.common.logging.flexlogger.Logge /** * Records a message. - * + * * @param message the message * @param throwable the throwable */ @@ -114,7 +116,7 @@ public class Logger4J implements org.onap.policy.common.logging.flexlogger.Logge /** * Records an error message. - * + * * @param message the message */ @Override @@ -124,7 +126,7 @@ public class Logger4J implements org.onap.policy.common.logging.flexlogger.Logge /** * Records an error message. - * + * * @param message the message * @param throwable the throwable */ @@ -135,7 +137,7 @@ public class Logger4J implements org.onap.policy.common.logging.flexlogger.Logge /** * Records an error message. - * + * * @param msg the message code * @param throwable the throwable * @param arguments the messages @@ -148,7 +150,7 @@ public class Logger4J implements org.onap.policy.common.logging.flexlogger.Logge /** * Records an error message. - * + * * @param msg the message code * @param arguments the messages */ @@ -159,7 +161,7 @@ public class Logger4J implements org.onap.policy.common.logging.flexlogger.Logge /** * Records a message. - * + * * @param message the message */ @Override @@ -169,7 +171,7 @@ public class Logger4J implements org.onap.policy.common.logging.flexlogger.Logge /** * Records a message. - * + * * @param message the message * @param throwable the throwable */ @@ -180,7 +182,7 @@ public class Logger4J implements org.onap.policy.common.logging.flexlogger.Logge /** * Records a message. - * + * * @param message the message */ @Override @@ -190,7 +192,7 @@ public class Logger4J implements org.onap.policy.common.logging.flexlogger.Logge /** * Records a message. - * + * * @param message the message * @param throwable the throwable */ @@ -201,7 +203,7 @@ public class Logger4J implements org.onap.policy.common.logging.flexlogger.Logge /** * Records a message. - * + * * @param msg the message code * @param arguments the messages */ @@ -212,7 +214,7 @@ public class Logger4J implements org.onap.policy.common.logging.flexlogger.Logge /** * Records a message. - * + * * @param msg the message code * @param throwable the throwable * @param arguments the messages @@ -224,7 +226,7 @@ public class Logger4J implements org.onap.policy.common.logging.flexlogger.Logge /** * Records a message. - * + * * @param message the message */ @Override @@ -234,7 +236,7 @@ public class Logger4J implements org.onap.policy.common.logging.flexlogger.Logge /** * Records a message. - * + * * @param message the message * @param throwable the throwable */ @@ -245,7 +247,7 @@ public class Logger4J implements org.onap.policy.common.logging.flexlogger.Logge /** * Returns true for debug enabled, or false for not. - * + * * @return boolean */ @Override @@ -255,7 +257,7 @@ public class Logger4J implements org.onap.policy.common.logging.flexlogger.Logge /** * Returns true for error enabled, or false for not. - * + * * @return boolean */ @SuppressWarnings("deprecation") @@ -266,7 +268,7 @@ public class Logger4J implements org.onap.policy.common.logging.flexlogger.Logge /** * Returns true for info enabled, or false for not. - * + * * @return boolean */ @Override @@ -276,7 +278,7 @@ public class Logger4J implements org.onap.policy.common.logging.flexlogger.Logge /** * Returns true for warn enabled, or false for not. - * + * * @return boolean */ @SuppressWarnings("deprecation") @@ -288,7 +290,7 @@ public class Logger4J implements org.onap.policy.common.logging.flexlogger.Logge /** * Returns true for audit enabled, or false for not. - * + * * @return boolean */ @Override @@ -298,7 +300,7 @@ public class Logger4J implements org.onap.policy.common.logging.flexlogger.Logge /** * Returns true for metrics enabled, or false for not. - * + * * @return boolean */ @Override @@ -308,7 +310,7 @@ public class Logger4J implements org.onap.policy.common.logging.flexlogger.Logge /** * Records an audit message. - * + * * @param message the message */ @Override @@ -318,7 +320,7 @@ public class Logger4J implements org.onap.policy.common.logging.flexlogger.Logge /** * Records an audit message. - * + * * @param message the message * @param throwable the throwable */ @@ -330,7 +332,7 @@ public class Logger4J implements org.onap.policy.common.logging.flexlogger.Logge /** * Records an audit message. - * + * * @param eventId the event ID */ @Override @@ -340,7 +342,7 @@ public class Logger4J implements org.onap.policy.common.logging.flexlogger.Logge /** * Records an audit message. - * + * * @param eventId the event ID */ @Override @@ -352,7 +354,7 @@ public class Logger4J implements org.onap.policy.common.logging.flexlogger.Logge /** * Records an audit message. - * + * * @param eventId the event ID * @param rule the rule * @param policyVersion the policy version @@ -364,7 +366,7 @@ public class Logger4J implements org.onap.policy.common.logging.flexlogger.Logge /** * Records an audit message. - * + * * @param eventId the event ID * @param rule the rule * @param policyVersion the policy version @@ -380,7 +382,7 @@ public class Logger4J implements org.onap.policy.common.logging.flexlogger.Logge /** * Records an audit message. - * + * * @param eventId the event ID * @param rule the rule */ @@ -391,7 +393,7 @@ public class Logger4J implements org.onap.policy.common.logging.flexlogger.Logge /** * Records an audit message. - * + * * @param eventId the event ID * @param rule the rule */ @@ -406,7 +408,7 @@ public class Logger4J implements org.onap.policy.common.logging.flexlogger.Logge /** * Records a metrics message. - * + * * @param eventId the event ID * @param message the message */ @@ -418,7 +420,7 @@ public class Logger4J implements org.onap.policy.common.logging.flexlogger.Logge /** * Records a metrics message. - * + * * @param eventId the event ID * @param message the message */ @@ -433,7 +435,7 @@ public class Logger4J implements org.onap.policy.common.logging.flexlogger.Logge /** * Records a metrics message. - * + * * @param message the message */ @Override @@ -443,11 +445,11 @@ public class Logger4J implements org.onap.policy.common.logging.flexlogger.Logge /** * Returns transaction Id. - * + * * @param transId the transaction ID */ @Override - public String postMDCInfoForEvent(String transId) { + public String postMdcInfoForEvent(String transId) { String transactionId = transId; if (transactionId == null || transactionId.isEmpty()) { transactionId = UUID.randomUUID().toString(); @@ -458,17 +460,17 @@ public class Logger4J implements org.onap.policy.common.logging.flexlogger.Logge /** * Records transaction Id. - * + * * @param message the message */ @Override - public void postMDCInfoForEvent(Object message) { + public void postMdcInfoForEvent(Object message) { log.info(message); } /** * Returns true for trace enabled, or false for not. - * + * * @return boolean */ @Override @@ -478,11 +480,11 @@ public class Logger4J implements org.onap.policy.common.logging.flexlogger.Logge /** * Records transaction Id. - * + * * @param transId the transaction ID */ @Override - public void postMDCInfoForTriggeredRule(String transId) { + public void postMdcInfoForTriggeredRule(String transId) { log.info(transId); } 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 9d9165ef..38759bc2 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,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-Logging * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,6 +20,8 @@ package org.onap.policy.common.logging.flexlogger; +import static org.onap.policy.common.logging.flexlogger.DisplayUtils.displayErrorMessage; + import java.io.File; import java.io.FileInputStream; import java.io.IOException; @@ -36,7 +38,7 @@ import java.util.TimerTask; * notifications of future changes. */ public class PropertyUtil { - + protected static class LazyHolder { /** * Timer thread. Will not be allocated by the JVM until it is first referenced. @@ -50,7 +52,7 @@ public class PropertyUtil { /** * 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 @@ -74,7 +76,7 @@ public class PropertyUtil { /** * 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 @@ -94,7 +96,7 @@ public class PropertyUtil { 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 @@ -150,7 +152,7 @@ public class PropertyUtil { try { poll(); } catch (Exception e) { - System.err.println(e); + displayErrorMessage(e); } } }; @@ -159,7 +161,7 @@ public class PropertyUtil { /** * 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 */ @@ -170,7 +172,7 @@ public class PropertyUtil { /** * Remove a listener from the notification list. - * + * * @param listener this is the listener to remove */ synchronized void removeListener(Listener listener) { @@ -190,7 +192,7 @@ public class PropertyUtil { /** * 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 { @@ -308,7 +310,7 @@ public class PropertyUtil { /** * 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 @@ -325,7 +327,7 @@ public class PropertyUtil { /** * 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 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 70ad08ae..f7a68a3d 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 @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-Logging * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,6 +20,8 @@ package org.onap.policy.common.logging.flexlogger; +import static org.onap.policy.common.logging.flexlogger.DisplayUtils.displayMessage; + import com.att.eelf.configuration.EELFLogger.Level; import java.io.Serializable; @@ -46,11 +48,11 @@ public class SystemOutLogger implements Logger, Serializable { /** * Constructor. - * + * * @param clazz the class */ public SystemOutLogger(Class clazz) { - System.out.println("create instance of SystemOutLogger"); + displayMessage("create instance of SystemOutLogger"); if (clazz != null) { className = clazz.getName(); } @@ -59,11 +61,11 @@ public class SystemOutLogger implements Logger, Serializable { /** * Constructor. - * + * * @param className the class name */ public SystemOutLogger(String className) { - System.out.println("create instance of SystemOutLogger"); + displayMessage("create instance of SystemOutLogger"); if (className != null) { this.className = className; } @@ -114,7 +116,7 @@ public class SystemOutLogger implements Logger, Serializable { @Override public void setTransId(String transId) { - System.out.println(transId); + displayMessage(transId); this.transId = transId; } @@ -129,129 +131,129 @@ public class SystemOutLogger implements Logger, Serializable { /** * Records a message. - * + * * @param message the message */ @Override public void debug(Object message) { - System.out.println(transId + "|" + className + " : " + message); + displayMessage(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); + displayMessage(transId + "|" + className + " : " + message + ":" + throwable); } /** * Records an error message. - * + * * @param message the message */ @Override public void error(Object message) { - System.out.println(transId + "|" + className + " : " + message); + displayMessage(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); + displayMessage(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)); + displayMessage(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)); + displayMessage(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); + displayMessage(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); + displayMessage(transId + "|" + className + " : " + message + ":" + throwable); } /** * Records a message. - * + * * @param message the message */ @Override public void warn(Object message) { - System.out.println(transId + "|" + className + " : " + message); + displayMessage(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); + displayMessage(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)); + displayMessage(transId + "|" + className + " : " + "MessageCodes:" + msg + Arrays.asList(arguments)); } /** * Records a message. - * + * * @param msg the message code * @param throwable the throwable * @param arguments the messages @@ -259,34 +261,34 @@ public class SystemOutLogger implements Logger, Serializable { @Override public void warn(MessageCodes msg, Throwable throwable, String... arguments) { - System.out.println(transId + "|" + className + " : " + "MessageCodes:" + msg + Arrays.asList(arguments)); + displayMessage(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); + displayMessage(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); + displayMessage(transId + "|" + className + " : " + message + ":" + throwable); } /** * Returns true for debug enabled, or false for not. - * + * * @return boolean */ @Override @@ -296,7 +298,7 @@ public class SystemOutLogger implements Logger, Serializable { /** * Returns true for warn enabled, or false for not. - * + * * @return boolean */ @Override @@ -306,7 +308,7 @@ public class SystemOutLogger implements Logger, Serializable { /** * Returns true for info enabled, or false for not. - * + * * @return boolean */ @Override @@ -316,7 +318,7 @@ public class SystemOutLogger implements Logger, Serializable { /** * Returns true for error enabled, or false for not. - * + * * @return boolean */ @Override @@ -326,7 +328,7 @@ public class SystemOutLogger implements Logger, Serializable { /** * Returns true for audit enabled, or false for not. - * + * * @return boolean */ @Override @@ -337,7 +339,7 @@ public class SystemOutLogger implements Logger, Serializable { /** * Returns true for metrics enabled, or false for not. - * + * * @return boolean */ @Override @@ -348,52 +350,52 @@ public class SystemOutLogger implements Logger, Serializable { /** * Records an audit message. - * + * * @param message the message */ @Override public void audit(Object message) { - System.out.println(transId + "|" + className + " : " + message); + displayMessage(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); + displayMessage(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); + displayMessage(transId + "|" + className + " : " + eventId); } /** * Records an audit message. - * + * * @param eventId the event ID */ @Override public void recordAuditEventStart(UUID eventId) { - System.out.println(eventId); + displayMessage(eventId); } /** * Records an audit message. - * + * * @param eventId the event ID * @param rule the rule * @param policyVersion the policy version @@ -401,12 +403,12 @@ public class SystemOutLogger implements Logger, Serializable { @Override public void recordAuditEventEnd(String eventId, String rule, String policyVersion) { - System.out.println(className + " : " + eventId + ":" + rule + ":" + policyVersion); + displayMessage(className + " : " + eventId + ":" + rule + ":" + policyVersion); } /** * Records an audit message. - * + * * @param eventId the event ID * @param rule the rule * @param policyVersion the policy version @@ -414,76 +416,76 @@ public class SystemOutLogger implements Logger, Serializable { @Override public void recordAuditEventEnd(UUID eventId, String rule, String policyVersion) { - System.out.println(className + " : " + eventId + ":" + rule + ":" + policyVersion); + displayMessage(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); + displayMessage(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); + displayMessage(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); + displayMessage(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); + displayMessage(className + " : " + eventId + ":" + message); } /** * Records a metrics message. - * + * * @param message the message */ @Override public void metrics(Object message) { - System.out.println(className + " : " + message); + displayMessage(className + " : " + message); } /** * Returns transaction Id. - * + * * @param transId the transaction ID */ @Override - public String postMDCInfoForEvent(String transId) { + public String postMdcInfoForEvent(String transId) { String transactionId = transId; if (transactionId == null || transactionId.isEmpty()) { @@ -495,18 +497,18 @@ public class SystemOutLogger implements Logger, Serializable { /** * Records transaction Id. - * + * * @param message the message */ @Override - public void postMDCInfoForEvent(Object message) { - System.out.println(message); + public void postMdcInfoForEvent(Object message) { + displayMessage(message); } /** * Returns true for trace enabled, or false for not. - * + * * @return boolean */ @Override @@ -517,13 +519,12 @@ public class SystemOutLogger implements Logger, Serializable { /** * Records transaction Id. - * + * * @param transId the transaction ID */ @Override - public void postMDCInfoForTriggeredRule(String transId) { + public void postMdcInfoForTriggeredRule(String transId) { - System.out.println(transId); + displayMessage(transId); } - } 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 85600671..ee64306f 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,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-Logging * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -25,7 +25,7 @@ import org.onap.policy.common.logging.nsa.impl.Slf4jLoggingContext; /** * A factory for setting up a LoggingContext. - * + * */ public class LoggingContextFactory { public static class Builder { @@ -47,4 +47,8 @@ public class LoggingContextFactory { return forShared ? new SharedContext(baseContext) : new Slf4jLoggingContext(baseContext); } } + + private LoggingContextFactory() { + // do nothing + } } 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 deleted file mode 100644 index 3dd62e69..00000000 --- a/common-logging/src/test/java/org/onap/policy/common/logging/eelf/DroolsPDPMDCInfoTest.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * ONAP Policy Engine - Common Modules - * ================================================================================ - * Copyright (C) 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. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.logging.eelf; - -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)); - } - -} 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 new file mode 100644 index 00000000..96030962 --- /dev/null +++ b/common-logging/src/test/java/org/onap/policy/common/logging/eelf/DroolsPdpMdcInfoTest.java @@ -0,0 +1,42 @@ +/* + * ============LICENSE_START======================================================= + * ONAP Policy Engine - Common Modules + * ================================================================================ + * Copyright (C) 2018-2019 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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.common.logging.eelf; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import com.att.eelf.configuration.Configuration; +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)); + } + +} 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 f7aa733a..6fe81d27 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 @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine - Common Modules * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -42,7 +42,7 @@ public class EventDataTest { EventData eventData = new EventData(); assertNull(eventData.getEndTime()); - assertNull(eventData.getRequestID()); + assertNull(eventData.getRequestId()); assertNull(eventData.getStartTime()); } @@ -53,24 +53,24 @@ public class EventDataTest { public void testEventDataStringInstantInstant() { EventData eventData = new EventData("myreq", istart, iend); - assertEquals("myreq", eventData.getRequestID()); + assertEquals("myreq", eventData.getRequestId()); assertEquals(istart, eventData.getStartTime()); assertEquals(iend, eventData.getEndTime()); } /** - * Test method for {@link EventData#getRequestID()} and {@link EventData#setRequestID(String)}. + * Test method for {@link EventData#getRequestId()} and {@link EventData#setRequestId(String)}. */ @Test public void testGetSetRequestId() { EventData eventData = new EventData(); - assertNull(eventData.getRequestID()); + assertNull(eventData.getRequestId()); - eventData.setRequestID("abc"); - assertEquals("abc", eventData.getRequestID()); + eventData.setRequestId("abc"); + assertEquals("abc", eventData.getRequestId()); - eventData.setRequestID("def"); - assertEquals("def", eventData.getRequestID()); + eventData.setRequestId("def"); + assertEquals("def", eventData.getRequestId()); } /** 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 7dc8fddc..e6024682 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 @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine - Common Modules * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -55,16 +55,16 @@ public class EventTrackInfoTest { } /** - * Test method for {@link EventTrackInfo#getEventDataByRequestID(String)}. + * Test method for {@link EventTrackInfo#getEventDataByRequestId(String)}. */ @Test - public void testGetEventDataByRequestID() { + public void testGetEventDataByRequestId() { info.storeEventData(data1); info.storeEventData(data2); - assertTrue(data1 == info.getEventDataByRequestID("abc")); - assertTrue(data2 == info.getEventDataByRequestID("def")); - assertNull(info.getEventDataByRequestID("hello")); + assertTrue(data1 == info.getEventDataByRequestId("abc")); + assertTrue(data2 == info.getEventDataByRequestId("def")); + assertNull(info.getEventDataByRequestId("hello")); } /** @@ -86,14 +86,14 @@ public class EventTrackInfoTest { assertEquals(2, info.getEventInfo().size()); // look-up by request id - assertTrue(data1 == info.getEventDataByRequestID("abc")); - assertTrue(data2 == info.getEventDataByRequestID("def")); + 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")); + assertTrue(data1 == info.getEventDataByRequestId("abc")); + assertTrue(data2 == info.getEventDataByRequestId("def")); } /** @@ -110,8 +110,8 @@ public class EventTrackInfoTest { assertEquals(1, info.getEventInfo().size()); // look-up by request id - assertNull(info.getEventDataByRequestID("abc")); - assertTrue(data2 == info.getEventDataByRequestID("def")); + assertNull(info.getEventDataByRequestId("abc")); + assertTrue(data2 == info.getEventDataByRequestId("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 8d6b6d68..6af3632a 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 @@ -3,13 +3,14 @@ * ONAP-Logging * ================================================================================ * Copyright (C) 2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2019 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. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -34,12 +35,11 @@ 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.overrideStaticField; +import static org.onap.policy.common.logging.eelf.OnapConfigProperties.PARTNER_NAME; +import static org.onap.policy.common.logging.eelf.OnapConfigProperties.RESPONSE_CODE; +import static org.onap.policy.common.logging.eelf.OnapConfigProperties.RESPONSE_DESCRIPTION; +import static org.onap.policy.common.logging.eelf.OnapConfigProperties.SERVER_NAME; +import static org.onap.policy.common.logging.eelf.OnapConfigProperties.STATUS_CODE; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFLogger.Level; @@ -51,6 +51,7 @@ import java.util.UUID; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; +import org.powermock.reflect.Whitebox; import org.slf4j.MDC; public class PolicyLoggerTest { @@ -105,8 +106,8 @@ public class PolicyLoggerTest { } @Test - public void testPostMDCInfoForEventString() { - PolicyLogger.postMDCInfoForEvent("transactionId"); + public void testPostMdcInfoForEventString() { + PolicyLogger.postMdcInfoForEvent("transactionId"); assertEquals("", MDC.get(MDC_REMOTE_HOST)); assertEquals("transactionId", MDC.get(MDC_KEY_REQUEST_ID)); @@ -121,12 +122,12 @@ public class PolicyLoggerTest { } @Test - public void testPostMDCInfoForEventStringDrools() { + public void testPostMdcInfoForEventStringDrools() { Properties properties = new Properties(); properties.setProperty("policy.component", "DROOLS"); PolicyLogger.init(properties); - PolicyLogger.postMDCInfoForEvent("transactionId"); + PolicyLogger.postMdcInfoForEvent("transactionId"); assertEquals("transactionId", MDC.get(MDC_KEY_REQUEST_ID)); assertEquals("Policy.droolsPdp", MDC.get(MDC_SERVICE_NAME)); @@ -140,8 +141,8 @@ public class PolicyLoggerTest { } @Test - public void testPostMDCInfoForEventObject() { - PolicyLogger.postMDCInfoForEvent(1); + public void testPostMdcInfoForEventObject() { + PolicyLogger.postMdcInfoForEvent(1); assertEquals("", MDC.get(MDC_REMOTE_HOST)); assertEquals("1", MDC.get(MDC_KEY_REQUEST_ID)); @@ -156,8 +157,8 @@ public class PolicyLoggerTest { } @Test - public void testPostMDCInfoForTriggeredRule() { - PolicyLogger.postMDCInfoForTriggeredRule("transactionId"); + public void testPostMdcInfoForTriggeredRule() { + PolicyLogger.postMdcInfoForTriggeredRule("transactionId"); assertEquals("", MDC.get(MDC_REMOTE_HOST)); assertEquals("transactionId", MDC.get(MDC_KEY_REQUEST_ID)); @@ -171,8 +172,8 @@ public class PolicyLoggerTest { } @Test - public void testPostMDCUUIDForTriggeredRule() { - PolicyLogger.postMDCUUIDForTriggeredRule(1); + public void testPostMdcUuidForTriggeredRule() { + PolicyLogger.postMdcUuidForTriggeredRule(1); assertEquals("", MDC.get(MDC_REMOTE_HOST)); assertEquals("1", MDC.get(MDC_KEY_REQUEST_ID)); @@ -188,7 +189,7 @@ public class PolicyLoggerTest { @Test public void testInfoMessageCodesStringStringArray() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger); PolicyLogger.info(MessageCodes.ERROR_DATA_ISSUE, "str1", "str2"); Mockito.verify(mockLogger).info(MessageCodes.ERROR_DATA_ISSUE, "str2"); } @@ -196,7 +197,7 @@ public class PolicyLoggerTest { @Test public void testInfoStringString() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger); PolicyLogger.info("str1", "str2"); Mockito.verify(mockLogger).info(MessageCodes.GENERAL_INFO, "str2"); } @@ -204,7 +205,7 @@ public class PolicyLoggerTest { @Test public void testInfoObject() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger); PolicyLogger.info("str1"); Mockito.verify(mockLogger).info(MessageCodes.GENERAL_INFO, "str1"); } @@ -212,7 +213,7 @@ public class PolicyLoggerTest { @Test public void testInfoMessageCodesThrowableStringArray() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); + Whitebox.setInternalState(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")); @@ -221,7 +222,7 @@ public class PolicyLoggerTest { @Test public void testInfoMessageCodesStringThrowableStringArray() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger); PolicyLogger.info(MessageCodes.ERROR_DATA_ISSUE, "PolicyLoggerTest", new NullPointerException(), "str1", "str2"); Mockito.verify(mockLogger).info((MessageCodes) Mockito.any(), @@ -231,7 +232,7 @@ public class PolicyLoggerTest { @Test public void testWarnMessageCodesStringStringArray() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger); PolicyLogger.warn(MessageCodes.ERROR_DATA_ISSUE, "str1"); Mockito.verify(mockLogger).warn(MessageCodes.ERROR_DATA_ISSUE); } @@ -239,7 +240,7 @@ public class PolicyLoggerTest { @Test public void testWarnStringString() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger); PolicyLogger.warn("str1", "str2"); Mockito.verify(mockLogger).warn(MessageCodes.GENERAL_INFO, "str2"); } @@ -247,7 +248,7 @@ public class PolicyLoggerTest { @Test public void testWarnObject() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger); PolicyLogger.warn(1); Mockito.verify(mockLogger).warn(MessageCodes.GENERAL_WARNING, "1"); } @@ -255,7 +256,7 @@ public class PolicyLoggerTest { @Test public void testWarnMessageCodesThrowableStringArray() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); + Whitebox.setInternalState(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")); @@ -264,7 +265,7 @@ public class PolicyLoggerTest { @Test public void testWarnMessageCodesStringThrowableStringArray() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger); PolicyLogger.warn(MessageCodes.ERROR_DATA_ISSUE, "PolicyLoggerTest", new NullPointerException(), "str1", "str2"); Mockito.verify(mockLogger).warn((MessageCodes) Mockito.any(), @@ -274,7 +275,7 @@ public class PolicyLoggerTest { @Test public void testWarnString() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger); PolicyLogger.warn("str1"); Mockito.verify(mockLogger).warn(MessageCodes.GENERAL_WARNING, "str1"); } @@ -282,7 +283,7 @@ public class PolicyLoggerTest { @Test public void testErrorStringString() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "errorLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "errorLogger", mockLogger); PolicyLogger.error("str1", "str2"); Mockito.verify(mockLogger).error(MessageCodes.GENERAL_ERROR, "str2"); assertEquals("POLICY-515E", MDC.get("ErrorCode")); @@ -293,7 +294,7 @@ public class PolicyLoggerTest { @Test public void testErrorString() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "errorLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "errorLogger", mockLogger); PolicyLogger.error("str1"); Mockito.verify(mockLogger).error(MessageCodes.GENERAL_ERROR, "str1"); assertEquals("ERROR", MDC.get("ErrorCategory")); @@ -305,7 +306,7 @@ public class PolicyLoggerTest { @Test public void testErrorObject() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "errorLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "errorLogger", mockLogger); PolicyLogger.error(1); Mockito.verify(mockLogger).error(MessageCodes.GENERAL_ERROR, "1"); assertEquals("ERROR", MDC.get("ErrorCategory")); @@ -317,7 +318,7 @@ public class PolicyLoggerTest { @Test public void testErrorMessageCodesThrowableStringArray() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "errorLogger", mockLogger); + Whitebox.setInternalState(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")); @@ -326,7 +327,7 @@ public class PolicyLoggerTest { @Test public void testErrorMessageCodesStringThrowableStringArray() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "errorLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "errorLogger", mockLogger); PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "PolicyLoggerTest", new NullPointerException(), "str1", "str2"); Mockito.verify(mockLogger).error((MessageCodes) Mockito.any(), @@ -336,7 +337,7 @@ public class PolicyLoggerTest { @Test public void testErrorMessageCodesStringArray() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "errorLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "errorLogger", mockLogger); PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "str1", "str2"); Mockito.verify(mockLogger).error(MessageCodes.ERROR_DATA_ISSUE, "str1", "str2"); } @@ -344,7 +345,7 @@ public class PolicyLoggerTest { @Test public void testDebugMessageCodesStringArray() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger); PolicyLogger.debug(MessageCodes.ERROR_DATA_ISSUE, "str1", "str2"); Mockito.verify(mockLogger).debug(MessageCodes.ERROR_DATA_ISSUE, "str1", "str2"); } @@ -352,7 +353,7 @@ public class PolicyLoggerTest { @Test public void testDebugStringString() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger); PolicyLogger.debug("str1", "str2"); Mockito.verify(mockLogger).debug(MessageCodes.GENERAL_INFO, "str2"); } @@ -360,7 +361,7 @@ public class PolicyLoggerTest { @Test public void testDebugString() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger); PolicyLogger.debug("str1"); Mockito.verify(mockLogger).debug("str1"); } @@ -368,7 +369,7 @@ public class PolicyLoggerTest { @Test public void testDebugObject() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger); PolicyLogger.debug(1); Mockito.verify(mockLogger).debug("1"); } @@ -376,7 +377,7 @@ public class PolicyLoggerTest { @Test public void testAuditStringObject() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "auditLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "auditLogger", mockLogger); PolicyLogger.audit("PolicyLoggerTest", 1); assertEquals("PolicyLoggerTest", MDC.get("ClassName")); assertEquals("COMPLETE", MDC.get("StatusCode")); @@ -386,7 +387,7 @@ public class PolicyLoggerTest { @Test public void testAuditObject() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "auditLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "auditLogger", mockLogger); PolicyLogger.audit(1); assertEquals("", MDC.get("ClassName")); assertEquals("COMPLETE", MDC.get("StatusCode")); @@ -396,7 +397,7 @@ public class PolicyLoggerTest { @Test public void testDebugMessageCodesThrowableStringArray() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); + Whitebox.setInternalState(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")); @@ -405,7 +406,7 @@ public class PolicyLoggerTest { @Test public void testDebugMessageCodesStringThrowableStringArray() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger); PolicyLogger.debug(MessageCodes.ERROR_DATA_ISSUE, "PolicyLoggerTest", new NullPointerException(), "str1", "str2"); Mockito.verify(mockLogger).debug((MessageCodes) Mockito.any(), @@ -415,7 +416,7 @@ public class PolicyLoggerTest { @Test public void testIsDebugEnabled() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger); Mockito.when(mockLogger.isDebugEnabled()).thenReturn(false).thenReturn(true); assertFalse(PolicyLogger.isDebugEnabled()); assertTrue(PolicyLogger.isDebugEnabled()); @@ -424,7 +425,7 @@ public class PolicyLoggerTest { @Test public void testIsErrorEnabled() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "errorLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "errorLogger", mockLogger); Mockito.when(mockLogger.isErrorEnabled()).thenReturn(false).thenReturn(true); assertFalse(PolicyLogger.isErrorEnabled()); assertTrue(PolicyLogger.isErrorEnabled()); @@ -433,7 +434,7 @@ public class PolicyLoggerTest { @Test public void testIsWarnEnabled() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger); Mockito.when(mockLogger.isWarnEnabled()).thenReturn(false).thenReturn(true); assertFalse(PolicyLogger.isWarnEnabled()); assertTrue(PolicyLogger.isWarnEnabled()); @@ -442,7 +443,7 @@ public class PolicyLoggerTest { @Test public void testIsInfoEnabled1() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger); Mockito.when(mockLogger.isInfoEnabled()).thenReturn(false).thenReturn(true); assertFalse(PolicyLogger.isInfoEnabled1()); assertTrue(PolicyLogger.isInfoEnabled1()); @@ -451,7 +452,7 @@ public class PolicyLoggerTest { @Test public void testIsAuditEnabled() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger); Mockito.when(mockLogger.isInfoEnabled()).thenReturn(false).thenReturn(true); assertFalse(PolicyLogger.isAuditEnabled()); assertTrue(PolicyLogger.isAuditEnabled()); @@ -460,7 +461,7 @@ public class PolicyLoggerTest { @Test public void testIsInfoEnabled() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger); Mockito.when(mockLogger.isInfoEnabled()).thenReturn(false).thenReturn(true); assertFalse(PolicyLogger.isInfoEnabled()); assertTrue(PolicyLogger.isInfoEnabled()); @@ -469,7 +470,7 @@ public class PolicyLoggerTest { @Test public void testTraceStringString() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger); PolicyLogger.trace("str1", "str2"); Mockito.verify(mockLogger).trace(MessageCodes.GENERAL_INFO, "str2"); } @@ -477,7 +478,7 @@ public class PolicyLoggerTest { @Test public void testTraceObject() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger); PolicyLogger.trace(1); Mockito.verify(mockLogger).trace("1"); } @@ -492,7 +493,7 @@ public class PolicyLoggerTest { } @Test - public void testRecordAuditEventStartAndEndUUID() { + public void testRecordAuditEventStartAndEndUuid() { UUID uuid = UUID.randomUUID(); PolicyLogger.recordAuditEventStart(uuid);; assertNotNull(PolicyLogger.getEventTracker().getEventInfo().get(uuid.toString())); @@ -512,7 +513,7 @@ public class PolicyLoggerTest { } @Test - public void testRecordAuditEventEndUUIDStringString() { + public void testRecordAuditEventEndUuidStringString() { UUID uuid = UUID.randomUUID(); PolicyLogger.recordAuditEventStart(uuid);; assertNotNull(PolicyLogger.getEventTracker().getEventInfo().get(uuid.toString())); @@ -532,7 +533,7 @@ public class PolicyLoggerTest { } @Test - public void testCreatAuditEventTrackingRecordUUIDString() { + public void testCreatAuditEventTrackingRecordUuidString() { UUID uuid = UUID.randomUUID(); PolicyLogger.recordAuditEventStart(uuid);; assertNotNull(PolicyLogger.getEventTracker().getEventInfo().get(uuid.toString())); @@ -560,7 +561,7 @@ public class PolicyLoggerTest { } @Test - public void testRecordMetricEventUUIDString() { + public void testRecordMetricEventUuidString() { UUID uuid = UUID.randomUUID(); PolicyLogger.recordMetricEvent(uuid, "str1"); assertEquals(uuid.toString(), MDC.get(MDC_KEY_REQUEST_ID)); @@ -569,7 +570,7 @@ public class PolicyLoggerTest { @Test public void testRecordMetricEventString() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "metricsLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "metricsLogger", mockLogger); PolicyLogger.recordMetricEvent("eventId"); Mockito.verify(mockLogger).info(Mockito.eq(MessageCodes.RULE_METRICS_INFO), Mockito.anyString(), Mockito.eq("eventId")); @@ -578,7 +579,7 @@ public class PolicyLoggerTest { @Test public void testMetricsString() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "metricsLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "metricsLogger", mockLogger); PolicyLogger.metrics("str1"); Mockito.verify(mockLogger).info(Mockito.eq(MessageCodes.RULE_METRICS_INFO), Mockito.anyString(), Mockito.eq("str1")); @@ -587,7 +588,7 @@ public class PolicyLoggerTest { @Test public void testMetricsStringObject() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "metricsLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "metricsLogger", mockLogger); PolicyLogger.metrics("PolicyLoggerTest", 1); Mockito.verify(mockLogger).info(Mockito.eq(MessageCodes.RULE_METRICS_INFO), Mockito.anyString(), Mockito.eq("1")); @@ -596,7 +597,7 @@ public class PolicyLoggerTest { @Test public void testMetricsObject() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "metricsLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "metricsLogger", mockLogger); PolicyLogger.metrics(1); Mockito.verify(mockLogger).info(Mockito.eq(MessageCodes.RULE_METRICS_INFO), Mockito.anyString(), Mockito.eq("1")); @@ -605,7 +606,7 @@ public class PolicyLoggerTest { @Test public void testMetricsPrintln() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "metricsLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "metricsLogger", mockLogger); PolicyLogger.metricsPrintln("str1"); Mockito.verify(mockLogger).info("str1"); } 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 a7e835ce..d3c09ee6 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 @@ -3,13 +3,14 @@ * ONAP-Logging * ================================================================================ * Copyright (C) 2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2019 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. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -26,16 +27,14 @@ 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.powermock.reflect.Whitebox; import org.slf4j.MDC; public class EelfLoggerTest { @@ -92,7 +91,7 @@ public class EelfLoggerTest { @Test public void testDebugObject() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger); eelfLogger.debug("message"); Mockito.verify(mockLogger).debug(MessageCodes.GENERAL_INFO, "message"); } @@ -100,7 +99,7 @@ public class EelfLoggerTest { @Test public void testErrorObject() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "errorLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "errorLogger", mockLogger); eelfLogger.error("message"); Mockito.verify(mockLogger).error(MessageCodes.GENERAL_ERROR, "message"); } @@ -108,7 +107,7 @@ public class EelfLoggerTest { @Test public void testInfoObject() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger); eelfLogger.info("message"); Mockito.verify(mockLogger).info(MessageCodes.GENERAL_INFO, "message"); } @@ -116,7 +115,7 @@ public class EelfLoggerTest { @Test public void testWarnObject() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger); eelfLogger.warn("message"); Mockito.verify(mockLogger).warn(MessageCodes.GENERAL_INFO, "message"); } @@ -124,7 +123,7 @@ public class EelfLoggerTest { @Test public void testTraceObject() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger); eelfLogger.trace("message"); Mockito.verify(mockLogger).trace(MessageCodes.GENERAL_INFO, "message"); } @@ -132,7 +131,7 @@ public class EelfLoggerTest { @Test public void testIsDebugEnabled() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger); Mockito.when(mockLogger.isDebugEnabled()).thenReturn(false).thenReturn(true); assertFalse(eelfLogger.isDebugEnabled()); assertTrue(eelfLogger.isDebugEnabled()); @@ -142,7 +141,7 @@ public class EelfLoggerTest { @Test public void testIsInfoEnabled() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger); Mockito.when(mockLogger.isInfoEnabled()).thenReturn(false).thenReturn(true); assertFalse(eelfLogger.isInfoEnabled()); assertTrue(eelfLogger.isInfoEnabled()); @@ -151,7 +150,7 @@ public class EelfLoggerTest { @Test public void testIsWarnEnabled() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger); Mockito.when(mockLogger.isWarnEnabled()).thenReturn(false).thenReturn(true); assertFalse(eelfLogger.isWarnEnabled()); assertTrue(eelfLogger.isWarnEnabled()); @@ -160,7 +159,7 @@ public class EelfLoggerTest { @Test public void testIsErrorEnabled() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "errorLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "errorLogger", mockLogger); Mockito.when(mockLogger.isErrorEnabled()).thenReturn(false).thenReturn(true); assertFalse(eelfLogger.isErrorEnabled()); assertTrue(eelfLogger.isErrorEnabled()); @@ -183,7 +182,7 @@ public class EelfLoggerTest { @Test public void testIsTraceEnabled() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger); Mockito.when(mockLogger.isDebugEnabled()).thenReturn(false).thenReturn(true); assertFalse(eelfLogger.isTraceEnabled()); assertTrue(eelfLogger.isTraceEnabled()); @@ -199,7 +198,7 @@ public class EelfLoggerTest { @Test public void testDebugObjectThrowable() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger); eelfLogger.debug("message", new NullPointerException()); Mockito.verify(mockLogger).debug((MessageCodes) Mockito.any(), Mockito.startsWith("message:java.lang.NullPointerException")); @@ -208,7 +207,7 @@ public class EelfLoggerTest { @Test public void testErrorObjectThrowable() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "errorLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "errorLogger", mockLogger); eelfLogger.error("message", new NullPointerException()); Mockito.verify(mockLogger).error((MessageCodes) Mockito.any(), Mockito.startsWith("message:java.lang.NullPointerException")); @@ -218,7 +217,7 @@ public class EelfLoggerTest { @Test public void testInfoObjectThrowable() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger); eelfLogger.info("message", new NullPointerException()); Mockito.verify(mockLogger).info((MessageCodes) Mockito.any(), Mockito.startsWith("message:java.lang.NullPointerException")); @@ -227,7 +226,7 @@ public class EelfLoggerTest { @Test public void testWarnObjectThrowable() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger); eelfLogger.warn("message", new NullPointerException()); Mockito.verify(mockLogger).warn((MessageCodes) Mockito.any(), Mockito.startsWith("message:java.lang.NullPointerException")); @@ -236,7 +235,7 @@ public class EelfLoggerTest { @Test public void testTraceObjectThrowable() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger); eelfLogger.trace("message", new NullPointerException()); Mockito.verify(mockLogger).trace("message"); } @@ -244,7 +243,7 @@ public class EelfLoggerTest { @Test public void testAuditObjectThrowable() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "auditLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "auditLogger", mockLogger); eelfLogger.audit("message", new NullPointerException()); Mockito.verify(mockLogger).info("message"); } @@ -256,7 +255,7 @@ public class EelfLoggerTest { } @Test - public void testRecordAuditEventStartUUID() { + public void testRecordAuditEventStartUuid() { UUID uuid = UUID.randomUUID(); eelfLogger.recordAuditEventStart(uuid); assertNotNull(PolicyLogger.getEventTracker().getEventInfo().get(uuid.toString())); @@ -272,7 +271,7 @@ public class EelfLoggerTest { } @Test - public void testRecordAuditEventEndUUIDStringString() { + public void testRecordAuditEventEndUuidStringString() { UUID uuid = UUID.randomUUID(); eelfLogger.recordAuditEventStart(uuid);; assertNotNull(PolicyLogger.getEventTracker().getEventInfo().get(uuid.toString())); @@ -291,7 +290,7 @@ public class EelfLoggerTest { } @Test - public void testRecordAuditEventEndUUIDString() { + public void testRecordAuditEventEndUuidString() { UUID uuid = UUID.randomUUID(); eelfLogger.recordAuditEventStart(uuid);; assertNotNull(PolicyLogger.getEventTracker().getEventInfo().get(uuid.toString())); @@ -307,7 +306,7 @@ public class EelfLoggerTest { } @Test - public void testRecordMetricEventUUIDString() { + public void testRecordMetricEventUuidString() { UUID uuid = UUID.randomUUID(); eelfLogger.recordMetricEvent(uuid, "str2"); assertEquals(uuid.toString(), MDC.get(MDC_KEY_REQUEST_ID)); @@ -316,7 +315,7 @@ public class EelfLoggerTest { @Test public void testMetrics() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "metricsLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "metricsLogger", mockLogger); eelfLogger.metrics(1); Mockito.verify(mockLogger).info(Mockito.eq(MessageCodes.RULE_METRICS_INFO), Mockito.anyString(), Mockito.eq("1")); @@ -325,7 +324,7 @@ public class EelfLoggerTest { @Test public void testErrorMessageCodesThrowableStringArray() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "errorLogger", mockLogger); + Whitebox.setInternalState(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")); @@ -334,22 +333,22 @@ public class EelfLoggerTest { @Test public void testErrorMessageCodesStringArray() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "errorLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "errorLogger", mockLogger); eelfLogger.error(MessageCodes.GENERAL_ERROR, "str1", "str2"); Mockito.verify(mockLogger).error(MessageCodes.GENERAL_ERROR, "str1", "str2"); } @Test - public void testPostMDCInfoForEventString() { - eelfLogger.postMDCInfoForEvent("transactionId"); + public void testPostMdcInfoForEventString() { + eelfLogger.postMdcInfoForEvent("transactionId"); assertEquals("transactionId", MDC.get(MDC_KEY_REQUEST_ID)); } @Test public void testWarnMessageCodesStringArray() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); + Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger); eelfLogger.warn(MessageCodes.GENERAL_ERROR, "str1", "str2"); Mockito.verify(mockLogger).warn(MessageCodes.GENERAL_ERROR, "str1", "str2"); } @@ -357,7 +356,7 @@ public class EelfLoggerTest { @Test public void testWarnMessageCodesThrowableStringArray() { EELFLogger mockLogger = Mockito.mock(EELFLogger.class); - overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger); + Whitebox.setInternalState(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")); @@ -365,14 +364,14 @@ public class EelfLoggerTest { } @Test - public void testPostMDCInfoForTriggeredRule() { - eelfLogger.postMDCInfoForTriggeredRule("transactionId"); + public void testPostMdcInfoForTriggeredRule() { + eelfLogger.postMdcInfoForTriggeredRule("transactionId"); assertEquals("transactionId", MDC.get(MDC_KEY_REQUEST_ID)); } @Test - public void testPostMDCInfoForEventObject() { - eelfLogger.postMDCInfoForEvent(1); + public void testPostMDdcInfoForEventObject() { + eelfLogger.postMdcInfoForEvent(1); assertEquals("1", MDC.get(MDC_KEY_REQUEST_ID)); } 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 7d6088eb..a74dd94d 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 @@ -3,13 +3,14 @@ * ONAP-Logging * ================================================================================ * Copyright (C) 2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2019 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. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,20 +23,19 @@ package org.onap.policy.common.logging.flexlogger; 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; +import org.powermock.reflect.Whitebox; public class FlexLoggerTest { @Test public void testGetLoggerClassOfQEelf() { - overrideStaticField(FlexLogger.class, "loggerType", LoggerType.EELF); + Whitebox.setInternalState(FlexLogger.class, "loggerType", LoggerType.EELF); Logger logger = FlexLogger.getLogger((Class) null); assertSame(logger, FlexLogger.getLogger((Class) null)); assertNotEquals(logger, FlexLogger.getLogger(String.class)); @@ -43,77 +43,77 @@ public class FlexLoggerTest { @Test public void testGetLoggerClassOfQLog4j() { - overrideStaticField(FlexLogger.class, "loggerType", LoggerType.LOG4J); + Whitebox.setInternalState(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); + Whitebox.setInternalState(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); + Whitebox.setInternalState(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); + Whitebox.setInternalState(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); + Whitebox.setInternalState(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); + Whitebox.setInternalState(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); + Whitebox.setInternalState(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); + Whitebox.setInternalState(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); + Whitebox.setInternalState(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); + Whitebox.setInternalState(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); + Whitebox.setInternalState(FlexLogger.class, "loggerType", LoggerType.SYSTEMOUT); Logger logger = FlexLogger.getLogger("str1", true); assertSame(logger, FlexLogger.getLogger("str1", true)); } 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 7f2964c2..99c343c0 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 @@ -3,13 +3,14 @@ * ONAP-Logging * ================================================================================ * Copyright (C) 2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2019 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. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -27,13 +28,12 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.UUID; - import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.junit.Test; import org.mockito.Mockito; import org.onap.policy.common.logging.eelf.MessageCodes; -import org.onap.policy.common.logging.util.TestUtils; +import org.powermock.reflect.Whitebox; public class Logger4JTest { @@ -53,7 +53,7 @@ public class Logger4JTest { @Test public void testDebugObject() { Logger logger = Mockito.mock(Logger.class); - TestUtils.overrideField(Logger4J.class, logger4J, "log", logger); + Whitebox.setInternalState(logger4J, "log", logger); Mockito.when(logger.isDebugEnabled()).thenReturn(true); logger4J.setTransId("transactionId"); logger4J.debug("message"); @@ -63,7 +63,7 @@ public class Logger4JTest { @Test public void testErrorObject() { Logger logger = Mockito.mock(Logger.class); - TestUtils.overrideField(Logger4J.class, logger4J, "log", logger); + Whitebox.setInternalState(logger4J, "log", logger); logger4J.setTransId("transactionId"); logger4J.error("message"); Mockito.verify(logger).error("transactionId|Logger4JTest|message"); @@ -72,7 +72,7 @@ public class Logger4JTest { @Test public void testInfoObject() { Logger logger = Mockito.mock(Logger.class); - TestUtils.overrideField(Logger4J.class, logger4J, "log", logger); + Whitebox.setInternalState(logger4J, "log", logger); logger4J.setTransId("transactionId"); logger4J.info("message"); Mockito.verify(logger).info("transactionId|Logger4JTest|message"); @@ -81,7 +81,7 @@ public class Logger4JTest { @Test public void testWarnObject() { Logger logger = Mockito.mock(Logger.class); - TestUtils.overrideField(Logger4J.class, logger4J, "log", logger); + Whitebox.setInternalState(logger4J, "log", logger); logger4J.setTransId("transactionId"); logger4J.warn("message"); Mockito.verify(logger).warn("transactionId|Logger4JTest|message"); @@ -90,7 +90,7 @@ public class Logger4JTest { @Test public void testTraceObject() { Logger logger = Mockito.mock(Logger.class); - TestUtils.overrideField(Logger4J.class, logger4J, "log", logger); + Whitebox.setInternalState(logger4J, "log", logger); logger4J.setTransId("transactionId"); logger4J.trace("message"); Mockito.verify(logger).trace("transactionId|Logger4JTest|message"); @@ -99,7 +99,7 @@ public class Logger4JTest { @Test public void testIsDebugEnabled() { Logger logger = Mockito.mock(Logger.class); - TestUtils.overrideField(Logger4J.class, logger4J, "log", logger); + Whitebox.setInternalState(logger4J, "log", logger); Mockito.when(logger.isDebugEnabled()).thenReturn(true).thenReturn(false); assertTrue(logger4J.isDebugEnabled()); assertFalse(logger4J.isDebugEnabled()); @@ -108,7 +108,7 @@ public class Logger4JTest { @Test public void testIsErrorEnabled() { Logger logger = Mockito.mock(Logger.class); - TestUtils.overrideField(Logger4J.class, logger4J, "log", logger); + Whitebox.setInternalState(logger4J, "log", logger); Mockito.when(logger.isEnabledFor(Level.ERROR)).thenReturn(true).thenReturn(false); assertTrue(logger4J.isErrorEnabled()); assertFalse(logger4J.isErrorEnabled()); @@ -117,7 +117,7 @@ public class Logger4JTest { @Test public void testIsInfoEnabled() { Logger logger = Mockito.mock(Logger.class); - TestUtils.overrideField(Logger4J.class, logger4J, "log", logger); + Whitebox.setInternalState(logger4J, "log", logger); Mockito.when(logger.isInfoEnabled()).thenReturn(true).thenReturn(false); assertTrue(logger4J.isInfoEnabled()); assertFalse(logger4J.isInfoEnabled()); @@ -126,7 +126,7 @@ public class Logger4JTest { @Test public void testIsWarnEnabled() { Logger logger = Mockito.mock(Logger.class); - TestUtils.overrideField(Logger4J.class, logger4J, "log", logger); + Whitebox.setInternalState(logger4J, "log", logger); Mockito.when(logger.isEnabledFor(Level.WARN)).thenReturn(true).thenReturn(false); assertTrue(logger4J.isWarnEnabled()); assertFalse(logger4J.isWarnEnabled()); @@ -135,7 +135,7 @@ public class Logger4JTest { @Test public void testAuditObject() { Logger logger = Mockito.mock(Logger.class); - TestUtils.overrideField(Logger4J.class, logger4J, "log", logger); + Whitebox.setInternalState(logger4J, "log", logger); logger4J.audit("str1"); Mockito.verify(logger).info("Logger4JTest|str1"); } @@ -143,15 +143,15 @@ public class Logger4JTest { @Test public void testRecordAuditEventStartString() { Logger logger = Mockito.mock(Logger.class); - TestUtils.overrideField(Logger4J.class, logger4J, "log", logger); + Whitebox.setInternalState(logger4J, "log", logger); logger4J.recordAuditEventEnd("eventId", "rule"); Mockito.verify(logger).info("Logger4JTest|eventId:rule"); } @Test - public void testRecordAuditEventStartUUID() { + public void testRecordAuditEventStartUuid() { Logger logger = Mockito.mock(Logger.class); - TestUtils.overrideField(Logger4J.class, logger4J, "log", logger); + Whitebox.setInternalState(logger4J, "log", logger); UUID uuid = UUID.randomUUID(); logger4J.recordAuditEventStart(uuid); Mockito.verify(logger).info("Logger4JTest|recordAuditEventStart with eventId " + uuid.toString()); @@ -160,15 +160,15 @@ public class Logger4JTest { @Test public void testRecordAuditEventEndStringStringString() { Logger logger = Mockito.mock(Logger.class); - TestUtils.overrideField(Logger4J.class, logger4J, "log", logger); + Whitebox.setInternalState(logger4J, "log", logger); logger4J.recordAuditEventEnd("eventId", "rule", "policyVersion"); Mockito.verify(logger).info("Logger4JTest|eventId:rule"); } @Test - public void testRecordAuditEventEndUUIDStringString() { + public void testRecordAuditEventEndUuidStringString() { Logger logger = Mockito.mock(Logger.class); - TestUtils.overrideField(Logger4J.class, logger4J, "log", logger); + Whitebox.setInternalState(logger4J, "log", logger); UUID uuid = UUID.randomUUID(); logger4J.recordAuditEventEnd(uuid, "rule", "policyVersion"); Mockito.verify(logger).info("Logger4JTest|" + uuid.toString() + ":rule"); @@ -177,15 +177,15 @@ public class Logger4JTest { @Test public void testRecordAuditEventEndStringString() { Logger logger = Mockito.mock(Logger.class); - TestUtils.overrideField(Logger4J.class, logger4J, "log", logger); + Whitebox.setInternalState(logger4J, "log", logger); logger4J.recordAuditEventEnd("eventId", "rule"); Mockito.verify(logger).info("Logger4JTest|eventId:rule"); } @Test - public void testRecordAuditEventEndUUIDString() { + public void testRecordAuditEventEndUuidString() { Logger logger = Mockito.mock(Logger.class); - TestUtils.overrideField(Logger4J.class, logger4J, "log", logger); + Whitebox.setInternalState(logger4J, "log", logger); UUID uuid = UUID.randomUUID(); logger4J.recordAuditEventEnd(uuid, "rule"); Mockito.verify(logger).info("Logger4JTest|" + uuid.toString() + ":rule"); @@ -194,15 +194,15 @@ public class Logger4JTest { @Test public void testRecordMetricEventStringString() { Logger logger = Mockito.mock(Logger.class); - TestUtils.overrideField(Logger4J.class, logger4J, "log", logger); + Whitebox.setInternalState(logger4J, "log", logger); logger4J.recordMetricEvent("eventId", "str1"); Mockito.verify(logger).info("Logger4JTest|eventId:str1"); } @Test - public void testRecordMetricEventUUIDString() { + public void testRecordMetricEventUuidString() { Logger logger = Mockito.mock(Logger.class); - TestUtils.overrideField(Logger4J.class, logger4J, "log", logger); + Whitebox.setInternalState(logger4J, "log", logger); UUID uuid = UUID.randomUUID(); logger4J.recordMetricEvent(uuid, "str1"); Mockito.verify(logger).info("Logger4JTest|" + uuid.toString() + ":str1"); @@ -211,7 +211,7 @@ public class Logger4JTest { @Test public void testMetrics() { Logger logger = Mockito.mock(Logger.class); - TestUtils.overrideField(Logger4J.class, logger4J, "log", logger); + Whitebox.setInternalState(logger4J, "log", logger); logger4J.metrics("str1"); Mockito.verify(logger).info("str1"); } @@ -219,7 +219,7 @@ public class Logger4JTest { @Test public void testErrorMessageCodesThrowableStringArray() { Logger logger = Mockito.mock(Logger.class); - TestUtils.overrideField(Logger4J.class, logger4J, "log", logger); + Whitebox.setInternalState(logger4J, "log", logger); logger4J.setTransId("transactionId"); logger4J.error(MessageCodes.GENERAL_ERROR, new NullPointerException(), "str1", "str2"); Mockito.verify(logger) @@ -229,7 +229,7 @@ public class Logger4JTest { @Test public void testErrorMessageCodesStringArray() { Logger logger = Mockito.mock(Logger.class); - TestUtils.overrideField(Logger4J.class, logger4J, "log", logger); + Whitebox.setInternalState(logger4J, "log", logger); logger4J.setTransId("transactionId"); logger4J.error(MessageCodes.GENERAL_ERROR, "str1", "str2"); Mockito.verify(logger) @@ -237,14 +237,14 @@ public class Logger4JTest { } @Test - public void testPostMDCInfoForEventString() { - String returnedTransactionId = logger4J.postMDCInfoForEvent("transactionId"); + public void testPostMdcInfoForEventString() { + String returnedTransactionId = logger4J.postMdcInfoForEvent("transactionId"); assertEquals("transactionId", returnedTransactionId); } @Test - public void testPostMDCInfoForEventEmptyString() { - String returnedTransactionId = logger4J.postMDCInfoForEvent(""); + public void testPostMdcInfoForEventEmptyString() { + String returnedTransactionId = logger4J.postMdcInfoForEvent(""); assertNotNull("", returnedTransactionId); assertNotEquals("", returnedTransactionId); } @@ -252,7 +252,7 @@ public class Logger4JTest { @Test public void testWarnMessageCodesStringArray() { Logger logger = Mockito.mock(Logger.class); - TestUtils.overrideField(Logger4J.class, logger4J, "log", logger); + Whitebox.setInternalState(logger4J, "log", logger); logger4J.warn(MessageCodes.GENERAL_ERROR, "str1", "str2"); Mockito.verify(logger).warn("Logger4JTest|MessageCodes:" + MessageCodes.GENERAL_ERROR + "[str1, str2]"); } @@ -260,7 +260,7 @@ public class Logger4JTest { @Test public void testWarnMessageCodesThrowableStringArray() { Logger logger = Mockito.mock(Logger.class); - TestUtils.overrideField(Logger4J.class, logger4J, "log", logger); + Whitebox.setInternalState(logger4J, "log", logger); logger4J.setTransId("transactionId"); logger4J.warn(MessageCodes.GENERAL_ERROR, new NullPointerException(), "str1", "str2"); Mockito.verify(logger).warn("Logger4JTest|MessageCodes:" + MessageCodes.GENERAL_ERROR + "[str1, str2]"); @@ -269,7 +269,7 @@ public class Logger4JTest { @Test public void testDebugObjectThrowable() { Logger logger = Mockito.mock(Logger.class); - TestUtils.overrideField(Logger4J.class, logger4J, "log", logger); + Whitebox.setInternalState(logger4J, "log", logger); logger4J.setTransId("transactionId"); Exception exception = new NullPointerException(); logger4J.debug("message", exception); @@ -279,7 +279,7 @@ public class Logger4JTest { @Test public void testErrorObjectThrowable() { Logger logger = Mockito.mock(Logger.class); - TestUtils.overrideField(Logger4J.class, logger4J, "log", logger); + Whitebox.setInternalState(logger4J, "log", logger); logger4J.setTransId("transactionId"); Exception exception = new NullPointerException(); logger4J.error("message", exception); @@ -289,7 +289,7 @@ public class Logger4JTest { @Test public void testInfoObjectThrowable() { Logger logger = Mockito.mock(Logger.class); - TestUtils.overrideField(Logger4J.class, logger4J, "log", logger); + Whitebox.setInternalState(logger4J, "log", logger); logger4J.setTransId("transactionId"); Exception exception = new NullPointerException(); logger4J.info("message", exception); @@ -299,7 +299,7 @@ public class Logger4JTest { @Test public void testWarnObjectThrowable() { Logger logger = Mockito.mock(Logger.class); - TestUtils.overrideField(Logger4J.class, logger4J, "log", logger); + Whitebox.setInternalState(logger4J, "log", logger); Exception exception = new NullPointerException(); logger4J.warn("message", exception); Mockito.verify(logger).warn("message", exception); @@ -308,7 +308,7 @@ public class Logger4JTest { @Test public void testTraceObjectThrowable() { Logger logger = Mockito.mock(Logger.class); - TestUtils.overrideField(Logger4J.class, logger4J, "log", logger); + Whitebox.setInternalState(logger4J, "log", logger); Exception exception = new NullPointerException(); logger4J.trace("message", exception); Mockito.verify(logger).trace("message", exception); @@ -317,7 +317,7 @@ public class Logger4JTest { @Test public void testAuditObjectThrowable() { Logger logger = Mockito.mock(Logger.class); - TestUtils.overrideField(Logger4J.class, logger4J, "log", logger); + Whitebox.setInternalState(logger4J, "log", logger); Exception exception = new NullPointerException(); logger4J.audit("message", exception); Mockito.verify(logger).info("message", exception); @@ -326,24 +326,24 @@ public class Logger4JTest { @Test public void testIsTraceEnabled() { Logger logger = Mockito.mock(Logger.class); - TestUtils.overrideField(Logger4J.class, logger4J, "log", logger); + Whitebox.setInternalState(logger4J, "log", logger); logger4J.isTraceEnabled(); Mockito.verify(logger).isTraceEnabled(); } @Test - public void testPostMDCInfoForTriggeredRule() { + public void testPostMdcInfoForTriggeredRule() { Logger logger = Mockito.mock(Logger.class); - TestUtils.overrideField(Logger4J.class, logger4J, "log", logger); - logger4J.postMDCInfoForTriggeredRule("transactionId"); + Whitebox.setInternalState(logger4J, "log", logger); + logger4J.postMdcInfoForTriggeredRule("transactionId"); Mockito.verify(logger).info("transactionId"); } @Test - public void testPostMDCInfoForEventObject() { + public void testPostMdcInfoForEventObject() { Logger logger = Mockito.mock(Logger.class); - TestUtils.overrideField(Logger4J.class, logger4J, "log", logger); - logger4J.postMDCInfoForEvent(1); + Whitebox.setInternalState(logger4J, "log", logger); + logger4J.postMdcInfoForEvent(1); Mockito.verify(logger).info(1); } 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 cd16a3fd..92df0297 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 @@ -3,13 +3,14 @@ * ONAP-Logging * ================================================================================ * Copyright (C) 2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2019 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. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -222,7 +223,7 @@ public class SystemOutLoggerTest { } @Test - public void testRecordAuditEventStartUUID() { + public void testRecordAuditEventStartUuid() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); PrintStream old = System.out; @@ -253,7 +254,7 @@ public class SystemOutLoggerTest { } @Test - public void testRecordAuditEventEndUUIDStringString() { + public void testRecordAuditEventEndUuidStringString() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); PrintStream old = System.out; @@ -284,7 +285,7 @@ public class SystemOutLoggerTest { } @Test - public void testRecordAuditEventEndUUIDString() { + public void testRecordAuditEventEndUuidString() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); PrintStream old = System.out; @@ -315,7 +316,7 @@ public class SystemOutLoggerTest { } @Test - public void testRecordMetricEventUUIDString() { + public void testRecordMetricEventUuidString() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); PrintStream old = System.out; @@ -379,8 +380,8 @@ public class SystemOutLoggerTest { } @Test - public void testPostMDCInfoForEventString() { - assertEquals("transactionId", systemOutLogger.postMDCInfoForEvent("transactionId")); + public void testPostMdcInfoForEventString() { + assertEquals("transactionId", systemOutLogger.postMdcInfoForEvent("transactionId")); } @Test @@ -525,13 +526,13 @@ public class SystemOutLoggerTest { } @Test - public void testPostMDCInfoForTriggeredRule() { + public void testPostMdcInfoForTriggeredRule() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); PrintStream old = System.out; try { System.setOut(ps); - systemOutLogger.postMDCInfoForTriggeredRule("transactionId"); + systemOutLogger.postMdcInfoForTriggeredRule("transactionId"); assertTrue(baos.toString(), baos.toString().contains("transactionId")); } finally { System.out.flush(); @@ -540,13 +541,13 @@ public class SystemOutLoggerTest { } @Test - public void testPostMDCInfoForEventObject() { + public void testPostMdcInfoForEventObject() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); PrintStream old = System.out; try { System.setOut(ps); - systemOutLogger.postMDCInfoForEvent(1); + systemOutLogger.postMdcInfoForEvent(1); assertTrue(baos.toString(), baos.toString().contains("1")); } finally { System.out.flush(); 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 deleted file mode 100644 index 94bfbb74..00000000 --- a/common-logging/src/test/java/org/onap/policy/common/logging/util/TestUtils.java +++ /dev/null @@ -1,77 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP-Logging - * ================================================================================ - * Copyright (C) 2018 Ericsson. 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. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * 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 { - - /** - * 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); - - final Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); - - field.set(object, newValue); - } catch (final Exception e) { - fail(e.toString()); - } - } - - /** - * 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); - - final Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); - modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); - - field.set(null, newValue); - } catch (final Exception e) { - fail(e.toString()); - } - } - -} -- cgit 1.2.3-korg