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 +- 22 files changed, 1246 insertions(+), 1341 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 (limited to 'common-logging/src/main') 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 + } } -- cgit 1.2.3-korg