diff options
Diffstat (limited to 'common-logging/src/main/java/org/openecomp')
25 files changed, 5613 insertions, 0 deletions
diff --git a/common-logging/src/main/java/org/openecomp/policy/common/logging/ECOMPLoggingContext.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/ECOMPLoggingContext.java new file mode 100644 index 00000000..71e75a11 --- /dev/null +++ b/common-logging/src/main/java/org/openecomp/policy/common/logging/ECOMPLoggingContext.java @@ -0,0 +1,530 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-Logging + * ================================================================================ + * Copyright (C) 2017 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.openecomp.policy.common.logging; + +//import static org.openecomp.policy.common.logging.eelf.Configuration.TRANSACTION_BEGIN_TIME_STAMP; +//import static org.openecomp.policy.common.logging.eelf.Configuration.TRANSACTION_ELAPSED_TIME; +//import static org.openecomp.policy.common.logging.eelf.Configuration.TRANSACTION_END_TIME_STAMP; + +import static com.att.eelf.configuration.Configuration.MDC_ALERT_SEVERITY; +import static com.att.eelf.configuration.Configuration.MDC_INSTANCE_UUID; + +import java.text.SimpleDateFormat; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.Date; +import java.util.Properties; +import java.util.Timer; +import java.util.TimerTask; + +import org.slf4j.MDC; + +import org.openecomp.policy.common.logging.nsa.LoggingContextFactory; +import org.openecomp.policy.common.logging.nsa.SharedLoggingContext; + +/** + * A facade over the org.openecomp.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 ECOMPLoggingContext constructor that takes another ECOMPLoggingContext 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 "ECOMP 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 ECOMPLoggingContext { + + 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 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 LoggingContextFactory.Builder loggingContextBuilder = new LoggingContextFactory.Builder(); + + protected SharedLoggingContext context = null; +// private long transactionStartTime = 0; + private Instant transactionStartTime; + private Instant metricStartTime; + + /** + * Create a new ECOMPLoggingContext with no base context. + */ + public ECOMPLoggingContext() { + context = (SharedLoggingContext) loggingContextBuilder.forSharing().build(); + } + + /** + * Create a new ECOMPLoggingContext 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 + */ + public ECOMPLoggingContext(ECOMPLoggingContext 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; + } + + /** + * Indicate the start of transaction processing. The current system time + * will be recorded for use by <code>transactionEnded()</code> to calculate + * the duration of the transaction. + */ + public void transactionStarted() { +// transactionStartTime = System.currentTimeMillis(); + transactionStartTime = Instant.now(); + setTransactionBeginTimestamp(transactionStartTime); + } + + /** + * Indicate the end of transaction processing. The difference between the + * current system time and the time recorded by <code>transactionStarted()</code> + * will be recorded in the data item with key "TransactionElapsedTime". + */ + public void transactionEnded() { + Instant transactionEndTime = Instant.now(); + setTransactionEndTimestamp(transactionEndTime); + setTransactionElapsedTime(transactionEndTime); + } + + /** + * Indicate the start of metric processing. The current system time + * will be recorded for use by <code>metricEnded()</code> to calculate + * the duration of the metric. + */ + public void metricStarted() { +// transactionStartTime = System.currentTimeMillis(); + metricStartTime = Instant.now(); + setMetricBeginTimestamp(metricStartTime); + } + + /** + * Indicate the end of metric processing. The difference between the + * current system time and the time recorded by <code>metricStarted()</code> + * will be recorded in the data item with key "MetricElapsedTime". + */ + public void metricEnded() { + Instant metricEndTime = Instant.now(); + setMetricEndTimestamp(metricEndTime); + setMetricElapsedTime(metricEndTime); + } + + + /** + * Set the value for the data item with key "requestId" + * + * @param id + */ + 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, ""); + } + + /** + * Set the value for the data item with key "serviceInstanceId" + * + * @param id + */ + 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, ""); + } + + /** + * 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 + */ + 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, ""); + } + + /** + * Set the value for the data item with key "serverName" + * + * @param id + */ + 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, ""); + } + + /** + * Set the value for the data item with key "serviceName" + * + * @param id + */ + 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, ""); + } + + /** + * Set the value for the data item with key "instanceUuid" + * + * @param id + */ + 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, ""); + } + + /** + * Set the value for the data item with key "severity" + * + * @param id + */ + 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, ""); + } + + /** + * Set the value for the data item with key "serverIp" + * + * @param id + */ + 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, ""); + } + + /** + * Set the value for the data item with key "server" + * + * @param id + */ + 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, ""); + } + + /** + * Set the value for the data item with key "clientIp" + * + * @param id + */ + 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, ""); + } + + /** + * 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 id + */ + 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, ""); + } + + /** + * Set the value for the data item with key "timer". + * An alternative to calling this method directly is to call + * <code>transactionStarted()</code> at the start of transaction + * processing and <code>transactionEnded()</code> at the end, + * which will compute the time difference in milliseconds + * and store the result as the "timer" value. + * + * @param id + */ +// public void setTimer(Long timer) { +// context.put(TIMER, timer); +// } + +// public void setTimer(Long elapsedtime) { +// String unit = " milliseconds"; +// context.put(TRANSACTION_ELAPSED_TIME, elapsedtime + unit); +// } + + /** + * Get the value for the data item with key "timer" + * @return current value, or 0 if not set + */ +// public long getTimer() { +// return context.get(TRANSACTION_ELAPSED_TIME, 0); +// } + + /** + * Set the value for the data item with key "TransactionBeginTimestamp" + * + * @param id + */ + public void setTransactionBeginTimestamp(Instant transactionStartTime) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+00:00"); + + String formatedTime = sdf.format(Date.from(transactionStartTime)); + context.put(TRANSACTION_BEGIN_TIME_STAMP, formatedTime ); + } + + /** + * 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, 0); + } + + /** + * Set the value for the data item with key "TransactionEndTimestamp" + * + * @param id + */ + public void setTransactionEndTimestamp(Instant transactionEndTime) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+00:00"); + + String formatedTime = sdf.format(Date.from(transactionEndTime)); + context.put(TRANSACTION_END_TIME_STAMP, formatedTime ); + } + + /** + * 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, 0); + } + + /** + * Set the value for the data item with key "TransactionElapsedTime". + * An alternative to calling this method directly is to call + * <code>transactionStarted()</code> at the start of transaction + * processing and <code>transactionEnded()</code> at the end, + * which will compute the time difference in milliseconds + * and store the result as the "ns" value. + * + * @param id + */ + + public void setTransactionElapsedTime(Instant transactionEndTime) { + long ns = Duration.between(transactionStartTime, transactionEndTime).getSeconds(); + String unit = " Seconds"; + if(ns == 1){ + unit = " Second"; + } + + if(ns < 1){ + ns = Duration.between(transactionStartTime, transactionEndTime).toMillis(); + unit = " milliseconds"; + } + context.put(TRANSACTION_ELAPSED_TIME, ns + unit); + } + + /** + * 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, 0); + } + + /** + * Set the value for the data item with key "MetricBeginTimestamp" + * + * @param id + */ + public void setMetricBeginTimestamp(Instant metricStartTime) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+00:00"); + + String formatedTime = sdf.format(Date.from(metricStartTime)); + context.put(METRIC_BEGIN_TIME_STAMP, formatedTime ); + } + + /** + * 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, 0); + } + + /** + * Set the value for the data item with key "MetricEndTimestamp" + * + * @param id + */ + public void setMetricEndTimestamp(Instant metricEndTime) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+00:00"); + + String formatedTime = sdf.format(Date.from(metricEndTime)); + context.put(METRIC_END_TIME_STAMP, formatedTime ); + } + + /** + * 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, 0); + } + + /** + * Set the value for the data item with key "MetricElapsedTime". + * An alternative to calling this method directly is to call + * <code>metricStarted()</code> at the start of metric + * processing and <code>metricEnded()</code> at the end, + * which will compute the time difference in milliseconds + * and store the result as the "ns" value. + * + * @param id + */ + + public void setMetricElapsedTime(Instant metricEndTime) { + long ns = Duration.between(metricStartTime, metricEndTime).getSeconds(); + String unit = " Seconds"; + if(ns == 1){ + unit = " Second"; + } + + if(ns < 1){ + ns = Duration.between(metricStartTime, metricEndTime).toMillis(); + unit = " milliseconds"; + } + context.put(METRIC_ELAPSED_TIME, ns + unit); + } + + /** + * 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, 0); + } + +} diff --git a/common-logging/src/main/java/org/openecomp/policy/common/logging/ECOMPLoggingUtils.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/ECOMPLoggingUtils.java new file mode 100644 index 00000000..5e6aa909 --- /dev/null +++ b/common-logging/src/main/java/org/openecomp/policy/common/logging/ECOMPLoggingUtils.java @@ -0,0 +1,52 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-Logging + * ================================================================================ + * Copyright (C) 2017 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.openecomp.policy.common.logging; + +import javax.servlet.http.HttpServletRequest; + +public class ECOMPLoggingUtils { + + public static ECOMPLoggingContext getLoggingContextForRequest(HttpServletRequest request, + ECOMPLoggingContext baseContext) + { + ECOMPLoggingContext requestContext = new ECOMPLoggingContext(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 + 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/openecomp/policy/common/logging/eelf/Configuration.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/Configuration.java new file mode 100644 index 00000000..a2a0b783 --- /dev/null +++ b/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/Configuration.java @@ -0,0 +1,91 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-Logging + * ================================================================================ + * Copyright (C) 2017 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.openecomp.policy.common.logging.eelf; + + +public interface Configuration extends com.att.eelf.configuration.Configuration{ + + /** + * The Date-time of the start of a transaction + */ + public String BEGIN_TIME_STAMP = "BeginTimestamp"; + + /** + * The Date-time of the end of transaction + */ + public String END_TIME_STAMP = "EndTimestamp"; + + /** + * Externally advertised API invoked by clients of this component + */ + public String SERVICE_NAME = "ServiceName"; + + /** + * Client or user invoking the API + */ + public String PARTNER_NAME = "PartnerName"; + + /** + * High level success or failure (COMPLETE or ERROR) + */ + public String STATUS_CODE = "StatusCode"; + + /** + * Application specific response code + */ + public String RESPONSE_CODE = "ResponseCode"; + + /** + * Human readable description of the application specific response code + */ + public String RESPONSE_DESCRIPTION = "ResponseDescription"; + + /** + * Externally advertised API invoked by clients of this component + */ + public String ELAPSED_TIME = "ElapsedTime"; + + /** + * High level failure (ERROR) + */ + public String ERROR_CATEGORY = "ErrorCategory"; + + /** + * Error Code + */ + public String ERROR_CODE = "ErrorCode"; + + /** + * Error Description + */ + public String ERROR_DESCRIPTION = "ErrorDesciption"; + + /** + * Class name + */ + public String CLASS_NAME = "ClassName"; + + /** + * Server name + */ + public String SERVER_NAME = "ServerName"; + +} diff --git a/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/DroolsPDPMDCInfo.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/DroolsPDPMDCInfo.java new file mode 100644 index 00000000..ad502475 --- /dev/null +++ b/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/DroolsPDPMDCInfo.java @@ -0,0 +1,53 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-Logging + * ================================================================================ + * Copyright (C) 2017 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.openecomp.policy.common.logging.eelf; + +import java.util.concurrent.ConcurrentHashMap; + +public class DroolsPDPMDCInfo implements MDCInfo{ + + private static ConcurrentHashMap<String, String> mdcMap = new ConcurrentHashMap<String, String>(); + + static { + + mdcMap.put(org.openecomp.policy.common.logging.eelf.Configuration.MDC_REMOTE_HOST, ""); + mdcMap.put(org.openecomp.policy.common.logging.eelf.Configuration.MDC_SERVICE_NAME, "Policy.droolsPdp"); + mdcMap.put(org.openecomp.policy.common.logging.eelf.Configuration.MDC_SERVICE_INSTANCE_ID, "Policy.droolsPdp.event"); + mdcMap.put(org.openecomp.policy.common.logging.eelf.Configuration.MDC_INSTANCE_UUID, ""); + mdcMap.put(org.openecomp.policy.common.logging.eelf.Configuration.MDC_ALERT_SEVERITY, ""); + mdcMap.put(org.openecomp.policy.common.logging.eelf.Configuration.PARTNER_NAME, "N/A"); + mdcMap.put(org.openecomp.policy.common.logging.eelf.Configuration.STATUS_CODE, "N/A"); + mdcMap.put(org.openecomp.policy.common.logging.eelf.Configuration.RESPONSE_CODE, "N/A"); + mdcMap.put(org.openecomp.policy.common.logging.eelf.Configuration.RESPONSE_DESCRIPTION, "N/A"); + + } + + @Override + /** + * @return the instance of ConcurrentHashMap + */ + public ConcurrentHashMap<String, String> getMDCInfo() { + + return mdcMap; + } + + +} diff --git a/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/ErrorCodeMap.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/ErrorCodeMap.java new file mode 100644 index 00000000..4e4457d0 --- /dev/null +++ b/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/ErrorCodeMap.java @@ -0,0 +1,112 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-Logging + * ================================================================================ + * Copyright (C) 2017 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.openecomp.policy.common.logging.eelf; + +import java.util.HashMap; +import java.util.Map; + +/** + * + * ErrorCodeMap contains a HashMap of ErrorCodeInfo (error code and error description) + * + */ +public class ErrorCodeMap { + + + public static HashMap<MessageCodes, ErrorCodeInfo> hm = new HashMap(); + + private static String ERROR_PERMISSIONS = "POLICY-100E"; + private static String ERROR_PERMISSIONS_DESCRIPTION = "This is a Permissions Error. Please check the error message for detail information"; + + private static String ERROR_SCHEMA_INVALID = "POLICY-400E"; + private static String ERROR_SCHEMA_INVALID_DESCRIPTION = "This is an Invalid Schema Error. Please check the error message for detail information"; + + private static String UPDATE_ERROR = "POLICY-502E"; + private static String UPDATE_ERROR_DESCRIPTION = "This is an updating error. Please check the error message for detail information"; + + private static String EXCEPTION_ERROR_CODE = "POLICY-503E"; + private static String EXCEPTION_ERROR_DESCRIPTION = "This is an exception error message during the process. Please check the error message for detail information"; + + private static String MISS_PROPERTY_ERROR = "POLICY-504E"; + private static String MISS_PROPERTY_ERROR_DESCRIPTION = "This is an error of missing properties. Please check the error message for detail information"; + + private static String GENERAL_ERROR_CODE = "POLICY-515E"; + private static String GENERAL_ERROR_DESCRIPTION = "This is a general error message during the process. Please check the error message for detail information"; + + private static String ERROR_SYSTEM_ERROR = "POLICY-516E"; + private static String ERROR_SYSTEM_ERROR_DESCRIPTION = "This is a System Error. Please check the error message for detail information"; + + private static String ERROR_DATA_ISSUE = "POLICY-517E"; + private static String ERROR_DATA_ISSUE_DESCRIPTION = "This is a Data Issue Error. Please check the error message for detail information"; + + private static String ERROR_PROCESS_FLOW = "POLICY-518E"; + private static String ERROR_PROCESS_FLOW_DESCRIPTION = "This is a Process Flow Error. Please check the error message for detail information"; + + private static String ERROR_UNKNOWN = "POLICY-519E"; + private static String ERROR_UNKNOWN_DESCRIPTION = "This is an Unknown Error. Please check the error message for detail information"; + + private static String ERROR_AUDIT = "POLICY-520E"; + private static String ERROR_AUDIT_DESCRIPTION = "This is an audit Error. Please check the error message for detail information"; + + static { + hm.put(MessageCodes.EXCEPTION_ERROR, new ErrorCodeInfo(EXCEPTION_ERROR_CODE, EXCEPTION_ERROR_DESCRIPTION)); + hm.put(MessageCodes.GENERAL_ERROR, new ErrorCodeInfo(GENERAL_ERROR_CODE, GENERAL_ERROR_DESCRIPTION)); + hm.put(MessageCodes.MISS_PROPERTY_ERROR, new ErrorCodeInfo(MISS_PROPERTY_ERROR, MISS_PROPERTY_ERROR_DESCRIPTION)); + hm.put(MessageCodes.UPDATE_ERROR, new ErrorCodeInfo(UPDATE_ERROR, UPDATE_ERROR_DESCRIPTION)); + hm.put(MessageCodes.ERROR_SYSTEM_ERROR, new ErrorCodeInfo(ERROR_SYSTEM_ERROR, ERROR_SYSTEM_ERROR_DESCRIPTION)); + hm.put(MessageCodes.ERROR_DATA_ISSUE, new ErrorCodeInfo(ERROR_DATA_ISSUE, ERROR_DATA_ISSUE_DESCRIPTION)); + hm.put(MessageCodes.ERROR_PERMISSIONS, new ErrorCodeInfo(ERROR_PERMISSIONS, ERROR_PERMISSIONS_DESCRIPTION)); + hm.put(MessageCodes.ERROR_DATA_ISSUE, new ErrorCodeInfo(ERROR_DATA_ISSUE, ERROR_DATA_ISSUE_DESCRIPTION)); + hm.put(MessageCodes.ERROR_PROCESS_FLOW, new ErrorCodeInfo(ERROR_PROCESS_FLOW, ERROR_PROCESS_FLOW_DESCRIPTION)); + hm.put(MessageCodes.ERROR_SCHEMA_INVALID, new ErrorCodeInfo(ERROR_SCHEMA_INVALID, ERROR_SCHEMA_INVALID_DESCRIPTION)); + hm.put(MessageCodes.ERROR_UNKNOWN, new ErrorCodeInfo(ERROR_UNKNOWN, ERROR_UNKNOWN_DESCRIPTION)); + hm.put(MessageCodes.ERROR_AUDIT, new ErrorCodeInfo(ERROR_AUDIT, ERROR_AUDIT_DESCRIPTION)); + } + + static class ErrorCodeInfo { + + private String errorCode; + private String errorDesc; + + public ErrorCodeInfo(String errorCode, String errorDesc){ + this.errorCode = errorCode; + this.errorDesc = errorDesc; + } + + public String getErrorCode() { + return errorCode; + } + + public void setErrorCode(String errorCode) { + this.errorCode = errorCode; + } + + public String getErrorDesc() { + return errorDesc; + } + + public void setErrorDesc(String errorDesc) { + this.errorDesc = errorDesc; + } + + } + +} diff --git a/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/EventData.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/EventData.java new file mode 100644 index 00000000..549651fb --- /dev/null +++ b/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/EventData.java @@ -0,0 +1,93 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-Logging + * ================================================================================ + * Copyright (C) 2017 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.openecomp.policy.common.logging.eelf; + +import java.time.Instant; + +import javax.swing.text.html.parser.Entity; + +/** + * + * EventData can be used for logging a rule event. + * + */ +public class EventData { + + private String requestID = null; + private Instant startTime = null; + private Instant endTime = null; + + public EventData() { + + } + + public EventData(String requestID, Instant startTime, Instant endTime) { + + this.requestID = requestID; + this.startTime = startTime; + this.endTime = endTime; + } + + public String getRequestID() { + return requestID; + } + + public void setRequestID(String requestID) { + this.requestID = requestID; + } + + public Instant getStartTime() { + return startTime; + } + + public void setStartTime(Instant startTime) { + this.startTime = startTime; + } + + public Instant getEndTime() { + return endTime; + } + + public void setEndTime(Instant endTime) { + this.endTime = endTime; + } + + public String toString(){ + return requestID + " Starting Time : " + this.startTime + " Ending Time : " + this.endTime; + } + @Override + public int hashCode(){ + final int prime =31; + int result =1; + result = prime * result +((requestID == null) ? 0: requestID.hashCode()); + return result; + } + @Override + public boolean equals(Object obj){ + + String requestId = (String) obj; + if(requestID != null && requestID.equals(requestId)){ + return true; + } + return false; + } + +} diff --git a/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/EventTrackInfo.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/EventTrackInfo.java new file mode 100644 index 00000000..c6ed63d4 --- /dev/null +++ b/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/EventTrackInfo.java @@ -0,0 +1,90 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-Logging + * ================================================================================ + * Copyright (C) 2017 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.openecomp.policy.common.logging.eelf; + +import java.io.IOException; +import java.time.Instant; +import java.util.Properties; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +import org.openecomp.policy.common.logging.flexlogger.PropertyUtil; + +/** + * + * EventTrackInfo contains a ConcurrentHashMap of EventData + * + */ +public class EventTrackInfo { + + private ConcurrentHashMap<String, EventData> eventInfo = null; + + public EventTrackInfo() { + /* + * An initial capacity of 16 ensures the number of elements before resizing happens + * Load factor of 0,9 ensures a dense packaging inside ConcurrentHashMap which will optimize memory use + * ConcurencyLevel set to 1 will ensure that only one shard is created and maintained + */ + eventInfo = new ConcurrentHashMap<String, EventData>(16, 0.9f, 1); + } + + /** + * Returns an instance of EventData associated to this requestID + * @param requestID + * @return EventData + */ + public EventData getEventDataByRequestID(String requestID){ + return eventInfo.get(requestID); + } + + /** + * Stores an EventData object in a ConcurrentHashMap using its requestID as key. + * @param event + */ + public void storeEventData(EventData event){ + + if(event == null || event.getRequestID() == null || event.getRequestID().isEmpty()){ + return; + } + //in case override the start time, check the original event was already stored or not + if(!eventInfo.containsKey(event.getRequestID())){ + eventInfo.put(event.getRequestID(), event); + } + } + + /** + * Removes an EventData object from a ConcurrentHashMap using the eventId as key. + * @param eventId + */ + public void remove(String eventId){ + if(eventInfo != null){ + eventInfo.remove(eventId); + } + } + + /** + * Returns a ConcurrentHashMap of EventData + */ + public ConcurrentHashMap<String, EventData> getEventInfo() { + return eventInfo; + } + +} diff --git a/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/EventTrackInfoHandler.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/EventTrackInfoHandler.java new file mode 100644 index 00000000..a947ed01 --- /dev/null +++ b/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/EventTrackInfoHandler.java @@ -0,0 +1,109 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-Logging + * ================================================================================ + * Copyright (C) 2017 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.openecomp.policy.common.logging.eelf; + +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.Timer; +import java.util.TimerTask; + +/** + * + * EventTrackInfoHandler is the handler of clean up all expired event objcts + * + */ +public class EventTrackInfoHandler extends TimerTask { + + String className = this.getClass().getSimpleName(); + + @Override + public void run() { + + PolicyLogger.info(className + + " Release expired event records start..."); + + CleanUp(); + + PolicyLogger.info(className + " Release expired event records done"); + } + + /** + * Removes all expired event objects from the ConcurrentHashMap of EventData + */ + private void CleanUp() { + + if (PolicyLogger.getEventTracker() == null + || PolicyLogger.getEventTracker().getEventInfo() == null + || PolicyLogger.getEventTracker().getEventInfo().isEmpty()) { + return; + } + + Instant startTime = null; + long ns = 0; + + ArrayList<String> expiredEvents = null; + + for (String key: PolicyLogger.getEventTracker().getEventInfo().keySet()) { + EventData event = PolicyLogger.getEventTracker().getEventInfo().get(key); + startTime = event.getStartTime(); + ns = Duration.between(startTime, Instant.now()).getSeconds(); + + PolicyLogger.info(className + + " duration time : " + ns); + + PolicyLogger.info(className + + " PolicyLogger.EXPIRED_TIME : " + PolicyLogger.EXPIRED_TIME); + + // if longer than EXPIRED_TIME, remove the object + + if (ns > PolicyLogger.EXPIRED_TIME){ + if (expiredEvents == null) { + expiredEvents = new ArrayList<String>(); + } + expiredEvents.add(key); + + PolicyLogger.info(className + + " add expired event request ID: " + + event.getRequestID()); + } + } + + synchronized (PolicyLogger.getEventTracker().getEventInfo()) { + if (expiredEvents != null) { + for (String expiredKey : expiredEvents) { + PolicyLogger.getEventTracker().getEventInfo() + .remove(expiredKey); + System.out.println(className + + " removed expired event request ID: " + + expiredKey); + PolicyLogger.info(className + + " removed expired event request ID: " + + expiredKey); + } + } + + } + + } + +} diff --git a/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/MDCInfo.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/MDCInfo.java new file mode 100644 index 00000000..6b5e395f --- /dev/null +++ b/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/MDCInfo.java @@ -0,0 +1,35 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-Logging + * ================================================================================ + * Copyright (C) 2017 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.openecomp.policy.common.logging.eelf; + +import java.util.concurrent.ConcurrentHashMap; + +/** + * + * Interface needs to be implemented by DroolsPDPMDCInfo + * + */ + +public interface MDCInfo { + + public ConcurrentHashMap<String, String> getMDCInfo(); + +} diff --git a/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/MessageCodes.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/MessageCodes.java new file mode 100644 index 00000000..6f1437eb --- /dev/null +++ b/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/MessageCodes.java @@ -0,0 +1,163 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-Logging + * ================================================================================ + * Copyright (C) 2017 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.openecomp.policy.common.logging.eelf; + +import com.att.eelf.i18n.EELFResolvableErrorEnum; +import com.att.eelf.i18n.EELFResourceManager; + +/** + * + * MessageCodes contains all the messagge codes for EELF logging messages + * + */ +public enum MessageCodes implements EELFResolvableErrorEnum { + // Below is a list of Error Messages taken from com.att.research.xacml.api XACMLErrorConstants + // found under: policy-engine\XACML\src\main\java\com\att\research\xacml\api\XACMLErrorConstants.java + + ERROR_PERMISSIONS, + + ERROR_SYSTEM_ERROR, + + ERROR_DATA_ISSUE, + + ERROR_SCHEMA_INVALID, + + ERROR_PROCESS_FLOW, + + ERROR_UNKNOWN, + + ERROR_AUDIT, + + // Above is a list of Error Messages taken from com.att.research.xacml.api XACMLErrorConstants + // found under: policy-engine\XACML\src\main\java\com\att\research\xacml\api\XACMLErrorConstants.java + + //----------------------5000-5099 Business/Flow Processing Related --------------------/ + + BAD_TYPE_WARNING, + + GENERAL_INFO, + + GENERAL_WARNING, + + MISS_PROPERTY_ERROR, + + EXCEPTION_ERROR, + + MISS_PROPERTY_INFO, + + RULE_AUDIT_EXEC_INFO, + + RULE_AUDIT_BEGIN_INFO, + + RULE_AUDIT_END_INFO, + + RULE_AUDIT_START_END_INFO, + + RULE_METRICS_INFO, + + UEB_AUDIT_EXEC_INFO, + + UEB_AUDIT_BEGIN_INFO, + + UEB_AUDIT_END_INFO, + + UPDATE_ERROR, + + GENERAL_ERROR, + + //----------------------New enums should be added above this line ------------------------------------------------------------------/ + + //--------------------- The enums below are old code. They should not be used since 1607 release and eventually will be removed -----/ + /** + * Application message which requires no arguments + */ + MESSAGE_SAMPLE_NOARGS, + + /** + * Application message which requires one argument {0} + */ + MESSAGE_SAMPLE_ONEARGUMENT, + + /** + * Audit message which requires one argument {0} + */ + AUDIT_MESSAGE_ONEARGUMENT, + + /** + * Error message which requires one argument {0} + */ + ERROR_MESSAGE_ONEARGUMENT, + + /** + * Metrics message which requires one argument {0} + */ + METRICS_MESSAGE_ONEARGUMENT, + + /** + * Debug message which requires one argument {0} + */ + DEBUG_MESSAGE_ONEARGUMENT, + + /** + * Application message which requires two argument {0} and another argument {1} + */ + MESSAGE_SAMPLE_TWOARGUMENTS, + + /** + * Sample error exception + */ + MESSAGE_SAMPLE_EXCEPTION, + + /** + * Sample warning message + */ + MESSAGE_WARNING_SAMPLE, + + /** + * Sample exception in method {0} + */ + MESSAGE_SAMPLE_EXCEPTION_ONEARGUMENT, + + /** + * Sample trace message + */ + MESSAGE_TRACE_SAMPLE, + + /** + * Sample error message + */ + MESSAGE_ERROR_SAMPLE; + + + /** + * Static initializer to ensure the resource bundles for this class are loaded... + * Here this application loads messages from three bundles + */ + static { + EELFResourceManager.loadMessageBundle("org/openecomp/policy/common/logging/eelf/Resources"); + String id = EELFResourceManager.getIdentifier(RULE_AUDIT_EXEC_INFO); + String value = EELFResourceManager.getMessage(RULE_AUDIT_EXEC_INFO); + + System.out.println("*********************** " + id); + System.out.println("*********************** " + value); + + } +} diff --git a/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/PolicyLogger.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/PolicyLogger.java new file mode 100644 index 00000000..624ba580 --- /dev/null +++ b/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/PolicyLogger.java @@ -0,0 +1,1438 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-Logging + * ================================================================================ + * Copyright (C) 2017 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.openecomp.policy.common.logging.eelf; + +import org.slf4j.MDC; + +import static org.openecomp.policy.common.logging.eelf.Configuration.*; + +import org.openecomp.policy.common.logging.flexlogger.LoggerType; +import org.openecomp.policy.common.logging.eelf.PolicyLogger; +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; +import java.net.UnknownHostException; +import java.text.SimpleDateFormat; +import java.time.Duration; +import java.time.Instant; +import java.util.Date; +import java.util.Iterator; +import java.util.Properties; +import java.util.Timer; +import java.util.TimerTask; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +/** + * + * PolicyLogger contains all the static methods for EELF logging + * + */ +public class PolicyLogger { + + private static EELFLogger applicationLogger = EELFManager.getInstance() + .getApplicationLogger(); + + private static EELFLogger errorLogger = EELFManager.getInstance() + .getErrorLogger(); + + private static EELFLogger metricsLogger = EELFManager.getInstance() + .getMetricsLogger(); + + private static EELFLogger auditLogger = EELFManager.getInstance() + .getAuditLogger(); + + private static EELFLogger debugLogger = EELFManager.getInstance() + .getDebugLogger(); + + private static EventTrackInfo eventTracker = new EventTrackInfo(); + + private static String hostName = null; + private static String hostAddress = null; + private static String component = null; + + private static TimerTask ttrcker = null; + private static boolean isEventTrackerRunning = false; + private static Timer timer = null; + + //Default:Timer initial delay and the delay between in milliseconds before task is to be execute + private static int TIMER_DELAY_TIME = 1000; + + //Default:Timer scheduleAtFixedRate period - time in milliseconds between successive task executions + private static int CHECK_INTERVAL = 30 * 1000; + + //Default:longest time an event info can be stored in the concurrentHashMap for logging - in seconds + static int EXPIRED_TIME = 60*60*1000*24; //one day + + //Default:the size of the concurrentHashMap which stores the event starting time - when its size reaches this limit, the Timer get executed + private static int CONCURRENTHASHMAP_LIMIT = 5000; + + //Default:the size of the concurrentHashMap which stores the event starting time - when its size drops to this point, stop the Timer + private static int STOP_CHECK_POINT = 2500; + + private static boolean isOverrideLogbackLevel = false; + + public static Level DEBUG_LEVEL = Level.INFO; + public static Level AUDIT_LEVEL = Level.INFO; + public static Level METRICS_LEVEL = Level.INFO; + public static Level ERROR_LEVEL = Level.ERROR; + public static String CLASS_NAME = "ClassName"; + + + static{ + if (hostName == null || hostAddress == null) { + try { + hostName = InetAddress.getLocalHost().getHostName(); + hostAddress = InetAddress.getLocalHost().getHostAddress(); + } catch (UnknownHostException e) { + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyLogger", "UnknownHostException"); + } + } + } + + /** + * Populates MDC info + * @param transId + * @return String + */ + public static String postMDCInfoForEvent(String transId) { + MDC.clear(); + + if(transId == null || transId.isEmpty()){ + transId = UUID.randomUUID().toString(); + } + + if(component != null && component.equalsIgnoreCase("DROOLS")){ + return postMDCInfoForEvent(transId, new DroolsPDPMDCInfo()); + } + + MDC.put(MDC_REMOTE_HOST, ""); + MDC.put(MDC_KEY_REQUEST_ID, transId); + 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, "PolicyLogger"); + } + Instant startTime = Instant.now(); + Instant endTime = Instant.now(); + long ns = Duration.between(startTime, endTime).getSeconds(); + String unit = " Seconds"; + if(ns == 1){ + unit = " Second"; + } + + if(ns < 1){ + ns = Duration.between(startTime, endTime).toMillis(); + unit = " milliseconds"; + } + MDC.put(MDC_INSTANCE_UUID, ""); + MDC.put(MDC_ALERT_SEVERITY, ""); + + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+00:00"); + + 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, ns + unit); + + MDC.put(PARTNER_NAME, "N/A"); + + MDC.put(STATUS_CODE, "N/A"); + MDC.put(RESPONSE_CODE, "N/A"); + MDC.put(RESPONSE_DESCRIPTION, "N/A"); + + + return transId; + + } + + /** + * Populate MDC Info using the passed in mdcInfo + * @param transId + * @param mdcInfo + * @return String + */ + private static String postMDCInfoForEvent(String transId, MDCInfo mdcInfo ) { + + MDC.put(MDC_KEY_REQUEST_ID, transId); + if(mdcInfo != null && mdcInfo.getMDCInfo() != null && !mdcInfo.getMDCInfo().isEmpty()){ + + ConcurrentHashMap<String, String> mdcMap = mdcInfo.getMDCInfo(); + Iterator<String> keyIterator = mdcMap.keySet().iterator(); + String key = ""; + + while(keyIterator.hasNext()){ + key = keyIterator.next(); + MDC.put(key, mdcMap.get(key)); + } + } + + try { + MDC.put(MDC_SERVER_FQDN, hostName); + MDC.put(MDC_SERVER_IP_ADDRESS, hostAddress); + } catch (Exception e) { + errorLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyLogger"); + } + Instant startTime = Instant.now(); + Instant endTime = Instant.now(); + long ns = Duration.between(startTime, endTime).getSeconds(); + String unit = " Seconds"; + if(ns == 1){ + unit = " Second"; + } + + if(ns < 1){ + ns = Duration.between(startTime, endTime).toMillis(); + unit = " milliseconds"; + } + + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+00:00"); + + 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, ns + unit); + + return transId; + } + + /** + * Set Timestamps for start, end and duration of logging a transaction + */ + private static void seTimeStamps(){ + + Instant startTime = Instant.now(); + Instant endTime = Instant.now(); + long ns = Duration.between(startTime, endTime).getSeconds(); + String unit = " Seconds"; + if(ns == 1){ + unit = " Second"; + } + + if(ns < 1){ + ns = Duration.between(startTime, endTime).toMillis(); + unit = " milliseconds"; + } + MDC.put(MDC_INSTANCE_UUID, ""); + MDC.put(MDC_ALERT_SEVERITY, ""); + + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+00:00"); + + 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, ns + unit); + + MDC.put(PARTNER_NAME, "N/A"); + + MDC.put(STATUS_CODE, "N/A"); + MDC.put(RESPONSE_CODE, "N/A"); + MDC.put(RESPONSE_DESCRIPTION, "N/A"); + + } + + /** + * Sets transaction Id to MDC + * @param transId + */ + public static void setTransId(String transId){ + + MDC.put(MDC_KEY_REQUEST_ID, transId); + } + + /** + * Returns current transaction Id used in MDC + * @return transId + */ + public static String getTransId(){ + + return MDC.get(MDC_KEY_REQUEST_ID); + } + + /** + * Sets transaction Id to MDC + * @param o + */ + public static void postMDCInfoForEvent(Object o){ + postMDCInfoForEvent(""+o); + } + + /** + * Resets transaction Id in MDC for the rule triggered by this event + * @param transId + * @return String + */ + public static String postMDCInfoForTriggeredRule(String transId) { + + MDC.clear(); + + if(transId == null || transId.isEmpty()){ + transId = UUID.randomUUID().toString(); + } + MDC.put(MDC_REMOTE_HOST, ""); + MDC.put(MDC_KEY_REQUEST_ID, transId); + 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, "PolicyLogger"); + } + MDC.put(MDC_INSTANCE_UUID, ""); + MDC.put(MDC_ALERT_SEVERITY, ""); + MDC.put(STATUS_CODE, "N/A"); + + return transId; + + } + + /** + * Resets transaction Id in MDC for the rule triggered by this event + * @param o + */ + public static void postMDCUUIDForTriggeredRule(Object o) { + + postMDCInfoForTriggeredRule("" + o); + + } + + // ************************************************************************************************ + /** + * Records the Info event with String [] arguments + * @param msg + * @param arguments + */ + public static void info(MessageCodes msg, String... arguments) { + MDC.put(CLASS_NAME, ""); + debugLogger.info(msg, arguments); + } + + /** + * Records the Info event with String [] arguments + * @param msg + * @param className + * @param arguments + */ + public static void info(MessageCodes msg, String className, String... arguments) { + MDC.put(CLASS_NAME, className); + debugLogger.info(msg, arguments); + } + + /** + * Records only one String message with its class name + * @param className + * @param arg0 + */ + public static void info( String className, String arg0) { + MDC.put(CLASS_NAME, className); + debugLogger.info(MessageCodes.GENERAL_INFO, arg0); + } + + /** + * Records only one String message without its class name passed in + * @param arg0 + */ + public static void info(String arg0) { + MDC.put(CLASS_NAME, ""); + debugLogger.info(MessageCodes.GENERAL_INFO, arg0); + } + + /** + * Records only one String message + * @param arg0 + */ + public static void info(Object arg0) { + MDC.put(CLASS_NAME, ""); + info(arg0); + } + + /** + * Records a message with passed in message code, Throwable object, a list of string values + * @param msg + * @param arg0 + * @param arguments + */ + public static void info(MessageCodes msg, Throwable arg0, + String... arguments) { + MDC.put(CLASS_NAME, ""); + String arguments2 = getNormalizedStackTrace(arg0, arguments); + debugLogger.info(msg, arguments2); + } + + /** + * Records a message with passed in message code, class name, Throwable object, a list of string values + * @param msg + * @param className + * @param arg0 + * @param arguments + */ + public static void info(MessageCodes msg, String className, Throwable arg0, + String... arguments) { + MDC.put(CLASS_NAME, className); + String arguments2 = getNormalizedStackTrace(arg0, arguments); + debugLogger.info(msg, arguments2); + } + + /** + * Records only one String message with its class name + * @param arg0 log message + * @param className class name + */ + public static void warn( String className, String arg0) { + MDC.put(CLASS_NAME, className); + debugLogger.warn(MessageCodes.GENERAL_INFO, arg0); + } + + /** + * Records only one String message + * @param arg0 + */ + public static void warn(Object arg0) { + MDC.put(CLASS_NAME, ""); + debugLogger.warn(MessageCodes.GENERAL_WARNING, "" + arg0); + } + + /** + * Records only one String message without its class name passed in + * @param arg0 + */ + public static void warn(String arg0) { + MDC.put(CLASS_NAME, ""); + debugLogger.warn(MessageCodes.GENERAL_WARNING, arg0); + } + + /** + * Records a message with passed in message code and a list of string values + * @param msg + * @param arguments + */ + public static void warn(MessageCodes msg, String... arguments) { + MDC.put(CLASS_NAME, ""); + debugLogger.warn(msg, arguments); + } + + /** + * Records a message with passed in message code, class name and a list of string values + * @param msg + * @param className + * @param arguments + */ + public static void warn(MessageCodes msg, String className, String... arguments) { + MDC.put(CLASS_NAME, className); + debugLogger.warn(msg, arguments); + } + + /** + * Records a message with passed in message code, Throwable object, a list of string values + * @param msg + * @param arg0 + * @param arguments + */ + public static void warn(MessageCodes msg, Throwable arg0, + String... arguments) { + MDC.put(CLASS_NAME, ""); + String arguments2 = getNormalizedStackTrace(arg0, arguments); + debugLogger.warn(msg, arguments2); + } + + /** + * Records a message with passed in message code, Throwable object, a list of string values + * @param msg + * @param className + * @param arg0 + * @param arguments + */ + public static void warn(MessageCodes msg, String className, Throwable arg0, + String... arguments) { + MDC.put(CLASS_NAME, className); + String arguments2 = getNormalizedStackTrace(arg0, arguments); + debugLogger.warn(msg, arguments2); + } + + /** + * Records only one String message with its class name + * @param className class name + * @param arg0 log message + */ + public static void error( String className, String arg0) { + MDC.put(CLASS_NAME, className); + if(ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR) != null){ + MDC.put(ERROR_CODE, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorCode()); + MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorDesc()); + + } + errorLogger.error(MessageCodes.GENERAL_ERROR, arg0); + } + + /** + * Records only one String message + * @param arg0 + */ + public static void error(String arg0) { + MDC.put(CLASS_NAME, ""); + MDC.put(ERROR_CATEGORY, "ERROR"); + + if(ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR) != null){ + MDC.put(ERROR_CODE, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorCode()); + MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorDesc()); + + } + errorLogger.error(MessageCodes.GENERAL_ERROR, arg0); + } + + /** + * Records only one String message + * @param arg0 + */ + public static void error(Object arg0) { + MDC.put(CLASS_NAME, ""); + MDC.put(ERROR_CATEGORY, "ERROR"); + + if(ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR) != null){ + MDC.put(ERROR_CODE, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorCode()); + MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorDesc()); + + } + errorLogger.error(MessageCodes.GENERAL_ERROR, "" + arg0); + } + + /** + * Records a message with passed in message code, Throwable object, a list of string values + * @param msg + * @param arg0 + * @param arguments + */ + public static void error(MessageCodes msg, Throwable arg0, + String... arguments) { + MDC.put(CLASS_NAME, ""); + MDC.put(ERROR_CATEGORY, "ERROR"); + + if(ErrorCodeMap.hm.get(msg) != null){ + MDC.put(ERROR_CODE, ErrorCodeMap.hm.get(msg).getErrorCode()); + MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.hm.get(msg).getErrorDesc()); + + } + String arguments2 = getNormalizedStackTrace(arg0, arguments); + errorLogger.error(msg, arguments2); + } + + /** + * Records a message with passed in message code, class name, Throwable object, a list of string values + * @param msg + * @param className + * @param arg0 + * @param arguments + */ + public static void error(MessageCodes msg, String className, Throwable arg0, + String... arguments) { + MDC.put(CLASS_NAME, className); + MDC.put(ERROR_CATEGORY, "ERROR"); + + if(ErrorCodeMap.hm.get(msg) != null){ + MDC.put(ERROR_CODE, ErrorCodeMap.hm.get(msg).getErrorCode()); + MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.hm.get(msg).getErrorDesc()); + + } + String arguments2 = getNormalizedStackTrace(arg0, arguments); + errorLogger.error(msg, arguments2); + } + + /** + * Records a message with passed in message code and a list of string values + * @param msg + * @param arguments + */ + public static void error(MessageCodes msg, String... arguments) { + MDC.put(CLASS_NAME, ""); + MDC.put(ERROR_CATEGORY, "ERROR"); + + if(ErrorCodeMap.hm.get(msg) != null){ + MDC.put(ERROR_CODE, ErrorCodeMap.hm.get(msg).getErrorCode()); + MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.hm.get(msg).getErrorDesc()); + + } + errorLogger.error(msg, arguments); + } + + /** + * Records a message with passed in message code and a list of string values + * @param msg + * @param arguments + */ + public static void debug(MessageCodes msg, String... arguments) { + MDC.put(CLASS_NAME, ""); + debugLogger.debug(msg, arguments); + } + + /** + * Records only one String message with its class name + * @param className + * @param arg0 + */ + public static void debug( String className, String arg0) { + MDC.put(CLASS_NAME, className); + debugLogger.debug(MessageCodes.GENERAL_INFO, arg0); + } + + /** + * Records only one String message + * @param arg0 + */ + public static void debug(String arg0) { + MDC.put(CLASS_NAME, ""); + debugLogger.debug(arg0); + } + + /** + * Records only one String message + * @param arg0 + */ + public static void debug(Object arg0) { + + MDC.put(CLASS_NAME, ""); + debugLogger.debug("" + arg0); + } + + /** + * Records only one String message with its class name + * @param className + * @param arg0 + */ + public static void audit(String className, Object arg0) { + MDC.put(STATUS_CODE, "N/A"); + MDC.put(CLASS_NAME, className); + auditLogger.info("" + arg0); + } + + /** + * Records only one String message + * @param arg0 + */ + public static void audit(Object arg0) { + MDC.put(STATUS_CODE, "N/A"); + MDC.put(CLASS_NAME, ""); + auditLogger.info("" + arg0); + } + + /** + * Records a message with passed in message code, hrowable object, a list of string values + * @param msg + * @param arg0 + * @param arguments + */ + public static void debug(MessageCodes msg, Throwable arg0, + String... arguments) { + MDC.put(CLASS_NAME, ""); + String arguments2 = getNormalizedStackTrace(arg0, arguments); + errorLogger.error(msg, arguments2); + } + + /** + * Records a message with passed in message code, class name, Throwable object, a list of string values + * @param msg + * @param className + * @param arg0 + * @param arguments + */ + public static void debug(MessageCodes msg, String className, Throwable arg0, + String... arguments) { + MDC.put(CLASS_NAME, className); + String arguments2 = getNormalizedStackTrace(arg0, arguments); + errorLogger.error(msg, arguments2); + } + /** + * returns true for enabled, false for not enabled + */ + public static boolean isDebugEnabled(){ + + return debugLogger.isDebugEnabled(); + } + + /** + * returns true for enabled, false for not enabled + */ + public static boolean isErrorEnabled(){ + + return errorLogger.isErrorEnabled(); + } + + /** + * returns true for enabled, false for not enabled + */ + public static boolean isWarnEnabled(){ + + return debugLogger.isWarnEnabled(); + } + + /** + * returns true for enabled, false for not enabled + */ + public static boolean isInfoEnabled1(){ + + return debugLogger.isInfoEnabled(); + } + + /** + * returns true for enabled, false for not enabled + */ + public static boolean isAuditEnabled(){ + + return debugLogger.isInfoEnabled(); + } + + /** + * returns true for enabled, false for not enabled + */ + public static boolean isInfoEnabled(){ + + return debugLogger.isInfoEnabled(); + } + + /** + * Records only one String message with its class name + * @param className + * @param arg0 + */ + public static void trace( String className, String arg0) { + MDC.put(CLASS_NAME, className); + errorLogger.info(MessageCodes.GENERAL_INFO, arg0); + } + + /** + * Records only one String message + * @param arg0 + */ + public static void trace(Object arg0){ + + MDC.put(CLASS_NAME, ""); + debugLogger.trace(""+arg0); + } + /** + * Records the starting time of the event with its request Id as the key + * @param eventId + */ + public static void recordAuditEventStart(String eventId) { + + MDC.put(STATUS_CODE, "N/A"); + postMDCInfoForEvent(eventId); + + if(eventTracker == null){ + eventTracker = new EventTrackInfo(); + } + EventData event = new EventData(); + event.setRequestID(eventId); + event.setStartTime(Instant.now()); + eventTracker.storeEventData(event); + MDC.put(MDC_KEY_REQUEST_ID, eventId); + debugLogger.info("CONCURRENTHASHMAP_LIMIT : " + CONCURRENTHASHMAP_LIMIT); + //--- Tracking the size of the concurrentHashMap, if it is above limit, keep EventTrack Timer running + int size = eventTracker.getEventInfo().size(); + + debugLogger.info("EventInfo concurrentHashMap Size : " + size + " on " + new Date()); + debugLogger.info("isEventTrackerRunning : " + isEventTrackerRunning); + + if( size >= CONCURRENTHASHMAP_LIMIT){ + + + if(!isEventTrackerRunning){ + + startCleanUp(); + isEventTrackerRunning = true; + } + + }else if( size <= STOP_CHECK_POINT){ + + if(isEventTrackerRunning){ + stopCleanUp(); + } + } + } + + /** + * Records the starting time of the event with its request Id as the key + * @param eventId + */ + public static void recordAuditEventStart(UUID eventId) { + + if(eventId == null){ + return; + } + + if(eventTracker == null){ + eventTracker = new EventTrackInfo(); + } + + recordAuditEventStart(eventId.toString()); + + } + + /** + * Records the ending time of the event with its request Id as the key + * @param eventId + * @param rule + */ + public static void recordAuditEventEnd(String eventId, String rule) { + + if(eventTracker == null){ + return; + } + if(eventId == null){ + return; + } + + creatAuditEventTrackingRecord(eventId, rule, ""); + + } + + /** + * Records the ending time of the event with its request Id as the key + * @param eventId + * @param rule + * @param policyVersion + */ + public static void recordAuditEventEnd(String eventId, String rule , String policyVersion) { + + if(eventTracker == null){ + return; + } + if(eventId == null){ + return; + } + + creatAuditEventTrackingRecord(eventId, rule, policyVersion); + + } + + /** + * Records the ending time of the event with its request Id as the key + * @param eventId + * @param rule + * @param policyVersion + */ + public static void recordAuditEventEnd(UUID eventId, String rule, String policyVersion) { + + if(eventId == null){ + return; + } + + recordAuditEventEnd(eventId.toString(), rule, policyVersion); + + } + + + /** + * Records the ending time of the event with its request Id as the key + * @param eventId + * @param rule + */ + public static void recordAuditEventEnd(UUID eventId, String rule) { + + if(eventId == null){ + return; + } + + recordAuditEventEnd(eventId.toString(), rule); + + } + + /** + * Records the ending time of the event with its request Id as the key + * @param eventId + * @param rule + * @param policyVersion + */ + public static void creatAuditEventTrackingRecord(String eventId, String rule, String policyVersion) { + + if(eventTracker == null){ + return; + } + + EventData event = eventTracker.getEventDataByRequestID(eventId); + + if(event != null){ + Instant endTime = event.getEndTime(); + if(endTime == null){ + endTime = Instant.now(); + } + MDC.put(STATUS_CODE, "COMPLETE"); + recordAuditEventStartToEnd(eventId, rule, event.getStartTime(), endTime, policyVersion); + } + } + + /** + * Records the ending time of the event with its request Id as the key + * @param eventId + * @param rule + */ + public static void creatAuditEventTrackingRecord(UUID eventId, String rule) { + + if(eventId == null){ + return; + } + + if(eventTracker == null){ + return; + } + + EventData event = eventTracker.getEventDataByRequestID(eventId.toString()); + + if(event != null){ + Instant endTime = event.getEndTime(); + if(endTime == null){ + endTime = Instant.now(); + } + + recordAuditEventStartToEnd(eventId.toString(), rule, event.getStartTime(), endTime, "N/A"); + } + } + + public static EventTrackInfo getEventTracker() { + return eventTracker; + } + + /** + * Records the audit with an event starting and ending times + * @param eventId + * @param rule + * @param startTime + * @param endTime + * @param policyVersion + */ + public static void recordAuditEventStartToEnd(String eventId, String rule, Instant startTime, Instant endTime, String policyVersion) { + + if(startTime == null || endTime == null){ + return; + } + String serviceName = MDC.get(MDC_SERVICE_NAME); + if(eventId != null && !eventId.isEmpty()){ + MDC.put(MDC_KEY_REQUEST_ID, eventId); + } + + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+00:00"); + + String formatedTime = sdf.format(Date.from(startTime)); + MDC.put(BEGIN_TIME_STAMP, formatedTime ); + + //set default values for these required fields below, they can be overridden + formatedTime = sdf.format(Date.from(endTime)); + MDC.put(END_TIME_STAMP, formatedTime); + + MDC.put(RESPONSE_CODE, "N/A"); + MDC.put(RESPONSE_DESCRIPTION, "N/A"); + + long ns = Duration.between(startTime, endTime).getSeconds(); + String unit = " Seconds"; + if(ns == 1){ + unit = " Second"; + } + + if(ns < 1){ + ns = Duration.between(startTime, endTime).toMillis(); + unit = " milliseconds"; + } + + MDC.put(ELAPSED_TIME, ns + unit); + + auditLogger.info(MessageCodes.RULE_AUDIT_START_END_INFO, + serviceName, rule, startTime.toString(), endTime.toString(), ns+unit, policyVersion); + + //--- remove the record from the concurrentHashMap + if(eventTracker != null){ + if(eventTracker.getEventDataByRequestID(eventId) != null){ + eventTracker.remove(eventId); + debugLogger.info("eventTracker.remove(" + eventId + ")"); + } + } + } + + /** + * Records the metrics with an event Id and log message + * @param eventId + * @param arg1 + */ + public static void recordMetricEvent(String eventId, String arg1) { + + seTimeStamps(); + + String serviceName = MDC.get(MDC_SERVICE_NAME); + MDC.put(MDC_KEY_REQUEST_ID, eventId); + metricsLogger.info(MessageCodes.RULE_AUDIT_END_INFO, + serviceName, arg1); + + } + + /** + * Records the metrics with an event Id, class name and log message + * @param eventId + * @param className + * @param arg1 + */ + public static void recordMetricEvent(String eventId, String className,String arg1) { + + seTimeStamps(); + + MDC.put(CLASS_NAME, className); + String serviceName = MDC.get(MDC_SERVICE_NAME); + MDC.put(MDC_KEY_REQUEST_ID, eventId); + metricsLogger.info(MessageCodes.RULE_AUDIT_END_INFO, + serviceName, arg1); + } + + /** + * Records the metrics with an event Id and log message + * @param eventId + * @param arg1 + */ + public static void recordMetricEvent(UUID eventId, String arg1) { + + if(eventId == null){ + return; + } + String serviceName = MDC.get(MDC_SERVICE_NAME); + MDC.put(MDC_KEY_REQUEST_ID, eventId.toString()); + metricsLogger.info(MessageCodes.RULE_AUDIT_END_INFO, + serviceName, arg1); + } + + /** + * Records a String message for metrics logs + * @param arg0 + */ + public static void recordMetricEvent(String arg0) { + seTimeStamps(); + String serviceName = MDC.get(MDC_SERVICE_NAME); + metricsLogger.info(MessageCodes.RULE_METRICS_INFO, + serviceName, arg0); + } + + + /** + * Records the metrics event with a String message + * @param arg0 + */ + public static void metrics(String arg0) { + String serviceName = MDC.get(MDC_SERVICE_NAME); + metricsLogger.info(MessageCodes.RULE_METRICS_INFO, + serviceName, arg0); + } + + /** + * Records the metrics event with a class name and a String message + * @param arg0 + */ + public static void metrics(String className, Object arg0) { + seTimeStamps(); + MDC.put(CLASS_NAME, className); + String serviceName = MDC.get(MDC_SERVICE_NAME); + metricsLogger.info(MessageCodes.RULE_METRICS_INFO, + serviceName, ""+arg0); + } + + /** + * Records the metrics event with a String message + * @param arg0 + */ + public static void metrics(Object arg0) { + seTimeStamps(); + MDC.put(CLASS_NAME, ""); + String serviceName = MDC.get(MDC_SERVICE_NAME); + metricsLogger.info(MessageCodes.RULE_METRICS_INFO, + serviceName, ""+arg0); + } + + /** + * Records the metrics event with a String message + * @param arg0 + */ + public static void metricsPrintln(String arg0) { + MDC.clear(); + metricsLogger.info(arg0); + } + + /** + * Removes all the return lines from the printStackTrace + * @param t + * @param arguments + */ + private static String getNormalizedStackTrace (Throwable t, String...arguments) { + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + t.printStackTrace(pw); + String newStValue = sw.toString().replace ('|', '!').replace ("\n", " - "); + int curSize = (arguments == null ? 0 : arguments.length); + StringBuffer newArgument = new StringBuffer(); + for(int i=0; i<curSize; i++) { + newArgument.append(arguments[i]); + newArgument.append(":"); + } + newArgument.append(newStValue); + return newArgument.toString(); + } + + /** + * Starts the process of cleaning up the ConcurrentHashMap of EventData + */ + private static void startCleanUp(){ + + if(!isEventTrackerRunning) { + ttrcker = new EventTrackInfoHandler(); + timer = new Timer(true); + timer.scheduleAtFixedRate(ttrcker, TIMER_DELAY_TIME, CHECK_INTERVAL); + debugLogger.info("EventTrackInfoHandler begins! : " + new Date()); + }else{ + debugLogger.info("Timer is still running : " + new Date()); + + } + } + + + /** + * Stops the process of cleaning up the ConcurrentHashMap of EventData + */ + private static void stopCleanUp(){ + + if(isEventTrackerRunning && timer != null){ + timer.cancel(); + timer.purge(); + debugLogger.info("Timer stopped: " + new Date()); + }else{ + debugLogger.info("Timer was already stopped : " + new Date()); + + } + isEventTrackerRunning = false; + + } + + /** + * Loads all the attributes from policyLogger.properties file + */ + public static LoggerType init(Properties properties) throws Exception { + // read in properties + Properties logger_properties = properties; + LoggerType logger_type = LoggerType.EELF; + + // fetch and verify definitions of some properties + try{ + + int timerDelayTime = Integer.parseInt(logger_properties.getProperty("timer.delay.time")); + int checkInterval = Integer.parseInt(logger_properties.getProperty("check.interval")); + int expiredDate = Integer.parseInt(logger_properties.getProperty("event.expired.time")); + int concurrentHashMapLimit = Integer.parseInt(logger_properties.getProperty("concurrentHashMap.limit")); + int stopCheckPoint = Integer.parseInt(logger_properties.getProperty("stop.check.point")); + String loggerType = logger_properties.getProperty("logger.type"); + + String debugLevel = logger_properties.getProperty("debugLogger.level"); + String metricsLevel = logger_properties.getProperty("metricsLogger.level"); + String auditLevel = logger_properties.getProperty("error.level"); + String errorLevel = logger_properties.getProperty("audit.level"); + component = logger_properties.getProperty("policy.component"); + String overrideLogbackLevel = logger_properties.getProperty("override.logback.level.setup"); + + if(overrideLogbackLevel != null && !overrideLogbackLevel.isEmpty()) { + if(overrideLogbackLevel.equalsIgnoreCase("TRUE")){ + isOverrideLogbackLevel = true; + }else{ + isOverrideLogbackLevel = false; + } + } + + + if (debugLevel != null && !debugLevel.isEmpty()){ + + DEBUG_LEVEL = Level.valueOf(debugLevel); + + } + //Only check if it is to turn off or not + if (errorLevel != null && errorLevel.equalsIgnoreCase(Level.OFF.toString())){ + + ERROR_LEVEL = Level.valueOf(errorLevel); + + } + //Only check if it is to turn off or not + if (metricsLevel != null && metricsLevel.equalsIgnoreCase(Level.OFF.toString())){ + + METRICS_LEVEL = Level.valueOf(metricsLevel); + + } + //Only check if it is to turn off or not + if (auditLevel != null && auditLevel.equalsIgnoreCase(Level.OFF.toString())){ + + AUDIT_LEVEL = Level.valueOf(auditLevel); + + } + + if(isOverrideLogbackLevel){ + + debugLogger.setLevel(DEBUG_LEVEL); + metricsLogger.setLevel(METRICS_LEVEL); + auditLogger.setLevel(AUDIT_LEVEL); + errorLogger.setLevel(ERROR_LEVEL); + + } + isEventTrackerRunning = false; + + debugLogger.info("timerDelayTiime value: " + timerDelayTime); + + debugLogger.info("checkInterval value: " + checkInterval); + + debugLogger.info("expiredDate value: " + expiredDate); + + debugLogger.info("concurrentHashMapLimit value: " + concurrentHashMapLimit); + + debugLogger.info("loggerType value: " + loggerType); + + debugLogger.info("debugLogger level: " + debugLevel); + + debugLogger.info("component: " + component); + + if (timerDelayTime > 0){ + + TIMER_DELAY_TIME = timerDelayTime; + + }else { + MDC.put(ERROR_CATEGORY, "ERROR"); + if(ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR) != null){ + MDC.put(ERROR_CODE, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorCode()); + MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorDesc()); + + } + errorLogger.error("failed to get the timer.delay.time, so use its default value: " + TIMER_DELAY_TIME); + } + + if (checkInterval > 0){ + + CHECK_INTERVAL = checkInterval; + + }else { + MDC.put(ERROR_CATEGORY, "ERROR"); + if(ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR) != null){ + MDC.put(ERROR_CODE, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorCode()); + MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorDesc()); + + } + errorLogger.error("failed to get the check.interval, so use its default value: " + CHECK_INTERVAL); + } + + if (expiredDate > 0){ + + EXPIRED_TIME = expiredDate; + + }else { + MDC.put(ERROR_CATEGORY, "ERROR"); + + if(ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR) != null){ + MDC.put(ERROR_CODE, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorCode()); + MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorDesc()); + + } + errorLogger.error("failed to get the event.expired.time, so use its default value: " + EXPIRED_TIME); + } + + if (concurrentHashMapLimit > 0){ + + CONCURRENTHASHMAP_LIMIT = concurrentHashMapLimit; + + }else { + MDC.put(ERROR_CATEGORY, "ERROR"); + if(ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR) != null){ + MDC.put(ERROR_CODE, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorCode()); + MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorDesc()); + + } + errorLogger.error("failed to get the concurrentHashMap.limit, so use its default value: " + CONCURRENTHASHMAP_LIMIT); + } + + if (stopCheckPoint > 0){ + + STOP_CHECK_POINT = stopCheckPoint; + + }else { + MDC.put(ERROR_CATEGORY, "ERROR"); + if(ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR) != null){ + MDC.put(ERROR_CODE, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorCode()); + MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorDesc()); + + } + errorLogger.error("failed to get the stop.check.point, so use its default value: " + STOP_CHECK_POINT); + } + + if (loggerType != null){ + + if (loggerType.equalsIgnoreCase("EELF")){ + + logger_type = LoggerType.EELF; + + }else if (loggerType.equalsIgnoreCase("LOG4J")){ + + logger_type = LoggerType.LOG4J; + + }else if (loggerType.equalsIgnoreCase("SYSTEMOUT")){ + + logger_type = LoggerType.SYSTEMOUT; + + } + + } + + if (debugLevel != null && !debugLevel.isEmpty()){ + + DEBUG_LEVEL = Level.valueOf(debugLevel); + + } + //Only check if it is to turn off or not + if (errorLevel != null && errorLevel.equalsIgnoreCase(Level.OFF.toString())){ + + ERROR_LEVEL = Level.valueOf(errorLevel); + + } + //Only check if it is to turn off or not + if (metricsLevel != null && metricsLevel.equalsIgnoreCase(Level.OFF.toString())){ + + METRICS_LEVEL = Level.valueOf(metricsLevel); + + } + //Only check if it is to turn off or not + if (auditLevel != null && auditLevel.equalsIgnoreCase(Level.OFF.toString())){ + + AUDIT_LEVEL = Level.valueOf(auditLevel); + + } + + }catch(Exception e){ + MDC.put(ERROR_CATEGORY, "ERROR"); + + if(ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR) != null){ + MDC.put(ERROR_CODE, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorCode()); + MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorDesc()); + + } + errorLogger.error("failed to get the policyLogger.properties, so use their default values",e); + } + + return logger_type; + + } + + /** + * Sets Debug Level + */ + public static void setDebugLevel(String debugLevel){ + + if(isOverrideLogbackLevel){ + PolicyLogger.DEBUG_LEVEL = Level.valueOf(debugLevel); + debugLogger.setLevel(DEBUG_LEVEL); + } + + } + + /** + * Sets Error OFF or ON + */ + public static void setErrorLevel(String errorLevel){ + + if(isOverrideLogbackLevel){ + if(errorLevel != null && errorLevel.equalsIgnoreCase("OFF")){ + PolicyLogger.ERROR_LEVEL = Level.OFF; + errorLogger.setLevel(ERROR_LEVEL); + }else{ + //--- set default value + errorLogger.setLevel(Level.ERROR); + PolicyLogger.ERROR_LEVEL = Level.ERROR; + } + } + } + + /** + * Sets Metrics OFF or ON + */ + public static void setMetricsLevel(String metricsLevel){ + + if(isOverrideLogbackLevel){ + if(metricsLevel != null && metricsLevel.equalsIgnoreCase("OFF")){ + PolicyLogger.METRICS_LEVEL = Level.OFF; + metricsLogger.setLevel(METRICS_LEVEL); + }else { + //--- set default value + metricsLogger.setLevel(Level.INFO); + PolicyLogger.METRICS_LEVEL = Level.INFO; + } + } + + } + + /** + * Sets Audit OFF or ON + */ + public static void setAuditLevel(String auditLevel){ + + if(isOverrideLogbackLevel){ + if(auditLevel != null && auditLevel.equalsIgnoreCase("OFF")){ + PolicyLogger.AUDIT_LEVEL = Level.OFF; + auditLogger.setLevel(AUDIT_LEVEL); + }else { + //--- set default value + auditLogger.setLevel(Level.INFO); + PolicyLogger.AUDIT_LEVEL = Level.INFO; + } + } + } + + /** + * Returns true for overriding logback levels; returns false for not + */ + public static boolean isOverrideLogbackLevel(){ + + return isOverrideLogbackLevel; + } + + /** + * Sets true for overriding logback levels; sets false for not + */ + public static void setOverrideLogbackLevel(boolean odl){ + + isOverrideLogbackLevel = odl; + + } + /** + * Sets server information to MDC + */ + public static void setServerInfo(String serverHost, String serverPort){ + MDC.put(SERVER_NAME, serverHost+":"+serverPort); + } + +} diff --git a/common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/EelfLogger.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/EelfLogger.java new file mode 100644 index 00000000..6e74b94c --- /dev/null +++ b/common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/EelfLogger.java @@ -0,0 +1,481 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-Logging + * ================================================================================ + * Copyright (C) 2017 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.openecomp.policy.common.logging.flexlogger; + +import java.util.UUID; + +import org.openecomp.policy.common.logging.eelf.MessageCodes; +import org.openecomp.policy.common.logging.eelf.PolicyLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; +import com.att.eelf.configuration.EELFLogger.Level; + +/** + * + * EelfLogger implements all the methods of interface Logger by calling PolicyLogger methods + * + */ + +public class EelfLogger implements Logger { + + private String className = ""; + private String transId = UUID.randomUUID().toString(); + + /** + * Constructor + * @param clazz + */ + public EelfLogger(Class clazz) { + if(clazz != null){ + className = clazz.getName(); + } + PolicyLogger.postMDCInfoForEvent(null); + } + + /** + * Constructor + * @param s + */ + public EelfLogger(String s) { + if(s != null){ + className = s; + } + PolicyLogger.postMDCInfoForEvent(null); + } + + /** + * Constructor + * @param clazz + * @param isNewTransaction + */ + public EelfLogger(Class clazz, boolean isNewTransaction) { + if(clazz != null){ + className = clazz.getName(); + } + if(isNewTransaction){ + transId = PolicyLogger.postMDCInfoForEvent(null); + }else{ + transId = PolicyLogger.getTransId(); + } + } + + /** + * Constructor + * @param s + * @param isNewTransaction + */ + public EelfLogger(String s, boolean isNewTransaction) { + if(s != null){ + className = s; + } + if(isNewTransaction){ + transId = PolicyLogger.postMDCInfoForEvent(null); + }else{ + transId = PolicyLogger.getTransId(); + } + } + + /** + * Constructor + * @param clazz + * @param transId + */ + public EelfLogger(Class clazz, String transId) { + if(clazz != null){ + className = clazz.getName(); + } + PolicyLogger.postMDCInfoForEvent(transId); + } + + /** + * Constructor + * @param s + * @param transId + */ + public EelfLogger(String s, String transId) { + if(s != null){ + className = s; + } + PolicyLogger.postMDCInfoForEvent(transId); + } + + /** + * Sets transaction Id for logging + * @param transId + */ + @Override + public void setTransId(String transId){ + + PolicyLogger.setTransId(transId); + this.transId = transId; + } + + /** + * Returns transaction Id for logging + */ + @Override + public String getTransId(){ + return transId; + } + + /** + * Records a message + * @param message + */ + @Override + public void debug(Object message) { + PolicyLogger.debug(className, ""+message); + } + + /** + * Records an error message + * @param message + */ + @Override + public void error(Object message) { + PolicyLogger.error(className, ""+message); + } + + /** + * Records a message + * @param message + */ + @Override + public void info(Object message) { + PolicyLogger.info(className, ""+message); + } + + /** + * Records a message + * @param message + */ + @Override + public void warn(Object message) { + PolicyLogger.warn(className, ""+message); + } + + /** + * Records a message + * @param message + */ + @Override + public void trace(Object message) { + PolicyLogger.trace(className, ""+message); + } + + /** + * Returns true for debug enabled, or false for not + * @return boolean + */ + @Override + public boolean isDebugEnabled(){ + return PolicyLogger.isDebugEnabled(); + } + + /** + * Returns true for info enabled, or false for not + * @return boolean + */ + @Override + public boolean isInfoEnabled(){ + return PolicyLogger.isInfoEnabled(); + } + + /** + * Returns true for warn enabled, or false for not + * @return boolean + */ + @Override + public boolean isWarnEnabled(){ + return PolicyLogger.isWarnEnabled(); + } + + /** + * Returns true for error enabled, or false for not + * @return boolean + */ + @Override + public boolean isErrorEnabled(){ + return PolicyLogger.isErrorEnabled(); + } + + /** + * Returns true for audit enabled, or false for not + * @return boolean + */ + @Override + public boolean isAuditEnabled(){ + if(PolicyLogger.AUDIT_LEVEL != null && PolicyLogger.AUDIT_LEVEL.toString().equals(Level.OFF.toString())){ + return false; + }else { + return true; + } + } + + /** + * Returns true for metrics enabled, or false for not + * @return boolean + */ + @Override + public boolean isMetricsEnabled(){ + if(PolicyLogger.METRICS_LEVEL != null && PolicyLogger.METRICS_LEVEL.toString().equals(Level.OFF.toString())){ + return false; + }else { + return true; + } + } + + /** + * Returns true for trace enabled, or false for not + * @return boolean + */ + @Override + public boolean isTraceEnabled(){ + return PolicyLogger.isDebugEnabled(); + } + + /** + * Records an audit message + * @param arg0 + */ + @Override + public void audit(Object arg0) { + PolicyLogger.audit(className, ""+ arg0); + } + + /** + * Records a message + * @param message + * @param t + */ + @Override + public void debug(Object message, Throwable t) { + PolicyLogger.debug(MessageCodes.GENERAL_INFO, t, message.toString()); + } + + /** + * Records an error message + * @param message + * @param t + */ + @Override + public void error(Object message, Throwable t) { + PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, t, message.toString()); + } + + /** + * Records a message + * @param message + * @param t + */ + @Override + public void info(Object message, Throwable t) { + PolicyLogger.info(MessageCodes.GENERAL_INFO, t, message.toString()); + } + + /** + * Records a message + * @param message + * @param t + */ + @Override + public void warn(Object message, Throwable t) { + PolicyLogger.warn(MessageCodes.GENERAL_WARNING, t, message.toString()); + } + + /** + * Records a message + * @param message + * @param t + */ + @Override + public void trace(Object message, Throwable t) { + PolicyLogger.trace(message); + } + + /** + * Records an audit message + * @param arg0 + * @param t + */ + @Override + public void audit(Object arg0, Throwable t) { + PolicyLogger.audit(arg0); + } + + /** + * Records an audit message + * @param eventId + */ + @Override + public void recordAuditEventStart(String eventId) { + PolicyLogger.recordAuditEventStart(eventId); + } + + /** + * Records an audit message + * @param eventId + */ + @Override + public void recordAuditEventStart(UUID eventId) { + PolicyLogger.recordAuditEventStart(eventId); + } + + /** + * Records an audit message + * @param eventId + * @param rule + * @param policyVersion + */ + @Override + public void recordAuditEventEnd(String eventId, String rule, String policyVersion) { + PolicyLogger.recordAuditEventEnd(eventId, rule, policyVersion); + } + + /** + * Records an audit message + * @param eventId + * @param rule + * @param policyVersion + */ + @Override + public void recordAuditEventEnd(UUID eventId, String rule, String policyVersion) { + PolicyLogger.recordAuditEventEnd(eventId, rule, policyVersion); + } + + /** + * Records an audit message + * @param eventId + * @param rule + */ + @Override + public void recordAuditEventEnd(String eventId, String rule) { + PolicyLogger.recordAuditEventEnd(eventId, rule); + } + + /** + * Records an audit message + * @param eventId + * @param rule + */ + @Override + public void recordAuditEventEnd(UUID eventId, String rule) { + PolicyLogger.recordAuditEventEnd(eventId, rule); + } + + /** + * Records a metrics message + * @param eventId + * @param arg1 + */ + @Override + public void recordMetricEvent(String eventId, String arg1) { + PolicyLogger.recordMetricEvent(eventId, arg1); + } + + /** + * Records a metrics message + * @param eventId + * @param arg1 + */ + @Override + public void recordMetricEvent(UUID eventId, String arg1) { + PolicyLogger.recordMetricEvent(eventId, arg1); + } + + /** + * Records a metrics message + * @param arg0 + */ + @Override + public void metrics(Object arg0) { + PolicyLogger.metrics(className, arg0); + } + + /** + * Records an error message + * @param msg + * @param arg0 + * @param arguments + */ + @Override + public void error(MessageCodes msg, Throwable arg0, String... arguments){ + PolicyLogger.error(msg, className, arg0, arguments); + } + + /** + * Records an error message + * @param msg + * @param arguments + */ + @Override + public void error(MessageCodes msg, String... arguments){ + PolicyLogger.error(msg, arguments); + } + + /** + * Populates MDC Info + * @param transId + */ + @Override + public String postMDCInfoForEvent(String transId) { + return PolicyLogger.postMDCInfoForEvent(transId); + + } + + /** + * Records a message + * @param msg + * @param arguments + */ + @Override + public void warn(MessageCodes msg, String... arguments){ + PolicyLogger.warn(msg, className, arguments); + } + + /** + * Records a message + * @param msg + * @param arg0 + * @param arguments + */ + @Override + public void warn(MessageCodes msg, Throwable arg0, String... arguments){ + PolicyLogger.warn(msg, className, arg0, arguments); + } + + /** + * Populates MDC Info for the rule triggered + * @param transId + */ + @Override + public void postMDCInfoForTriggeredRule(String transId){ + PolicyLogger.postMDCInfoForTriggeredRule(transId); + } + + /** + * Populates MDC Info + * @param o + */ + @Override + public void postMDCInfoForEvent(Object o){ + PolicyLogger.postMDCInfoForEvent(o); + } +} diff --git a/common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/FlexLogger.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/FlexLogger.java new file mode 100644 index 00000000..4748e34f --- /dev/null +++ b/common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/FlexLogger.java @@ -0,0 +1,366 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-Logging + * ================================================================================ + * Copyright (C) 2017 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.openecomp.policy.common.logging.flexlogger; + +import java.io.IOException; +import java.text.SimpleDateFormat; +import java.time.Instant; +import java.util.Date; +import java.util.Properties; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +import org.openecomp.policy.common.logging.eelf.PolicyLogger; +import org.openecomp.policy.common.logging.flexlogger.PropertyUtil; +import org.openecomp.policy.common.logging.flexlogger.PropertyUtil.Listener; + +/** + * + * FlexLogger acts as factory to generate instances of Logger based on logger type + * + */ +public class FlexLogger extends SecurityManager{ + + private static LoggerType loggerType = LoggerType.EELF; + private static boolean initLoggerCalled = false; + private static ConcurrentHashMap<String, Logger4J> logger4JMap = new ConcurrentHashMap<String, Logger4J>(); + private static ConcurrentHashMap<String, EelfLogger> eelfLoggerMap = new ConcurrentHashMap<String, EelfLogger>(); + private static ConcurrentHashMap<String, SystemOutLogger> systemOutMap = new ConcurrentHashMap<String, SystemOutLogger>(); + //--- init logger first + static { + loggerType = initlogger(); + } + + /** + * Returns an instance of Logger + * @param clazz + */ + static public Logger getLogger(Class clazz) { + + if (initLoggerCalled == false) { + loggerType = initlogger(); + } + Logger logger = null; + System.out.println("FlexLogger:getLogger : loggerType = " + loggerType); + switch (loggerType) { + + case EELF: + logger = getEelfLogger(clazz, false); + break; + case LOG4J: + logger = getLog4JLogger(clazz); + break; + case SYSTEMOUT: + logger = getSystemOutLogger(null); + break; + } + + return logger; + + } + + /** + * Returns an instance of Logger + * @param s + */ + static public Logger getLogger(String s) { + + if (initLoggerCalled == false) { + loggerType = initlogger(); + } + Logger logger = null; + System.out.println("FlexLogger:getLogger : loggerType = " + loggerType); + switch (loggerType) { + + case EELF: + logger = getEelfLogger(null,false); + break; + case LOG4J: + logger = getLog4JLogger(s); + break; + case SYSTEMOUT: + logger = getSystemOutLogger(null); + break; + } + + return logger; + + } + + /** + * Returns an instance of Logger + * @param clazz + * @param isNewTransaction + */ + static public Logger getLogger(Class clazz, boolean isNewTransaction) { + + if (initLoggerCalled == false) { + loggerType = initlogger(); + } + Logger logger = null; + System.out.println("FlexLogger:getLogger : loggerType = " + loggerType); + switch (loggerType) { + + case EELF: + logger = getEelfLogger(clazz, isNewTransaction); + break; + case LOG4J: + logger = getLog4JLogger(clazz); + break; + case SYSTEMOUT: + logger = getSystemOutLogger(null); + break; + } + + return logger; + + } + + /** + * Returns an instance of Logger + * @param s + * @param isNewTransaction + */ + static public Logger getLogger(String s, boolean isNewTransaction) { + + if (initLoggerCalled == false) { + loggerType = initlogger(); + } + Logger logger = null; + System.out.println("FlexLogger:getLogger : loggerType = " + loggerType); + switch (loggerType) { + + case EELF: + logger = getEelfLogger(null, isNewTransaction); + break; + case LOG4J: + logger = getLog4JLogger(s); + break; + case SYSTEMOUT: + logger = getSystemOutLogger(null); + break; + } + + return logger; + } + + /** + * Returns the calling class name + */ + public String getClassName(){ + System.out.println("getClassContext()[3].getName() " + getClassContext()[3].getName()); + return getClassContext()[3].getName(); + } + + /** + * Returns an instance of Logger4J + * @param clazz + */ + private static Logger4J getLog4JLogger(Class clazz){ + String className = new FlexLogger().getClassName(); + + if(!logger4JMap.containsKey(className)){ + //for 1610 release use the default debug.log for log4j + Logger4J logger = new Logger4J("debugLogger", className); + logger4JMap.put(className, logger); + } + + return logger4JMap.get(className); + } + + /** + * Returns an instance of Logger4J + * @param s + */ + private static Logger4J getLog4JLogger(String s){ + String className = new FlexLogger().getClassName(); + + if(!logger4JMap.containsKey(className)){ + Logger4J logger = new Logger4J(s, className); + logger4JMap.put(className, logger); + } + + return logger4JMap.get(className); + } + + /** + * Returns an instance of EelfLogger + * @param clazz + * @param isNewTransaction + */ + private static EelfLogger getEelfLogger(Class clazz, boolean isNewTransaction){ + + String className = ""; + EelfLogger logger = null; + if(clazz != null){ + className = clazz.getName(); + }else{ + className = new FlexLogger().getClassName(); + } + + if(!eelfLoggerMap.containsKey(className)){ + logger = new EelfLogger(clazz, isNewTransaction); + eelfLoggerMap.put(className, logger); + }else{ + logger = eelfLoggerMap.get(className); + if(logger == null){ + logger = new EelfLogger(clazz, isNewTransaction); + eelfLoggerMap.put(className, logger); + } + //installl already created but it is new transaction + if(isNewTransaction){ + String transId = PolicyLogger.postMDCInfoForEvent(null); + logger.setTransId(transId); + } + } + System.out.println("eelfLoggerMap size : " + eelfLoggerMap.size() + " class name: " + className); + return logger; + } + + /** + * Returns an instance of SystemOutLogger + * @param clazz + */ + private static SystemOutLogger getSystemOutLogger(Class clazz){ + + String className = new FlexLogger().getClassName(); + + if(!systemOutMap.containsKey(className)){ + SystemOutLogger logger = new SystemOutLogger(className); + systemOutMap.put(className, logger); + } + + return systemOutMap.get(className); + } + + /** + * loads the logger properties + */ + private static LoggerType initlogger() { + LoggerType loggerType = LoggerType.EELF; + String overrideLogbackLevel = "FALSE"; + String logger_Type = ""; + try { + + Properties properties = null; + properties = PropertyUtil.getProperties( + "config/policyLogger.properties"); + System.out.println("FlexLogger:properties => " + properties); + + if(properties != null) { + overrideLogbackLevel = properties.getProperty("override.logback.level.setup"); + System.out.println("FlexLogger:overrideLogbackLevel => " + overrideLogbackLevel); + logger_Type = properties.getProperty("logger.type"); + if (logger_Type != null){ + + if (logger_Type.equalsIgnoreCase("EELF")){ + + loggerType = LoggerType.EELF; + + }else if (logger_Type.equalsIgnoreCase("LOG4J")){ + + loggerType = LoggerType.LOG4J; + + }else if (logger_Type.equalsIgnoreCase("SYSTEMOUT")){ + + loggerType = LoggerType.SYSTEMOUT; + + } + + System.out.println("FlexLogger.logger_Type value: " + logger_Type); + } + } + //--- only use reload policyLogger.properties file listener for logger type EEFL and overrideLogbackLevel flag is true + if(logger_Type.equalsIgnoreCase("EELF") && overrideLogbackLevel != null && overrideLogbackLevel.equalsIgnoreCase("TRUE")){ + + System.out.println("FlexLogger: start listener."); + properties = PropertyUtil.getProperties( + "config/policyLogger.properties", new PropertiesCallBack( + "FlexLogger-CallBack")); + }else{ + System.out.println("FlexLogger: no listener needed."); + } + + try { + + loggerType = PolicyLogger.init(properties); + initLoggerCalled = true; + + } catch (Exception e) { + System.out.println("initlogger" + e); + } + + } catch (IOException e1) { + System.out.println("initlogger" + e1); + } + + return loggerType; + } + + /** + * PropertiesCallBack is listening any updates on the policyLogger.properties + */ + static public class PropertiesCallBack implements Listener { + String name; + + public PropertiesCallBack(String name) { + this.name = name; + } + + /** + * This method will be called automatically if he policyLogger.properties got updated + */ + public void propertiesChanged(Properties properties, + Set<String> changedKeys) { + + String debugLevel = properties.getProperty("debugLogger.level"); + String metricsLevel = properties.getProperty("metricsLogger.level"); + String auditLevel = properties.getProperty("audit.level"); + String errorLevel = properties.getProperty("error.level"); + + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+00:00"); + Instant startTime = Instant.now(); + String formatedTime = sdf.format(Date.from(startTime)); + System.out.println("FlexLogger.propertiesChanged : called at time : " + formatedTime); + System.out.println("FlexLogger.propertiesChanged : debugLevel : " + debugLevel); + + if (changedKeys != null) { + + if (changedKeys.contains("debugLogger.level")) { + PolicyLogger.setDebugLevel(debugLevel); + } + + if (changedKeys.contains("metricsLogger.level")) { + PolicyLogger.setMetricsLevel(metricsLevel); + } + + if (changedKeys.contains("error.level")) { + PolicyLogger.setErrorLevel(errorLevel); + } + + if (changedKeys.contains("audit.level")) { + PolicyLogger.setAuditLevel(auditLevel); + } + } + } + } + +} diff --git a/common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/FlexLoggerTester.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/FlexLoggerTester.java new file mode 100644 index 00000000..3e0d558a --- /dev/null +++ b/common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/FlexLoggerTester.java @@ -0,0 +1,81 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-Logging + * ================================================================================ + * Copyright (C) 2017 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.openecomp.policy.common.logging.flexlogger; + +import java.util.UUID; + +public class FlexLoggerTester { + + + public void testLogging(){ + + // get an instance of logger + Logger logger = FlexLogger.getLogger(FlexLoggerTester.class); + + //logger.info("this is a testing of FlexLogger with logger type:" + FlexLogger.loggerType); + + logger.info("logger.isAuditEnabled():" + logger.isAuditEnabled()); + logger.info("logger.isDebugEnabled():" + logger.isDebugEnabled()); + logger.info("logger.isErrorEnabled():" + logger.isErrorEnabled()); + logger.info("logger.isInfoEnabled():" + logger.isInfoEnabled()); + logger.info("logger.isMetricsEnabled():" + logger.isMetricsEnabled()); + logger.info("logger.isWarnEnabled():" + logger.isWarnEnabled()); + + if(logger.isDebugEnabled()) + logger.debug("this is from logger.debug call"); + else + logger.info("this is from logger.info call"); + + if(logger.isMetricsEnabled()) logger.metrics("this is from logger.metrics call"); + + logger.error("this is from logger.error call"); + if(logger.isAuditEnabled()) + logger.audit("this is from logger.audit call"); + else{ + logger.audit("shouldn't see this line in audit log"); + logger.info("shouldn't see this line in audit log"); + } + + if(logger.isMetricsEnabled()) + logger.metrics("this is from logger.metrics call"); + else{ + logger.metrics("shouldn't see this line in metrics log"); + logger.info("shouldn't see this line in metrics log"); + } + + if(logger.isErrorEnabled()) { + logger.error("this is from logger.error call"); + }else{ + logger.error("shouldn't see this logger.error call in error.log"); + logger.info("error is not enabled"); + } + + logger.info("logger.isDebugEnabled() returned value:" + logger.isDebugEnabled()); + logger.recordAuditEventEnd("123345456464998", "from recordAuditEventEnd call", "12345"); + logger.recordAuditEventEnd(UUID.randomUUID(), "from recordAuditEventEnd call", "abcdf"); + logger.recordAuditEventStart("from recordAuditEventStart call"); + logger.recordAuditEventStart(UUID.randomUUID().toString()); + logger.recordMetricEvent("123345456464998", "from recordMetricEvent call"); + logger.recordMetricEvent(UUID.randomUUID(), "from recordMetricEvent call"); + logger.trace("from trace call"); + + } +} diff --git a/common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/Logger.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/Logger.java new file mode 100644 index 00000000..ae210081 --- /dev/null +++ b/common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/Logger.java @@ -0,0 +1,226 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-Logging + * ================================================================================ + * Copyright (C) 2017 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.openecomp.policy.common.logging.flexlogger; + +import static org.openecomp.policy.common.logging.eelf.Configuration.STATUS_CODE; + +import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME; +import java.util.UUID; + +import org.slf4j.MDC; + +import org.openecomp.policy.common.logging.eelf.MessageCodes; + +/** + * + * Interface Logger - implemented by Logger4J, EelfLogger and SystemOutLogger + * + */ +public interface Logger { + + /** + * Prints messages with the level.DEBUG + */ + public void debug(Object message); + + /** + * Prints messages with the level.ERROR + */ + public void error(Object message); + + /** + * Prints messages with the level.ERROR + */ + public void error(MessageCodes msg, Throwable arg0, String... arguments); + + /** + * Prints messages with the level.INFO + */ + public void info(Object message); + + /** + * Prints messages with the level.WARN + */ + public void warn(Object message); + + /** + * Prints messages with the level.TRACE + */ + public void trace(Object message); + + /** + * Prints messages in audit log with the level.INFO + */ + public void audit(Object arg0); + + /** + * Prints messages with the level.DEBUG + */ + public void debug(Object message, Throwable t); + + /** + * Prints messages with the level.ERROR + */ + public void error(Object message, Throwable t); + + /** + * Prints messages with the level.INFO + */ + public void info(Object message, Throwable t); + + /** + * Prints messages with the level.WARN + */ + public void warn(Object message, Throwable t); + + /** + * Prints messages with the level.TRACE + */ + public void trace(Object message, Throwable t); + + /** + * Prints messages in audit log with the level.INFO + */ + public void audit(Object arg0, Throwable t); + + /** + * Records event Id in audit log with the level.INFO + */ + public void recordAuditEventStart(String eventId); + + /** + * Records the starting time of the event with its request Id as the key + */ + public void recordAuditEventStart(UUID eventId); + + /** + * Records the ending time of the event with its request Id as the key + */ + public void recordAuditEventEnd(String eventId, String rule, String policyVersion ); + + /** + * Records the ending time of the event with its request Id as the key + */ + public void recordAuditEventEnd(UUID eventId, String rule, String policyVersion); + + /** + * Records the ending time of the event with its request Id as the key + */ + public void recordAuditEventEnd(String eventId, String rule); + + /** + * Records the ending time of the event with its request Id as the key + */ + public void recordAuditEventEnd(UUID eventId, String rule); + + + /** + * Records the Metrics with event Id and log message + */ + public void recordMetricEvent(String eventId, String arg1); + + /** + * Records the Metrics with event Id and log message + */ + public void recordMetricEvent(UUID eventId, String arg1); + + /** + * Records the Metrics log message + */ + public void metrics(Object arg0); + + /** + * Returns a boolean value, true for debug logging enabled, false for not enabled + */ + public boolean isDebugEnabled(); + + /** + * Returns a boolean value, true for error logging enabled, false for not enabled + */ + public boolean isErrorEnabled(); + + /** + * Returns a boolean value, true for warn logging enabled, false for not enabled + */ + public boolean isWarnEnabled(); + + /** + * Returns a boolean value, true for info logging enabled, false for not enabled + */ + public boolean isInfoEnabled(); + + /** + * Returns a boolean value, true for error logging enabled, false for not enabled + */ + public boolean isAuditEnabled(); + + /** + * Returns a boolean value, true for warn logging enabled, false for not enabled + */ + public boolean isMetricsEnabled(); + + /** + * Returns a boolean value, true for trace logging enabled, false for not enabled + */ + public boolean isTraceEnabled(); + + + /** + * Populates MDC info + */ + public String postMDCInfoForEvent(String transId); + + /** + * Prints messages with the level.WARN + */ + public void warn(MessageCodes msg, String... arguments) ; + + /** + * Prints messages with the level.WARN + */ + public void warn(MessageCodes msg, Throwable arg0, String... arguments) ; + + /** + * Prints messages with the level.ERROR + */ + public void error(MessageCodes msg, String... arguments) ; + + /** + * Sets transaction Id + */ + public void setTransId(String transId); + + /** + * Returns transaction Id + */ + String getTransId(); + + /** + * Populates MDC Info for the rule triggered + */ + public void postMDCInfoForTriggeredRule(String transId); + + /** + * Populates MDC Info + */ + public void postMDCInfoForEvent(Object o); + +} diff --git a/common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/Logger4J.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/Logger4J.java new file mode 100644 index 00000000..02f95cf2 --- /dev/null +++ b/common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/Logger4J.java @@ -0,0 +1,454 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-Logging + * ================================================================================ + * Copyright (C) 2017 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.openecomp.policy.common.logging.flexlogger; + +import java.util.UUID; + +import org.apache.log4j.Logger; +import org.apache.log4j.Priority; + +import org.openecomp.policy.common.logging.eelf.MessageCodes; +import org.openecomp.policy.common.logging.eelf.PolicyLogger; +import com.att.eelf.configuration.EELFLogger.Level; + +/** + * + * Logger4J implements all the methods of interface Logger by calling org.apache.log4j.Logger + * + */ +public class Logger4J implements org.openecomp.policy.common.logging.flexlogger.Logger { + + private Logger log = null; + private String methodName = ""; + private String className = ""; + private String transId = UUID.randomUUID().toString(); + + /** + * Constructor + * @param clazz + */ + public Logger4J (Class clazz){ + System.out.println("create instance of Logger4J"); + if(clazz != null){ + log = Logger.getLogger(clazz); + className = clazz.getName(); + } + } + + /** + * Constructor + * @param s + * @param className + */ + public Logger4J (String s, String className){ + System.out.println("create instance of Logger4J"); + if(s != null){ + log = Logger.getLogger(s); + } + this.className = className; + } + + /** + * Sets transaction Id + */ + @Override + public void setTransId(String transId){ + log.info(transId); + this.transId = transId; + } + + /** + * Returns transaction Id + */ + @Override + public String getTransId(){ + return transId; + } + + /** + * Records a message + * @param message + */ + @Override + public void debug(Object message) { + if(isDebugEnabled()){ + log.debug(transId + "|" + message); + } + } + + /** + * Records an error message + * @param message + */ + @Override + public void error(Object message) { + log.error( transId + "|" + className +"|" + message); + } + + /** + * Records a message + * @param message + */ + @Override + public void info(Object message) { + log.info( transId + "|" + className +"|" + message); + } + + /** + * Records a message + * @param message + */ + @Override + public void warn(Object message) { + log.warn( transId + "|" + className +"|" + message); + } + + /** + * Records a message + * @param message + */ + @Override + public void trace(Object message) { + log.trace(transId + "|"+ className +"|" + message); + } + + /** + * Returns true for debug enabled, or false for not + * @return boolean + */ + @Override + public boolean isDebugEnabled(){ + return log.isDebugEnabled(); + } + + /** + * Returns true for error enabled, or false for not + * @return boolean + */ + @SuppressWarnings("deprecation") + @Override + public boolean isErrorEnabled(){ + return log.isEnabledFor(Priority.ERROR); + } + + /** + * Returns true for info enabled, or false for not + * @return boolean + */ + @Override + public boolean isInfoEnabled(){ + return log.isInfoEnabled(); + } + + /** + * Returns true for warn enabled, or false for not + * @return boolean + */ + @SuppressWarnings("deprecation") + @Override + public boolean isWarnEnabled(){ + //return log4j value + return log.isEnabledFor(Priority.WARN); + } + + /** + * Returns true for audit enabled, or false for not + * @return boolean + */ + @Override + public boolean isAuditEnabled(){ + if(PolicyLogger.AUDIT_LEVEL != null && PolicyLogger.AUDIT_LEVEL.toString().equals(Level.OFF.toString())){ + return false; + }else { + return true; + } + } + + /** + * Returns true for metrics enabled, or false for not + * @return boolean + */ + @Override + public boolean isMetricsEnabled(){ + if(PolicyLogger.METRICS_LEVEL != null && PolicyLogger.METRICS_LEVEL.toString().equals(Level.OFF.toString())){ + return false; + }else { + return true; + } + } + + /** + * Records an audit message + * @param arg0 + */ + @Override + public void audit(Object arg0) { + log.info(className +"|" +arg0); + } + + /** + * Records an audit message + * @param eventId + */ + @Override + public void recordAuditEventStart(String eventId) { + log.info(className +"|recordAuditEventStart with eventId " + eventId); + } + + /** + * Records an audit message + * @param eventId + */ + @Override + public void recordAuditEventStart(UUID eventId) { + if(eventId != null){ + recordAuditEventStart(eventId.toString()); + } + } + + /** + * Records an audit message + * @param eventId + * @param rule + * @param policyVersion + */ + @Override + public void recordAuditEventEnd(String eventId, String rule, String policyVersion) { + log.info(className +"|"+ eventId + ":" + rule); + } + + /** + * Records an audit message + * @param eventId + * @param rule + * @param policyVersion + */ + @Override + public void recordAuditEventEnd(UUID eventId, String rule, String policyVersion) { + if(eventId != null){ + recordAuditEventEnd(eventId.toString(), rule, policyVersion); + }else{ + recordAuditEventEnd(eventId, rule, policyVersion); + } + } + + /** + * Records an audit message + * @param eventId + * @param rule + */ + @Override + public void recordAuditEventEnd(String eventId, String rule) { + log.info(className +"|" +eventId + ":" + rule); + } + + /** + * Records an audit message + * @param eventId + * @param rule + */ + @Override + public void recordAuditEventEnd(UUID eventId, String rule) { + if(eventId != null){ + recordAuditEventEnd(eventId.toString(), rule); + }else{ + recordAuditEventEnd(eventId, rule); + } + } + + /** + * Records a metrics message + * @param eventId + * @param arg1 + */ + @Override + public void recordMetricEvent(String eventId, String arg1) { + log.info(className +"|" +eventId + ":" + arg1); + + } + + /** + * Records a metrics message + * @param eventId + * @param arg1 + */ + @Override + public void recordMetricEvent(UUID eventId, String arg1) { + if(eventId != null){ + recordMetricEvent(eventId.toString(), arg1); + }else{ + recordMetricEvent(eventId, arg1); + } + } + + /** + * Records a metrics message + * @param arg0 + */ + @Override + public void metrics(Object arg0) { + log.info(arg0); + } + + /** + * Records an error message + * @param msg + * @param arg0 + * @param arguments + */ + @Override + public void error(MessageCodes msg, Throwable arg0, String... arguments){ + log.error(transId + "|" + className +"|" + "MessageCodes :" + msg + arguments); + + } + + /** + * Records an error message + * @param msg + * @param arguments + */ + @Override + public void error(MessageCodes msg, String... arguments){ + log.error(transId + "|" + className +"|" + "MessageCode:" + msg + arguments); + } + + /** + * Returns transaction Id + * @param transId + */ + @Override + public String postMDCInfoForEvent(String transId) { + if(transId == null || transId.isEmpty()){ + transId = UUID.randomUUID().toString(); + } + + return transId; + } + + /** + * Records a message + * @param msg + * @param arguments + */ + @Override + public void warn(MessageCodes msg, String... arguments){ + log.warn(className +"|" +"MessageCodes:" + msg + arguments); + } + + /** + * Records a message + * @param msg + * @param arg0 + * @param arguments + */ + @Override + public void warn(MessageCodes msg, Throwable arg0, String... arguments){ + log.warn(className +"|" +"MessageCodes:" + msg + arguments); + } + + /** + * Records a message + * @param message + * @param t + */ + @Override + public void debug(Object message, Throwable t) { + log.debug(message, t); + } + + /** + * Records an error message + * @param message + * @param t + */ + @Override + public void error(Object message, Throwable t) { + log.error(message, t); + } + + /** + * Records a message + * @param message + * @param t + */ + @Override + public void info(Object message, Throwable t) { + log.info(message, t); + } + + /** + * Records a message + * @param message + * @param t + */ + @Override + public void warn(Object message, Throwable t) { + log.warn(message, t); + } + + /** + * Records a message + * @param message + * @param t + */ + @Override + public void trace(Object message, Throwable t) { + log.trace(message, t); + } + + /** + * Records an audit message + * @param arg0 + * @param t + */ + + @Override + public void audit(Object arg0, Throwable t) { + log.info(arg0, t); + } + + /** + * Returns true for trace enabled, or false for not + * @return boolean + */ + @Override + public boolean isTraceEnabled() { + return log.isTraceEnabled(); + } + + /** + * Records transaction Id + * @param transId + */ + @Override + public void postMDCInfoForTriggeredRule(String transId){ + log.info(transId); + } + + /** + * Records transaction Id + * @param o + */ + @Override + public void postMDCInfoForEvent(Object o){ + log.info(o); + } +} diff --git a/common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/LoggerType.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/LoggerType.java new file mode 100644 index 00000000..8fe55b29 --- /dev/null +++ b/common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/LoggerType.java @@ -0,0 +1,30 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-Logging + * ================================================================================ + * Copyright (C) 2017 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.openecomp.policy.common.logging.flexlogger; + +/** + * + * Logger types + * + */ +public enum LoggerType { + EELF, LOG4J, SYSTEMOUT +} diff --git a/common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/PropertyUtil.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/PropertyUtil.java new file mode 100644 index 00000000..462e10cb --- /dev/null +++ b/common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/PropertyUtil.java @@ -0,0 +1,403 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-Logging + * ================================================================================ + * Copyright (C) 2017 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.openecomp.policy.common.logging.flexlogger; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.Properties; +import java.util.Set; +import java.util.Timer; +import java.util.TimerTask; + +/** + * This class provides utilities to read properties from a properties + * file, and optionally get notifications of future changes + */ +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 opened, and 'IOException' if there is + * a problem loading the properties file. + */ + static public Properties getProperties(File file) throws IOException + { + // create an InputStream (may throw a FileNotFoundException) + FileInputStream fis = new FileInputStream(file); + try + { + // create the properties instance + Properties rval = new Properties(); + + // load properties (may throw an IOException) + rval.load(fis); + return(rval); + } + finally + { + // close input stream + fis.close(); + } + } + + /** + * Read in a properties file + * @param fileName the properties file + * @return a Properties object, containing the associated properties + * @throws IOException - subclass 'FileNotFoundException' if the file + * does not exist or can't be opened, and 'IOException' if there is + * a problem loading the properties file. + */ + static public Properties getProperties(String fileName) throws IOException + { + return(getProperties(new File(fileName))); + } + + /* ============================================================ */ + + // timer thread used for polling for property file changes + private static Timer timer = null; + + /** + * This is the callback interface, used for sending notifications of + * changes in the properties file. + */ + public interface Listener + { + /** + * Notification of a properties file change + * @param properties the new properties + * @param the set of property names that have changed, including + * additions and removals + */ + void propertiesChanged(Properties properties, Set<String> changedKeys); + } + + // this table maps canonical file into a 'ListenerRegistration' instance + static private HashMap<File, ListenerRegistration> registrations = + new HashMap<File, ListenerRegistration>(); + + /** + * This is an internal class - one instance of this exists for each + * property file that is being monitored. Note that multiple listeners + * can be registered for the same file. + */ + private static class ListenerRegistration + { + // the canonical path of the file being monitored + File file; + + // the most recent value of 'file.lastModified()' + long lastModified; + + // the most recent set of properties + Properties properties; + + // the set of listeners monitoring this file + LinkedList<Listener> listeners; + + // the 'TimerTask' instance, used for periodic polling + TimerTask timerTask; + + /** + * Constructor - create a 'ListenerRegistration' instance for this + * file, but with no listeners + */ + ListenerRegistration(File file) throws IOException + { + this.file = file; + + // The initial value of 'lastModified' is set to 0 to ensure that we + // correctly handle the case where the file is modified within the + // same second that polling begins. + lastModified = 0; + + // fetch current properties + properties = getProperties(file); + + // no listeners yet + listeners = new LinkedList<Listener>(); + + // add to static table, so this instance can be shared + registrations.put(file, this); + + if (timer == null) + { + // still need to create a timer thread + synchronized(PropertyUtil.class) + { + // an additional check is added inside the 'synchronized' block, + // just in case someone beat us to it + if (timer == null) + { + timer = new Timer("PropertyUtil-Timer", true); + } + } + } + + // create and schedule the timer task, so this is periodically polled + timerTask = new TimerTask() + { + public void run() + { + try + { + poll(); + } + catch (Exception e) + { + System.err.println(e); + } + } + }; + timer.schedule(timerTask, 10000L, 10000L); + } + + /** + * Add a listener to the notification list + * @param listener this is the listener to add to the list + * @return the properties at the moment the listener was added to the list + */ + synchronized Properties addListener(Listener listener) + { + listeners.add(listener); + return((Properties)properties.clone()); + } + + /** + * Remove a listener from the notification list + * @param listener this is the listener to remove + */ + synchronized void removeListener(Listener listener) + { + listeners.remove(listener); + + // See if we need to remove this 'ListenerRegistration' instance + // from the table. The 'synchronized' block is needed in case + // another listener is being added at about the same time that this + // one is being removed. + synchronized(registrations) + { + if (listeners.size() == 0) + { + timerTask.cancel(); + registrations.remove(file); + } + } + } + + /** + * This method is periodically called to check for property list updates + * @throws IOException if there is an error in reading the properties file + */ + synchronized void poll() throws IOException + { + long timestamp = file.lastModified(); + if (timestamp != lastModified) + { + // update the record, and send out the notifications + lastModified = timestamp; + + // Save old set, and initial set of changed properties. + Properties oldProperties = properties; + HashSet<String> changedProperties = + new HashSet<String>(oldProperties.stringPropertyNames()); + + // Fetch the list of listeners that we will potentially notify, + // and the new properties. Note that this is in a 'synchronized' + // block to ensure that all listeners receiving notifications + // actually have a newer list of properties than the one + // returned on the initial 'getProperties' call. + properties = getProperties(file); + + Set<String> newPropertyNames = properties.stringPropertyNames(); + changedProperties.addAll(newPropertyNames); + + // At this point, 'changedProperties' is the union of all properties + // in both the old and new properties files. Iterate through all + // of the entries in the new properties file - if the entry + // matches the one in the old file, remove it from + // 'changedProperties'. + for (String name : newPropertyNames) + { + if (properties.getProperty(name).equals + (oldProperties.getProperty(name))) + { + // Apparently, any property that exists must be of type + // 'String', and can't be null. For this reason, we don't + // need to worry about the case where + // 'properties.getProperty(name)' returns 'null'. Note that + // 'oldProperties.getProperty(name)' may be 'null' if the + // old property does not exist. + changedProperties.remove(name); + } + } + + // 'changedProperties' should be correct at this point + if (changedProperties.size() != 0) + { + // there were changes - notify everyone in 'listeners' + for (final Listener notify : listeners) + { + // Copy 'properties' and 'changedProperties', so it doesn't + // cause problems if the recipient makes changes. + final Properties tmpProperties = + (Properties)(properties.clone()); + final HashSet<String> tmpChangedProperties = + new HashSet<String>(changedProperties); + + // Do the notification in a separate thread, so blocking + // won't cause any problems. + new Thread() + { + public void run() + { + notify.propertiesChanged + (tmpProperties, tmpChangedProperties); + } + }.start(); + } + } + } + } + } + + /** + * Read in a properties file, and register for update notifications. + * NOTE: it is possible that the first callback will occur while this + * method is still in progress. To avoid this problem, use 'synchronized' + * blocks around this invocation and in the callback -- that will ensure + * that the processing of the initial properties complete before any + * updates are processed. + * + * @param file the properties file + * @param notify if not null, this is a callback interface that is used for + * notifications of changes + * @return a Properties object, containing the associated properties + * @throws IOException - subclass 'FileNotFoundException' if the file + * does not exist or can't be opened, and 'IOException' if there is + * a problem loading the properties file. + */ + static public Properties getProperties(File file, Listener listener) + throws IOException + { + if (listener == null) + { + // no listener specified -- just fetch the properties + return(getProperties(file)); + } + + // Convert the file to a canonical form in order to avoid the situation + // where different names refer to the same file. + file = file.getCanonicalFile(); + + // See if there is an existing registration. The 'synchronized' block + // is needed to handle the case where a new listener is added at about + // the same time that another one is being removed. + synchronized(registrations) + { + ListenerRegistration reg = registrations.get(file); + if (reg == null) + { + // a new registration is needed + reg = new ListenerRegistration(file); + } + return(reg.addListener(listener)); + } + } + + /** + * Read in a properties file, and register for update notifications. + * NOTE: it is possible that the first callback will occur while this + * method is still in progress. To avoid this problem, use 'synchronized' + * blocks around this invocation and in the callback -- that will ensure + * that the processing of the initial properties complete before any + * updates are processed. + * + * @param fileName the properties file + * @param notify if not null, this is a callback interface that is used for + * notifications of changes + * @return a Properties object, containing the associated properties + * @throws IOException - subclass 'FileNotFoundException' if the file + * does not exist or can't be opened, and 'IOException' if there is + * a problem loading the properties file. + */ + static public Properties getProperties(String fileName, Listener listener) + throws IOException + { + return(getProperties(new File(fileName), listener)); + } + + /** + * Stop listenening for updates + * @param file the properties file + * @param notify if not null, this is a callback interface that was used for + * notifications of changes + */ + static public void stopListening(File file, Listener listener) + { + if (listener != null) + { + ListenerRegistration reg = registrations.get(file); + if (reg != null) + { + reg.removeListener(listener); + } + } + } + + /** + * Stop listenening for updates + * @param fileName the properties file + * @param notify if not null, this is a callback interface that was used for + * notifications of changes + */ + static public void stopListening(String fileName, Listener listener) + { + stopListening(new File(fileName), listener); + } + + /* ============================================================ */ + + // TEMPORARY - used to test callback interface + static public class Test implements Listener + { + String name; + + public Test(String name) + { + this.name = name; + } + + public void propertiesChanged(Properties properties, Set<String> changedKeys) + { + System.out.println("Test(" + name + ")\nproperties = " + properties + + "\nchangedKeys = " + changedKeys); + } + } +} diff --git a/common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/SystemOutLogger.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/SystemOutLogger.java new file mode 100644 index 00000000..26f06640 --- /dev/null +++ b/common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/SystemOutLogger.java @@ -0,0 +1,497 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-Logging + * ================================================================================ + * Copyright (C) 2017 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.openecomp.policy.common.logging.flexlogger; + +import java.util.UUID; + +import org.openecomp.policy.common.logging.eelf.MessageCodes; +import org.openecomp.policy.common.logging.eelf.PolicyLogger; +import com.att.eelf.configuration.EELFLogger.Level; + +/** + * + * SystemOutLogger implements all the methods of interface Logger by calling System.out.println + * + */ +public class SystemOutLogger implements Logger { + + private String className = ""; + private boolean isDebugEnabled = true; + private boolean isInfoEnabled = true; + private boolean isWarnEnabled = true; + private boolean isErrorEnabled = true; + private boolean isAuditEnabled = true; + private boolean isMetricsEnabled = true; + private String transId = UUID.randomUUID().toString(); + + /** + * Constructor + * @param clazz + */ + public SystemOutLogger (Class clazz){ + System.out.println("create instance of SystemOutLogger"); + if(clazz != null){ + className = clazz.getName(); + } + initLevel(); + } + + /** + * Constructor + * @param s + */ + public SystemOutLogger (String s){ + System.out.println("create instance of SystemOutLogger"); + if(s != null){ + className = s; + } + initLevel(); + } + + /** + * Sets logging levels + */ + private void initLevel(){ + + if(PolicyLogger.DEBUG_LEVEL != null && PolicyLogger.DEBUG_LEVEL.toString().equals(Level.DEBUG.toString())){ + isDebugEnabled = true; + isInfoEnabled = true; + isWarnEnabled = true; + }else{ + isDebugEnabled = false; + } + + if(PolicyLogger.DEBUG_LEVEL != null && PolicyLogger.DEBUG_LEVEL.toString().equals(Level.INFO.toString())){ + isInfoEnabled = true; + isWarnEnabled = true; + isDebugEnabled = false; + } + + if(PolicyLogger.DEBUG_LEVEL != null && PolicyLogger.DEBUG_LEVEL.toString().equals(Level.OFF.toString())){ + isInfoEnabled = false; + isWarnEnabled = false; + isDebugEnabled = false; + } + + if(PolicyLogger.ERROR_LEVEL != null && PolicyLogger.ERROR_LEVEL.toString().equals(Level.OFF.toString())){ + isErrorEnabled = false; + } + + if(PolicyLogger.AUDIT_LEVEL != null && PolicyLogger.AUDIT_LEVEL.toString().equals(Level.OFF.toString())){ + isAuditEnabled = false; + } + + if(PolicyLogger.METRICS_LEVEL != null && PolicyLogger.METRICS_LEVEL.toString().equals(Level.OFF.toString())){ + isMetricsEnabled = false; + } + } + + /** + * Sets transaction Id + */ + @Override + public void setTransId(String transId){ + + System.out.println(transId); + this.transId = transId; + } + + /** + * Returns transaction Id + */ + @Override + public String getTransId(){ + + return transId; + } + + /** + * Records a message + * @param message + */ + @Override + public void debug(Object message) { + + System.out.println(transId + "|" + className+" : "+message); + } + + /** + * Records an error message + * @param message + */ + @Override + public void error(Object message) { + + System.out.println(transId + "|" + className+" : "+message); + } + + /** + * Records a message + * @param message + */ + @Override + public void info(Object message) { + + System.out.println(transId + "|" + className+" : "+message); + + } + + /** + * Records a message + * @param message + */ + @Override + public void warn(Object message) { + + System.out.println(transId + "|" + className+" : "+message); + } + + /** + * Records a message + * @param message + */ + @Override + public void trace(Object message) { + + System.out.println(transId + "|" + className+" : "+message); + } + + /** + * Returns true for debug enabled, or false for not + * @return boolean + */ + @Override + public boolean isDebugEnabled(){ + + return isDebugEnabled; + } + + /** + * Returns true for warn enabled, or false for not + * @return boolean + */ + @Override + public boolean isWarnEnabled(){ + + return isWarnEnabled; + } + + /** + * Returns true for info enabled, or false for not + * @return boolean + */ + @Override + public boolean isInfoEnabled(){ + + return isInfoEnabled; + } + + /** + * Returns true for error enabled, or false for not + * @return boolean + */ + @Override + public boolean isErrorEnabled(){ + + return isErrorEnabled; + } + + /** + * Returns true for audit enabled, or false for not + * @return boolean + */ + @Override + public boolean isAuditEnabled(){ + + return isAuditEnabled; + } + + /** + * Returns true for metrics enabled, or false for not + * @return boolean + */ + @Override + public boolean isMetricsEnabled(){ + + return isMetricsEnabled; + } + + /** + * Records an audit message + * @param arg0 + */ + @Override + public void audit(Object arg0) { + + System.out.println(transId + "|" +className+" : "+arg0); + } + + /** + * Records an audit message + * @param eventId + */ + @Override + public void recordAuditEventStart(String eventId) { + + System.out.println(transId + "|" +className+" : "+eventId); + + } + + /** + * Records an audit message + * @param eventId + */ + @Override + public void recordAuditEventStart(UUID eventId) { + + System.out.println(eventId); + } + + /** + * Records an audit message + * @param eventId + * @param rule + * @param policyVersion + */ + @Override + public void recordAuditEventEnd(String eventId, String rule, String policyVersion) { + + System.out.println(className+" : "+eventId + ":" + rule + ":" + policyVersion); + } + + /** + * Records an audit message + * @param eventId + * @param rule + * @param policyVersion + */ + @Override + public void recordAuditEventEnd(UUID eventId, String rule, String policyVersion) { + + System.out.println(className+" : "+eventId + ":" + rule + ":" + policyVersion); + } + + /** + * Records an audit message + * @param eventId + * @param rule + */ + @Override + public void recordAuditEventEnd(String eventId, String rule) { + + System.out.println(className+" : "+eventId + ":" + rule); + } + + /** + * Records an audit message + * @param eventId + * @param rule + */ + @Override + public void recordAuditEventEnd(UUID eventId, String rule) { + + System.out.println(className+" : "+eventId + ":" + rule); + } + + /** + * Records a metrics message + * @param eventId + * @param arg1 + */ + @Override + public void recordMetricEvent(String eventId, String arg1) { + + System.out.println(className+" : "+"eventId:" + ":" + eventId + "message:" + arg1); + + } + + /** + * Records a metrics message + * @param eventId + * @param arg1 + */ + @Override + public void recordMetricEvent(UUID eventId, String arg1) { + + System.out.println(className+" : "+eventId + ":" + arg1); + } + + /** + * Records a metrics message + * @param arg0 + */ + @Override + public void metrics(Object arg0) { + + System.out.println(className+" : "+arg0); + } + + /** + * Records an error message + * @param msg + * @param arg0 + * @param arguments + */ + @Override + public void error(MessageCodes msg, Throwable arg0, String... arguments){ + + System.out.println(className+" : "+"MessageCodes :" + msg + arguments); + + } + + /** + * Records an error message + * @param msg + * @param arguments + */ + @Override + public void error(MessageCodes msg, String... arguments){ + + System.out.println(transId + "|" + className+" : "+"MessageCode:" + msg + arguments); + } + + /** + * Returns transaction Id + * @param transId + */ + @Override + public String postMDCInfoForEvent(String transId) { + + if(transId == null || transId.isEmpty()){ + transId = UUID.randomUUID().toString(); + } + + return transId; + } + + /** + * Records a message + * @param msg + * @param arguments + */ + @Override + public void warn(MessageCodes msg, String... arguments){ + + System.out.println(transId + "|" + className+" : "+"MessageCodes:" + msg + arguments); + } + + /** + * Records a message + * @param msg + * @param arg0 + * @param arguments + */ + @Override + public void warn(MessageCodes msg, Throwable arg0, String... arguments){ + + System.out.println(transId + "|" + className+" : "+"MessageCodes:" + msg + arguments); + + } + + /** + * Records a message + * @param message + * @param t + */ + @Override + public void debug(Object message, Throwable t) { + System.out.println(transId + "|" + className+" : "+ message + ":" + t); + } + + /** + * Records an error message + * @param message + * @param t + */ + @Override + public void error(Object message, Throwable t) { + System.out.println(transId + "|" + className+" : "+ message + ":" + t); + } + + /** + * Records a message + * @param message + * @param t + */ + @Override + public void info(Object message, Throwable t) { + System.out.println(transId + "|" + className+" : "+ message + ":" + t); + } + + /** + * Records a message + * @param message + * @param t + */ + @Override + public void warn(Object message, Throwable t) { + System.out.println(transId + "|" + className+" : "+ message + ":" + t); + } + + /** + * Records a message + * @param message + * @param t + */ + @Override + public void trace(Object message, Throwable t) { + System.out.println(transId + "|" + className+" : "+ message + ":" + t); + } + + /** + * Records an audit message + * @param arg0 + * @param t + */ + @Override + public void audit(Object arg0, Throwable t) { + System.out.println(transId + "|" + className+" : "+ arg0 + ":" + t); + } + + /** + * Returns true for trace enabled, or false for not + * @return boolean + */ + @Override + public boolean isTraceEnabled() { + // default + return false; + } + + /** + * Records transaction Id + * @param transId + */ + @Override + public void postMDCInfoForTriggeredRule(String transId){ + + System.out.println(transId); + } + + /** + * Records transaction Id + * @param o + */ + @Override + public void postMDCInfoForEvent(Object o){ + System.out.println(o); + } +} diff --git a/common-logging/src/main/java/org/openecomp/policy/common/logging/nsa/LoggingContext.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/nsa/LoggingContext.java new file mode 100644 index 00000000..56f6686a --- /dev/null +++ b/common-logging/src/main/java/org/openecomp/policy/common/logging/nsa/LoggingContext.java @@ -0,0 +1,61 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-Logging + * ================================================================================ + * Copyright (C) 2017 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.openecomp.policy.common.logging.nsa; + +/** + * An interface for providing data into the underlying logging context. Systems should use + * this interface rather than log system specific MDC solutions in order to reduce dependencies. + * + * A LoggingContext is specific to the calling thread. + * + */ +public interface LoggingContext +{ + /** + * Put a key/value pair into the logging context, replacing an entry with the same key. + * @param key + * @param value + */ + void put ( String key, String value ); + + /** + * Put a key/value pair into the logging context, replacing an entry with the same key. + * @param key + * @param value + */ + void put ( String key, long value ); + + /** + * Get a string value, returning the default value if the value is missing. + * @param key + * @param defaultValue + * @return a string value + */ + String get ( String key, String defaultValue ); + + /** + * Get a long value, returning the default value if the value is missing or not a long. + * @param key + * @param defaultValue + * @return a long value + */ + long get ( String key, long defaultValue ); +} diff --git a/common-logging/src/main/java/org/openecomp/policy/common/logging/nsa/LoggingContextFactory.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/nsa/LoggingContextFactory.java new file mode 100644 index 00000000..b8fce10c --- /dev/null +++ b/common-logging/src/main/java/org/openecomp/policy/common/logging/nsa/LoggingContextFactory.java @@ -0,0 +1,55 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-Logging + * ================================================================================ + * Copyright (C) 2017 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.openecomp.policy.common.logging.nsa; + + +import org.openecomp.policy.common.logging.nsa.impl.SharedContext; +import org.openecomp.policy.common.logging.nsa.impl.Slf4jLoggingContext; + +/** + * A factory for setting up a LoggingContext + * + */ +public class LoggingContextFactory +{ + public static class Builder + { + public Builder withBaseContext ( LoggingContext lc ) + { + fBase = lc; + return this; + } + + public Builder forSharing () + { + fShared = true; + return this; + } + + public LoggingContext build () + { + return fShared ? new SharedContext ( fBase ) : new Slf4jLoggingContext ( fBase ); + } + + private LoggingContext fBase = null; + private boolean fShared = false; + } +} diff --git a/common-logging/src/main/java/org/openecomp/policy/common/logging/nsa/SharedLoggingContext.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/nsa/SharedLoggingContext.java new file mode 100644 index 00000000..2ecbcb0a --- /dev/null +++ b/common-logging/src/main/java/org/openecomp/policy/common/logging/nsa/SharedLoggingContext.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-Logging + * ================================================================================ + * Copyright (C) 2017 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.openecomp.policy.common.logging.nsa; + +/** + * A logging context must be thread-specific. Contexts that implement SharedLoggingContext + * are expected to be shared across threads, and they have to be able to populate another + * logging context with their data. + * + */ +public interface SharedLoggingContext extends LoggingContext +{ + /** + * Copy this context's data to the given context. This must work across threads so that + * a base context can be shared in another thread. + * @param lc + */ + void transferTo ( SharedLoggingContext lc ); +} diff --git a/common-logging/src/main/java/org/openecomp/policy/common/logging/nsa/impl/SharedContext.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/nsa/impl/SharedContext.java new file mode 100644 index 00000000..96ffbf64 --- /dev/null +++ b/common-logging/src/main/java/org/openecomp/policy/common/logging/nsa/impl/SharedContext.java @@ -0,0 +1,58 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-Logging + * ================================================================================ + * Copyright (C) 2017 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.openecomp.policy.common.logging.nsa.impl; + +import java.util.HashMap; +import java.util.Map.Entry; + +import org.openecomp.policy.common.logging.nsa.LoggingContext; +import org.openecomp.policy.common.logging.nsa.SharedLoggingContext; + +/** + * A shared logging context for SLF4J + * + */ +public class SharedContext extends Slf4jLoggingContext implements SharedLoggingContext +{ + public SharedContext ( LoggingContext base ) + { + super ( base ); + fMap = new HashMap<String,String> (); + } + + @Override + public void put ( String key, String value ) + { + super.put ( key, value ); + fMap.put ( key, value ); + } + + @Override + public void transferTo ( SharedLoggingContext lc ) + { + for ( Entry<String,String> e : fMap.entrySet () ) + { + lc.put ( e.getKey(), e.getValue() ); + } + } + + private final HashMap<String,String> fMap; +} diff --git a/common-logging/src/main/java/org/openecomp/policy/common/logging/nsa/impl/Slf4jLoggingContext.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/nsa/impl/Slf4jLoggingContext.java new file mode 100644 index 00000000..de31af98 --- /dev/null +++ b/common-logging/src/main/java/org/openecomp/policy/common/logging/nsa/impl/Slf4jLoggingContext.java @@ -0,0 +1,71 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-Logging + * ================================================================================ + * Copyright (C) 2017 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.openecomp.policy.common.logging.nsa.impl; + +import org.slf4j.MDC; + +import org.openecomp.policy.common.logging.nsa.LoggingContext; + +/** + * A logging context for SLF4J + * + */ +public class Slf4jLoggingContext implements LoggingContext +{ + public Slf4jLoggingContext ( LoggingContext base ) + { + } + + @Override + public void put ( String key, String value ) + { + MDC.put ( key, value ); + } + + public void put ( String key, long value ) + { + put ( key, "" + value ); + } + + + public String get ( String key, String defaultValue ) + { + String result = MDC.get ( key ); + if ( result == null ) + { + result = defaultValue; + } + return result; + } + + public long get ( String key, long defaultValue ) + { + final String str = get ( key, "" + defaultValue ); + try + { + return Long.parseLong ( str ); + } + catch ( NumberFormatException x ) + { + return defaultValue; + } + } +} diff --git a/common-logging/src/main/java/org/openecomp/policy/common/logging/nsa/package-info.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/nsa/package-info.java new file mode 100644 index 00000000..e1ef710b --- /dev/null +++ b/common-logging/src/main/java/org/openecomp/policy/common/logging/nsa/package-info.java @@ -0,0 +1,27 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-Logging + * ================================================================================ + * Copyright (C) 2017 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========================================================= + */ + +/** + * This package provides a logging context infrastructure and a corresponding + * implementation based on the SLF4J/Log4j "MDC" (Mapped Diagnostic Context) feature. + * + */ +package org.openecomp.policy.common.logging.nsa; + |