From 2d211f3e1943ded3a0ab59553b12bee602079398 Mon Sep 17 00:00:00 2001 From: "Arul.Nambi" Date: Thu, 14 Sep 2017 15:30:00 -0400 Subject: Renaming openecomp to onap Issue-ID: AAI-208 Change-Id: I11d428593971c665f0ebdf56465d87161ef7d112 Signed-off-by: Arul.Nambi --- eelf-logging/pom.xml | 4 +- .../org/onap/aai/cl/eelf/AaiLoggerAdapter.java | 351 +++++++++ .../java/org/onap/aai/cl/eelf/AuditLogLine.java | 83 +++ .../java/org/onap/aai/cl/eelf/ErrorLogLine.java | 44 ++ .../java/org/onap/aai/cl/eelf/LogMessageEnum.java | 33 + .../java/org/onap/aai/cl/eelf/LoggerFactory.java | 179 +++++ .../java/org/onap/aai/cl/eelf/MetricsLogLine.java | 85 +++ .../org/openecomp/cl/eelf/AaiLoggerAdapter.java | 351 --------- .../java/org/openecomp/cl/eelf/AuditLogLine.java | 83 --- .../java/org/openecomp/cl/eelf/ErrorLogLine.java | 44 -- .../java/org/openecomp/cl/eelf/LogMessageEnum.java | 33 - .../java/org/openecomp/cl/eelf/LoggerFactory.java | 179 ----- .../java/org/openecomp/cl/eelf/MetricsLogLine.java | 85 --- .../org/onap/aai/cl/eelf/AAILoggerAdapterTest.java | 824 +++++++++++++++++++++ .../org/onap/aai/cl/eelf/LoggerFactoryTest.java | 135 ++++ .../java/org/onap/aai/cl/eelf/UnitTestMsgs.java | 45 ++ .../openecomp/cl/eelf/AAILoggerAdapterTest.java | 824 --------------------- .../org/openecomp/cl/eelf/LoggerFactoryTest.java | 135 ---- .../java/org/openecomp/cl/eelf/UnitTestMsgs.java | 45 -- logging-api/pom.xml | 2 +- .../main/java/org/onap/aai/cl/api/LogFields.java | 86 +++ .../src/main/java/org/onap/aai/cl/api/LogLine.java | 116 +++ .../src/main/java/org/onap/aai/cl/api/Logger.java | 218 ++++++ .../onap/aai/cl/api/LoggerFactoryInterface.java | 45 ++ .../main/java/org/onap/aai/cl/mdc/MdcContext.java | 80 ++ .../main/java/org/onap/aai/cl/mdc/MdcOverride.java | 46 ++ .../main/java/org/openecomp/cl/api/LogFields.java | 86 --- .../main/java/org/openecomp/cl/api/LogLine.java | 117 --- .../src/main/java/org/openecomp/cl/api/Logger.java | 218 ------ .../openecomp/cl/api/LoggerFactoryInterface.java | 45 -- .../main/java/org/openecomp/cl/mdc/MdcContext.java | 80 -- .../java/org/openecomp/cl/mdc/MdcOverride.java | 46 -- pom.xml | 2 +- 33 files changed, 2374 insertions(+), 2375 deletions(-) create mode 100644 eelf-logging/src/main/java/org/onap/aai/cl/eelf/AaiLoggerAdapter.java create mode 100644 eelf-logging/src/main/java/org/onap/aai/cl/eelf/AuditLogLine.java create mode 100644 eelf-logging/src/main/java/org/onap/aai/cl/eelf/ErrorLogLine.java create mode 100644 eelf-logging/src/main/java/org/onap/aai/cl/eelf/LogMessageEnum.java create mode 100644 eelf-logging/src/main/java/org/onap/aai/cl/eelf/LoggerFactory.java create mode 100644 eelf-logging/src/main/java/org/onap/aai/cl/eelf/MetricsLogLine.java delete mode 100644 eelf-logging/src/main/java/org/openecomp/cl/eelf/AaiLoggerAdapter.java delete mode 100644 eelf-logging/src/main/java/org/openecomp/cl/eelf/AuditLogLine.java delete mode 100644 eelf-logging/src/main/java/org/openecomp/cl/eelf/ErrorLogLine.java delete mode 100644 eelf-logging/src/main/java/org/openecomp/cl/eelf/LogMessageEnum.java delete mode 100644 eelf-logging/src/main/java/org/openecomp/cl/eelf/LoggerFactory.java delete mode 100644 eelf-logging/src/main/java/org/openecomp/cl/eelf/MetricsLogLine.java create mode 100644 eelf-logging/src/test/java/org/onap/aai/cl/eelf/AAILoggerAdapterTest.java create mode 100644 eelf-logging/src/test/java/org/onap/aai/cl/eelf/LoggerFactoryTest.java create mode 100644 eelf-logging/src/test/java/org/onap/aai/cl/eelf/UnitTestMsgs.java delete mode 100644 eelf-logging/src/test/java/org/openecomp/cl/eelf/AAILoggerAdapterTest.java delete mode 100644 eelf-logging/src/test/java/org/openecomp/cl/eelf/LoggerFactoryTest.java delete mode 100644 eelf-logging/src/test/java/org/openecomp/cl/eelf/UnitTestMsgs.java create mode 100644 logging-api/src/main/java/org/onap/aai/cl/api/LogFields.java create mode 100644 logging-api/src/main/java/org/onap/aai/cl/api/LogLine.java create mode 100644 logging-api/src/main/java/org/onap/aai/cl/api/Logger.java create mode 100644 logging-api/src/main/java/org/onap/aai/cl/api/LoggerFactoryInterface.java create mode 100644 logging-api/src/main/java/org/onap/aai/cl/mdc/MdcContext.java create mode 100644 logging-api/src/main/java/org/onap/aai/cl/mdc/MdcOverride.java delete mode 100644 logging-api/src/main/java/org/openecomp/cl/api/LogFields.java delete mode 100644 logging-api/src/main/java/org/openecomp/cl/api/LogLine.java delete mode 100644 logging-api/src/main/java/org/openecomp/cl/api/Logger.java delete mode 100644 logging-api/src/main/java/org/openecomp/cl/api/LoggerFactoryInterface.java delete mode 100644 logging-api/src/main/java/org/openecomp/cl/mdc/MdcContext.java delete mode 100644 logging-api/src/main/java/org/openecomp/cl/mdc/MdcOverride.java diff --git a/eelf-logging/pom.xml b/eelf-logging/pom.xml index c9a9433..eaec784 100644 --- a/eelf-logging/pom.xml +++ b/eelf-logging/pom.xml @@ -23,7 +23,7 @@ 4.0.0 - org.openecomp.aai.logging-service + org.onap.aai.logging-service logging-service 1.1.0-SNAPSHOT @@ -36,7 +36,7 @@ - org.openecomp.aai.logging-service + org.onap.aai.logging-service logging-api ${project.version} diff --git a/eelf-logging/src/main/java/org/onap/aai/cl/eelf/AaiLoggerAdapter.java b/eelf-logging/src/main/java/org/onap/aai/cl/eelf/AaiLoggerAdapter.java new file mode 100644 index 0000000..adcdd3f --- /dev/null +++ b/eelf-logging/src/main/java/org/onap/aai/cl/eelf/AaiLoggerAdapter.java @@ -0,0 +1,351 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * Copyright © 2017 Amdocs + * ================================================================================ + * 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.cl.eelf; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFLogger.Level; +import com.att.eelf.i18n.EELFResolvableErrorEnum; +import com.att.eelf.i18n.EELFResourceManager; + +import org.onap.aai.cl.api.LogFields; +import org.onap.aai.cl.api.LogLine; +import org.onap.aai.cl.api.Logger; +import org.onap.aai.cl.api.LogLine.LogLineType; +import org.onap.aai.cl.mdc.MdcOverride; + +import java.util.HashMap; +import java.util.Map; + +/** + * This class provides a logging implementation which wraps the EELF logging + * framework. + */ +public class AaiLoggerAdapter implements Logger { + + public static final String BAD_ENUM_MSG = "UNRECOGNIZABLE ERROR CODE "; + + /** Field name to use for the message portion of our log lines. */ + public static final String MESSAGE_PREFIX = "Msg"; + + /** + * A place holder to use for fields in the standardized log message that we + * are not explicitly setting. + */ + public static final String NOT_APPLICABLE = "na"; + + /** + * The instance of the actual EELF logger that we will be sending our messages + * to. + */ + private EELFLogger eelfLogger; + + /** + * This indicates the logging format type. It is used for deciding the string + * builder for constructing standardized log statements. + */ + private LogLineType logLineType; + + /** An identifier for the component that is generating the log statements. */ + private String component = NOT_APPLICABLE; + + /** + * Creates a new instance of the {@link AaiLoggerAdapter}, backed by the + * supplied {@link EELFLogger} instance. + * + * @param eelfLogger + * - The instance of {@link EELFLogger} that this logger will invoke. + */ + public AaiLoggerAdapter(EELFLogger eelfLogger, LogLineType logLineType, String componentName) { + + // Store the supplied EELFLogger instance. + this.eelfLogger = eelfLogger; + this.logLineType = logLineType; + this.component = componentName; + } + + @Override + public boolean isTraceEnabled() { + return eelfLogger.isTraceEnabled(); + } + + @Override + public boolean isInfoEnabled() { + return eelfLogger.isInfoEnabled(); + } + + @Override + public boolean isErrorEnabled() { + return eelfLogger.isErrorEnabled(); + } + + @Override + public boolean isWarnEnabled() { + return eelfLogger.isWarnEnabled(); + } + + @Override + public boolean isDebugEnabled() { + return eelfLogger.isDebugEnabled(); + } + + /** + * Sets a number of the common fields which prefix all standard log + * statements. + */ + private void initLogLine(LogLine logLine, String level, String logCode, String msg, + LogFields fields) { + logLine.init(component, logCode, level, msg, fields, new MdcOverride()); + } + + private void initLogLine(LogLine logLine, String level, String logCode, String msg, + LogFields fields, MdcOverride override) { + logLine.init(component, logCode, level, msg, fields, override); + } + + @Override + public void info(Enum logCode, String... arguments) { + info(logCode, new LogFields(), arguments); + } + + @Override + public void info(Enum logCode, LogFields fields, String... arguments) { + + // We expect our error code to be compatible with the templating + // functionality provided by the EELF framework, so make sure + // that this is the case before we try to decode our error code. + if (logCode instanceof LogMessageEnum) { + // Cast our error code enum to make the EELF framework happy. + LogMessageEnum eelfLogCode = (LogMessageEnum) logCode; + + // Initialize the log line + LogLine logLine = getLogLine(); + initLogLine(logLine, Level.INFO.toString(), EELFResourceManager.getIdentifier(eelfLogCode), + EELFResourceManager.format(eelfLogCode, arguments), + (fields == null) ? new LogFields() : fields); + + // Pass our log string to the EELF logging framework. + eelfLogger.info(logLine.getFormattedLine()); + } else { + eelfLogger.error(BAD_ENUM_MSG + logCode.toString()); + } + } + + @Override + public void info(Enum logCode, LogFields fields, MdcOverride override, String... arguments) { + + // We expect our error code to be compatible with the templating + // functionality provided by the EELF framework, so make sure + // that this is the case before we try to decode our error code. + if (logCode instanceof LogMessageEnum) { + // Cast our error code enum to make the EELF framework happy. + LogMessageEnum eelfLogCode = (LogMessageEnum) logCode; + + // Initialize the log line + LogLine logLine = getLogLine(); + initLogLine(logLine, Level.INFO.toString(), EELFResourceManager.getIdentifier(eelfLogCode), + EELFResourceManager.format(eelfLogCode, arguments), + (fields == null) ? new LogFields() : fields, override); + + // Pass our log string to the EELF logging framework. + eelfLogger.info(logLine.getFormattedLine()); + } else { + eelfLogger.error(BAD_ENUM_MSG + logCode.toString()); + } + } + + @Override + public void debug(String message) { + // Initialize the log line + LogLine logLine = getLogLine(); + initLogLine(logLine, Level.DEBUG.toString(), "", message, new LogFields()); + + // Pass our log string the the EELF logging framework. + eelfLogger.debug(logLine.getFormattedLine()); + } + + @Override + public void debug(Enum logCode, String... arguments) { + debug(logCode, new LogFields(), arguments); + } + + @Override + public void debug(Enum logCode, LogFields fields, String... arguments) { + + // We expect our log code to be compatible with the templating + // functionality provided by the EELF framework, so make sure + // that this is the case before we try to decode it. + if (logCode instanceof LogMessageEnum) { + // Cast our error code enum to make the EELF framework happy. + LogMessageEnum eelfLogCode = (LogMessageEnum) logCode; + + // Initialize the log lineLogLine logLine = getLogLine(); + LogLine logLine = getLogLine(); + initLogLine(logLine, Level.DEBUG.toString(), EELFResourceManager.getIdentifier(eelfLogCode), + EELFResourceManager.format(eelfLogCode, arguments), + (fields == null) ? new LogFields() : fields); + + // Pass our log string to the EELF logging framework. + eelfLogger.debug(logLine.getFormattedLine()); + } else { + eelfLogger.error(BAD_ENUM_MSG + logCode.toString()); + } + } + + @Override + public void warn(Enum logCode, String... arguments) { + warn(logCode, new LogFields(), arguments); + } + + @Override + public void warn(Enum logCode, LogFields fields, String... arguments) { + + // We expect our log code to be compatible with the templating + // functionality provided by the EELF framework, so make sure + // that this is the case before we try to decode our it. + if (logCode instanceof LogMessageEnum) { + // Cast our error code enum to make the EELF framework happy. + LogMessageEnum eelfLogCode = (LogMessageEnum) logCode; + + // Initialize the log line + LogLine logLine = getLogLine(); + initLogLine(logLine, Level.WARN.toString(), EELFResourceManager.getIdentifier(eelfLogCode), + EELFResourceManager.format(eelfLogCode, arguments), + (fields == null) ? new LogFields() : fields); + + // Pass our log string to the EELF logging framework. + eelfLogger.warn(logLine.getFormattedLine()); + } else { + eelfLogger.error(BAD_ENUM_MSG + logCode.toString()); + } + } + + @Override + public void trace(Enum logCode, String... arguments) { + trace(logCode, new LogFields(), arguments); + } + + @Override + public void trace(Enum logCode, LogFields fields, String... arguments) { + + // We expect our log code to be compatible with the templating + // functionality provided by the EELF framework, so make sure + // that this is the case before we try to decode our it. + if (logCode instanceof LogMessageEnum) { + // Cast our error code enum to make the EELF framework happy. + LogMessageEnum eelfLogCode = (LogMessageEnum) logCode; + + // Initialize the log line + LogLine logLine = getLogLine(); + initLogLine(logLine, Level.TRACE.toString(), EELFResourceManager.getIdentifier(eelfLogCode), + EELFResourceManager.format(eelfLogCode, arguments), + (fields == null) ? new LogFields() : fields); + + // Pass our log string to the EELF logging framework. + eelfLogger.trace(logLine.getFormattedLine()); + + } else { + eelfLogger.error(BAD_ENUM_MSG + logCode.toString()); + } + } + + @Override + public void error(Enum logCode, String... arguments) { + error(logCode, new LogFields(), arguments); + } + + @Override + public void error(Enum logCode, LogFields fields, String... arguments) { + + // We expect our log code to be compatible with the templating + // functionality provided by the EELF framework, so make sure + // that this is the case before we try to decode it. + if (logCode instanceof LogMessageEnum) { + + // Cast our error code enum to make the EELF framework happy. + LogMessageEnum eelfLogCode = (LogMessageEnum) logCode; + + // Initialize the log line + LogLine logLine = getLogLine(); + initLogLine(logLine, Level.ERROR.toString(), EELFResourceManager.getIdentifier(eelfLogCode), + EELFResourceManager.format(eelfLogCode, arguments), + (fields == null) ? new LogFields() : fields); + + // Pass our log string to the EELF logging framework. + eelfLogger.error(logLine.getFormattedLine()); + + } else { + eelfLogger.error(BAD_ENUM_MSG + logCode.toString()); + } + } + + @Override + public void error(Enum logCode, Throwable ex, String... arguments) { + error(logCode, new LogFields(), ex, arguments); + } + + @Override + public void error(Enum logCode, LogFields fields, Throwable ex, String... arguments) { + + // We expect our log code to be compatible with the templating + // functionality provided by the EELF framework, so make sure + // that this is the case before we try to decode it. + if (logCode instanceof LogMessageEnum) { + // Cast our error code enum to make the EELF framework happy. + LogMessageEnum eelfLogCode = (LogMessageEnum) logCode; + + // Initialize the log line + LogLine logLine = getLogLine(); + initLogLine(logLine, Level.ERROR.toString(), EELFResourceManager.getIdentifier(eelfLogCode), + EELFResourceManager.format(eelfLogCode, arguments), + (fields == null) ? new LogFields() : fields); + + // Pass our log string to the EELF logging framework. + eelfLogger.error(logLine.getFormattedLine(), ex); + + } else { + eelfLogger.error(BAD_ENUM_MSG + logCode.toString()); + } + } + + @Override + public String formatMsg(Enum logCode, String... arguments) { + return EELFResourceManager.getMessage((EELFResolvableErrorEnum) logCode, arguments); + } + + private LogLine getLogLine() { + if (logLineType == LogLineType.AUDIT) { + return new AuditLogLine(); + } + + if (logLineType == LogLineType.ERROR) { + return new ErrorLogLine(); + } + + if (logLineType == LogLineType.METRICS) { + return new MetricsLogLine(); + } + + eelfLogger.warn("Unsupported LogLineType: " + logLineType); + return null; + } +} diff --git a/eelf-logging/src/main/java/org/onap/aai/cl/eelf/AuditLogLine.java b/eelf-logging/src/main/java/org/onap/aai/cl/eelf/AuditLogLine.java new file mode 100644 index 0000000..1a5d23b --- /dev/null +++ b/eelf-logging/src/main/java/org/onap/aai/cl/eelf/AuditLogLine.java @@ -0,0 +1,83 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * Copyright © 2017 Amdocs + * ================================================================================ + * 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.cl.eelf; + +import org.onap.aai.cl.api.LogLine; +import org.onap.aai.cl.mdc.MdcContext; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; + +/** This class is used to help standardize how log lines are written and provide + * profiling info. */ +public class AuditLogLine extends LogLine { + + /** (non-Javadoc) + * @see org.onap.aai.cl.api.LogLine#getFormattedLine() + */ + public String getFormattedLine() { + + // calculate start/end/elapsed times + Date currentDateTime = new Date(); + SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); + String startTimeString = getMdcValue(MdcContext.MDC_START_TIME); + String endTimeString = formatter.format(currentDateTime); + long elapsedTime = 0; + Date startDateTime; + try { + startDateTime = formatter.parse(startTimeString); + elapsedTime = currentDateTime.getTime() - startDateTime.getTime(); + } catch (ParseException e) { + // Leave an elapsed time of 0 if the start time was not properly formatted + } + String elapsedTimeString = Long.toString(elapsedTime); + + return startTimeString + "|" + // 1 start time + endTimeString + "|" + // 2 end time + getMdcValue(MdcContext.MDC_REQUEST_ID) + "|" + // 3 transaction id + getMdcValue(MdcContext.MDC_SERVICE_INSTANCE_ID) + "|" + // 4 service instance + Thread.currentThread().getName() + "|" + // 5 thread id + getMdcValue(MdcContext.MDC_SERVER_FQDN) + "|" + // 6 physical/virtual server name + getMdcValue(MdcContext.MDC_SERVICE_NAME) + "|" + // 7 service name + getMdcValue(MdcContext.MDC_PARTNER_NAME) + "|" + // 8 partner name + fieldValue(DefinedFields.STATUS_CODE) + "|" + // 9 status code + fieldValue(DefinedFields.RESPONSE_CODE) + "|" + // 10 response code + fieldValue(DefinedFields.RESPONSE_DESCRIPTION) + "|" + // 11 response description + fieldValue(DefinedFields.INSTANCE_UUID) + "|" + // 12 instance UUID + level + "|" + // 13 log level + fieldValue(DefinedFields.SEVERITY) + "|" + // 14 log severity + fieldValue(DefinedFields.SERVER_IP) + "|" + // 15 server ip + elapsedTimeString + "|" + // 16 elapsed time + getMdcValue(MdcContext.MDC_SERVER_FQDN) + "|" + // 17 server name + getMdcValue(MdcContext.MDC_CLIENT_ADDRESS) + "|" + // 18 client ip address + fieldValue(DefinedFields.CLASS_NAME) + "|" + // 19 class name + "" + "|" + // 20 deprecated + fieldValue(DefinedFields.PROCESS_KEY) + "|" + // 21 process key + fieldValue(DefinedFields.CUSTOM_1) + "|" + // 22 custom 1 + fieldValue(DefinedFields.CUSTOM_2) + "|" + // 23 custom 2 + fieldValue(DefinedFields.CUSTOM_3) + "|" + // 24 custom 3 + fieldValue(DefinedFields.CUSTOM_4) + "|" + // 25 custom 4 + message; // 26 details + } +} diff --git a/eelf-logging/src/main/java/org/onap/aai/cl/eelf/ErrorLogLine.java b/eelf-logging/src/main/java/org/onap/aai/cl/eelf/ErrorLogLine.java new file mode 100644 index 0000000..a7bf4a7 --- /dev/null +++ b/eelf-logging/src/main/java/org/onap/aai/cl/eelf/ErrorLogLine.java @@ -0,0 +1,44 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * Copyright © 2017 Amdocs + * ================================================================================ + * 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.cl.eelf; + +import org.onap.aai.cl.api.LogLine; + + +/** This class is used to help standardize how log lines are written and provide + * profiling info. */ +public class ErrorLogLine extends LogLine { + + /** (non-Javadoc) + * @see org.onap.aai.cl.api.LogLine#getFormattedLine() + */ + public String getFormattedLine() { + + // The error logger fields should be defined in logback.xml using the following pattern: + // %d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX}|%mdc{RequestId}|%thread||%mdc{PartnerName}|%logger||%.-5level|%msg%n" + return logCode + "|" + // 9 error code + message + "|" + // 10 log message + ""; // 11 extra details + + } +} diff --git a/eelf-logging/src/main/java/org/onap/aai/cl/eelf/LogMessageEnum.java b/eelf-logging/src/main/java/org/onap/aai/cl/eelf/LogMessageEnum.java new file mode 100644 index 0000000..79e17b9 --- /dev/null +++ b/eelf-logging/src/main/java/org/onap/aai/cl/eelf/LogMessageEnum.java @@ -0,0 +1,33 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * Copyright © 2017 Amdocs + * ================================================================================ + * 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.cl.eelf; + +import com.att.eelf.i18n.EELFResolvableErrorEnum; +import com.att.eelf.i18n.EELFResourceManager; + +/** This is a placeholder which client-specific message key enumerations should + * implement in order to tie into the log template functionality of the EELF + * framework. */ +public interface LogMessageEnum extends EELFResolvableErrorEnum { + +} diff --git a/eelf-logging/src/main/java/org/onap/aai/cl/eelf/LoggerFactory.java b/eelf-logging/src/main/java/org/onap/aai/cl/eelf/LoggerFactory.java new file mode 100644 index 0000000..26a8e4e --- /dev/null +++ b/eelf-logging/src/main/java/org/onap/aai/cl/eelf/LoggerFactory.java @@ -0,0 +1,179 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * Copyright © 2017 Amdocs + * ================================================================================ + * 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.cl.eelf; + +import com.att.eelf.configuration.EELFManager; + +import java.util.HashMap; +import java.util.Map; + +import org.onap.aai.cl.api.Logger; +import org.onap.aai.cl.api.LoggerFactoryInterface; +import org.onap.aai.cl.api.LogLine.LogLineType; + +/** This is an implementation of the {@link LoggerFactoryInterface} which + * constructs a {@link Logger} implementation which is compatible with the EELF + * framework. */ +public class LoggerFactory implements LoggerFactoryInterface { + + /** The instance for our factory singleton. */ + private static LoggerFactory instance; + + /** An instance of the log factory provided by the EELF framework. We will use + * this to get an actual EELF logger instance that we will wrap within our + * own, more generalized logger. */ + private EELFManager eelfManager; + + /** This cache maintains a mapping of logger names to instances so that if a + * logger with the same name is requested multiple times we can return the + * same instance each time. */ + private Map errorLoggerCache = new HashMap(); + + /** This cache maintains a mapping of metric logger names to instances so that + * if a logger with the same name is requested multiple times we can return + * the same instance each time. */ + private Map metricLoggerCache = new HashMap(); + + /** This cache maintains a mapping of audit logger names to instances so that + * if a logger with the same name is requested multiple times we can return + * the same instance each time. */ + private Map auditLoggerCache = new HashMap(); + + /** Returns the single instance of our factory singleton. + * + * @return - An instance of the {@link LoggerFactory} */ + public static synchronized LoggerFactory getInstance() { + + // If we don't already have an instance then create it now. + if (instance == null) { + instance = new LoggerFactory(); + } + + // Return our singleton instance. + return instance; + } + + /** + * Instantiates a new {@link LoggerFactory}. + */ + protected LoggerFactory() { + + // We need an instance of the factory provided by the EELF + // framework so that we can instantiate the EELF logger that + // we will be wrapping, so get one now. + if (eelfManager == null) { + eelfManager = EELFManager.getInstance(); + } + } + + /** + * (non-Javadoc) + * + * @see org.ecomp.cl.api.LoggerFactoryInterface#getLogger(java.lang.String) + */ + public Logger getLogger(String name) { + + // Check the cache to see if we have already instantiated a logger + // with the supplied name. + if (!errorLoggerCache.containsKey(name)) { + + // Nothing in the cache, so let's instantiate a logger now. + Logger logger = new AaiLoggerAdapter(eelfManager.getLogger(name), LogLineType.ERROR, name); + errorLoggerCache.put(name, logger); + } + + // Return the requested logger instance. + return errorLoggerCache.get(name); + } + + /** + * (non-Javadoc) + * + * @see org.ecomp.cl.api.LoggerFactoryInterface#getLogger(java.lang.Class) + */ + public Logger getLogger(Class clazz) { + + return getLogger(clazz.getName()); + } + + /** + * (non-Javadoc) + * + * @see org.ecomp.cl.api.LoggerFactoryInterface#getAuditLogger(java.lang.String) + */ + public Logger getAuditLogger(String name) { + + // Check the cache to see if we have already instantiated a logger + // with the supplied name. + if (!auditLoggerCache.containsKey(name)) { + + // Nothing in the cache, so let's instantiate a logger now. + Logger logger = new AaiLoggerAdapter(eelfManager.getAuditLogger(), LogLineType.AUDIT, name); + auditLoggerCache.put(name, logger); + } + + // Return the requested logger instance. + return auditLoggerCache.get(name); + } + + /** + * (non-Javadoc) + * + * @see org.ecomp.cl.api.LoggerFactoryInterface#getAuditLogger(java.lang.Class) + */ + public Logger getAuditLogger(Class clazz) { + + return getAuditLogger(clazz.getName()); + } + + /** + * (non-Javadoc) + * + * @see org.ecomp.cl.api.LoggerFactoryInterface#getMetricsLogger(java.lang.String) + */ + public Logger getMetricsLogger(String name) { + + // Check the cache to see if we have already instantiated a logger + // with the supplied name. + if (!metricLoggerCache.containsKey(name)) { + + // Nothing in the cache, so let's instantiate a logger now. + Logger logger = new AaiLoggerAdapter(eelfManager.getMetricsLogger(), LogLineType.METRICS, + name); + metricLoggerCache.put(name, logger); + } + + // Return the requested logger instance. + return metricLoggerCache.get(name); + } + + /** + * (non-Javadoc) + * + * @see org.ecomp.cl.api.LoggerFactoryInterface#getMetricsLogger(java.lang.Class) + */ + public Logger getMetricsLogger(Class clazz) { + + return getMetricsLogger(clazz.getName()); + } +} diff --git a/eelf-logging/src/main/java/org/onap/aai/cl/eelf/MetricsLogLine.java b/eelf-logging/src/main/java/org/onap/aai/cl/eelf/MetricsLogLine.java new file mode 100644 index 0000000..3b622d0 --- /dev/null +++ b/eelf-logging/src/main/java/org/onap/aai/cl/eelf/MetricsLogLine.java @@ -0,0 +1,85 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * Copyright © 2017 Amdocs + * ================================================================================ + * 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.cl.eelf; + +import org.onap.aai.cl.api.LogLine; +import org.onap.aai.cl.mdc.MdcContext; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; + +/** This class is used to help standardize how log lines are written and provide + * profiling info. */ +public class MetricsLogLine extends LogLine { + + /** Return the log line based on what we have so far. */ + public String getFormattedLine() { + + // Calculate start/end/elapsed times + Date currentDateTime = new Date(); + SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); + String startTimeString = getMdcValue(MdcContext.MDC_START_TIME); + String endTimeString = formatter.format(currentDateTime); + long elapsedTime = 0; + Date startDateTime; + try { + startDateTime = formatter.parse(startTimeString); + elapsedTime = currentDateTime.getTime() - startDateTime.getTime(); + } catch (ParseException e) { + // Leave an elapsed time of 0 if the start time was not properly formatted + } + String elapsedTimeString = Long.toString(elapsedTime); + + return startTimeString + "|" + // 1 start time + endTimeString + "|" + // 2 end time + getMdcValue(MdcContext.MDC_REQUEST_ID) + "|" + // 3 transaction id + getMdcValue(MdcContext.MDC_SERVICE_INSTANCE_ID) + "|" + // 4 service instance + Thread.currentThread().getName() + "|" + // 5 thread id + getMdcValue(MdcContext.MDC_SERVER_FQDN) + "|" + // 6 physical/virtual server name + getMdcValue(MdcContext.MDC_SERVICE_NAME) + "|" + // 7 service name + getMdcValue(MdcContext.MDC_PARTNER_NAME) + "|" + // 8 partner name + fieldValue(DefinedFields.TARGET_ENTITY) + "|" + // 9 target entity + fieldValue(DefinedFields.TARGET_SVC_NAME) + "|" + // 10 target service + fieldValue(DefinedFields.STATUS_CODE) + "|" + // 11 status code + fieldValue(DefinedFields.RESPONSE_CODE) + "|" + // 12 response code + fieldValue(DefinedFields.RESPONSE_DESCRIPTION) + "|" + // 13 response description + fieldValue(DefinedFields.INSTANCE_UUID) + "|" + // 14 instance UUID + level + "|" + // 15 log level + fieldValue(DefinedFields.SEVERITY) + "|" + // 16 log severity + fieldValue(DefinedFields.SERVER_IP) + "|" + // 17 server ip + elapsedTimeString + "|" + // 18 elapsed time + getMdcValue(MdcContext.MDC_SERVER_FQDN) + "|" + // 19 server name + fieldValue(DefinedFields.CLIENT_IP) + "|" + // 20 client ip address + fieldValue(DefinedFields.CLASS_NAME) + "|" + // 21 class name + "" + "|" + // 22 deprecated + fieldValue(DefinedFields.PROCESS_KEY) + "|" + // 23 process key + fieldValue(DefinedFields.TARGET_ENTITY) + "|" + // 24 target virtual entity + fieldValue(DefinedFields.CUSTOM_1) + "|" + // 25 custom 1 + fieldValue(DefinedFields.CUSTOM_2) + "|" + // 26 custom 2 + fieldValue(DefinedFields.CUSTOM_3) + "|" + // 27 custom 3 + fieldValue(DefinedFields.CUSTOM_4) + "|" + // 28 custom 4 + message; // 29 detail message + } + +} diff --git a/eelf-logging/src/main/java/org/openecomp/cl/eelf/AaiLoggerAdapter.java b/eelf-logging/src/main/java/org/openecomp/cl/eelf/AaiLoggerAdapter.java deleted file mode 100644 index 28bf1aa..0000000 --- a/eelf-logging/src/main/java/org/openecomp/cl/eelf/AaiLoggerAdapter.java +++ /dev/null @@ -1,351 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * Copyright © 2017 Amdocs - * ================================================================================ - * 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========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - */ -package org.openecomp.cl.eelf; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFLogger.Level; -import com.att.eelf.i18n.EELFResolvableErrorEnum; -import com.att.eelf.i18n.EELFResourceManager; - -import org.openecomp.cl.api.LogFields; -import org.openecomp.cl.api.LogLine; -import org.openecomp.cl.api.LogLine.LogLineType; -import org.openecomp.cl.api.Logger; -import org.openecomp.cl.mdc.MdcOverride; - -import java.util.HashMap; -import java.util.Map; - -/** - * This class provides a logging implementation which wraps the EELF logging - * framework. - */ -public class AaiLoggerAdapter implements Logger { - - public static final String BAD_ENUM_MSG = "UNRECOGNIZABLE ERROR CODE "; - - /** Field name to use for the message portion of our log lines. */ - public static final String MESSAGE_PREFIX = "Msg"; - - /** - * A place holder to use for fields in the standardized log message that we - * are not explicitly setting. - */ - public static final String NOT_APPLICABLE = "na"; - - /** - * The instance of the actual EELF logger that we will be sending our messages - * to. - */ - private EELFLogger eelfLogger; - - /** - * This indicates the logging format type. It is used for deciding the string - * builder for constructing standardized log statements. - */ - private LogLineType logLineType; - - /** An identifier for the component that is generating the log statements. */ - private String component = NOT_APPLICABLE; - - /** - * Creates a new instance of the {@link AaiLoggerAdapter}, backed by the - * supplied {@link EELFLogger} instance. - * - * @param eelfLogger - * - The instance of {@link EELFLogger} that this logger will invoke. - */ - public AaiLoggerAdapter(EELFLogger eelfLogger, LogLineType logLineType, String componentName) { - - // Store the supplied EELFLogger instance. - this.eelfLogger = eelfLogger; - this.logLineType = logLineType; - this.component = componentName; - } - - @Override - public boolean isTraceEnabled() { - return eelfLogger.isTraceEnabled(); - } - - @Override - public boolean isInfoEnabled() { - return eelfLogger.isInfoEnabled(); - } - - @Override - public boolean isErrorEnabled() { - return eelfLogger.isErrorEnabled(); - } - - @Override - public boolean isWarnEnabled() { - return eelfLogger.isWarnEnabled(); - } - - @Override - public boolean isDebugEnabled() { - return eelfLogger.isDebugEnabled(); - } - - /** - * Sets a number of the common fields which prefix all standard log - * statements. - */ - private void initLogLine(LogLine logLine, String level, String logCode, String msg, - LogFields fields) { - logLine.init(component, logCode, level, msg, fields, new MdcOverride()); - } - - private void initLogLine(LogLine logLine, String level, String logCode, String msg, - LogFields fields, MdcOverride override) { - logLine.init(component, logCode, level, msg, fields, override); - } - - @Override - public void info(Enum logCode, String... arguments) { - info(logCode, new LogFields(), arguments); - } - - @Override - public void info(Enum logCode, LogFields fields, String... arguments) { - - // We expect our error code to be compatible with the templating - // functionality provided by the EELF framework, so make sure - // that this is the case before we try to decode our error code. - if (logCode instanceof LogMessageEnum) { - // Cast our error code enum to make the EELF framework happy. - LogMessageEnum eelfLogCode = (LogMessageEnum) logCode; - - // Initialize the log line - LogLine logLine = getLogLine(); - initLogLine(logLine, Level.INFO.toString(), EELFResourceManager.getIdentifier(eelfLogCode), - EELFResourceManager.format(eelfLogCode, arguments), - (fields == null) ? new LogFields() : fields); - - // Pass our log string to the EELF logging framework. - eelfLogger.info(logLine.getFormattedLine()); - } else { - eelfLogger.error(BAD_ENUM_MSG + logCode.toString()); - } - } - - @Override - public void info(Enum logCode, LogFields fields, MdcOverride override, String... arguments) { - - // We expect our error code to be compatible with the templating - // functionality provided by the EELF framework, so make sure - // that this is the case before we try to decode our error code. - if (logCode instanceof LogMessageEnum) { - // Cast our error code enum to make the EELF framework happy. - LogMessageEnum eelfLogCode = (LogMessageEnum) logCode; - - // Initialize the log line - LogLine logLine = getLogLine(); - initLogLine(logLine, Level.INFO.toString(), EELFResourceManager.getIdentifier(eelfLogCode), - EELFResourceManager.format(eelfLogCode, arguments), - (fields == null) ? new LogFields() : fields, override); - - // Pass our log string to the EELF logging framework. - eelfLogger.info(logLine.getFormattedLine()); - } else { - eelfLogger.error(BAD_ENUM_MSG + logCode.toString()); - } - } - - @Override - public void debug(String message) { - // Initialize the log line - LogLine logLine = getLogLine(); - initLogLine(logLine, Level.DEBUG.toString(), "", message, new LogFields()); - - // Pass our log string the the EELF logging framework. - eelfLogger.debug(logLine.getFormattedLine()); - } - - @Override - public void debug(Enum logCode, String... arguments) { - debug(logCode, new LogFields(), arguments); - } - - @Override - public void debug(Enum logCode, LogFields fields, String... arguments) { - - // We expect our log code to be compatible with the templating - // functionality provided by the EELF framework, so make sure - // that this is the case before we try to decode it. - if (logCode instanceof LogMessageEnum) { - // Cast our error code enum to make the EELF framework happy. - LogMessageEnum eelfLogCode = (LogMessageEnum) logCode; - - // Initialize the log lineLogLine logLine = getLogLine(); - LogLine logLine = getLogLine(); - initLogLine(logLine, Level.DEBUG.toString(), EELFResourceManager.getIdentifier(eelfLogCode), - EELFResourceManager.format(eelfLogCode, arguments), - (fields == null) ? new LogFields() : fields); - - // Pass our log string to the EELF logging framework. - eelfLogger.debug(logLine.getFormattedLine()); - } else { - eelfLogger.error(BAD_ENUM_MSG + logCode.toString()); - } - } - - @Override - public void warn(Enum logCode, String... arguments) { - warn(logCode, new LogFields(), arguments); - } - - @Override - public void warn(Enum logCode, LogFields fields, String... arguments) { - - // We expect our log code to be compatible with the templating - // functionality provided by the EELF framework, so make sure - // that this is the case before we try to decode our it. - if (logCode instanceof LogMessageEnum) { - // Cast our error code enum to make the EELF framework happy. - LogMessageEnum eelfLogCode = (LogMessageEnum) logCode; - - // Initialize the log line - LogLine logLine = getLogLine(); - initLogLine(logLine, Level.WARN.toString(), EELFResourceManager.getIdentifier(eelfLogCode), - EELFResourceManager.format(eelfLogCode, arguments), - (fields == null) ? new LogFields() : fields); - - // Pass our log string to the EELF logging framework. - eelfLogger.warn(logLine.getFormattedLine()); - } else { - eelfLogger.error(BAD_ENUM_MSG + logCode.toString()); - } - } - - @Override - public void trace(Enum logCode, String... arguments) { - trace(logCode, new LogFields(), arguments); - } - - @Override - public void trace(Enum logCode, LogFields fields, String... arguments) { - - // We expect our log code to be compatible with the templating - // functionality provided by the EELF framework, so make sure - // that this is the case before we try to decode our it. - if (logCode instanceof LogMessageEnum) { - // Cast our error code enum to make the EELF framework happy. - LogMessageEnum eelfLogCode = (LogMessageEnum) logCode; - - // Initialize the log line - LogLine logLine = getLogLine(); - initLogLine(logLine, Level.TRACE.toString(), EELFResourceManager.getIdentifier(eelfLogCode), - EELFResourceManager.format(eelfLogCode, arguments), - (fields == null) ? new LogFields() : fields); - - // Pass our log string to the EELF logging framework. - eelfLogger.trace(logLine.getFormattedLine()); - - } else { - eelfLogger.error(BAD_ENUM_MSG + logCode.toString()); - } - } - - @Override - public void error(Enum logCode, String... arguments) { - error(logCode, new LogFields(), arguments); - } - - @Override - public void error(Enum logCode, LogFields fields, String... arguments) { - - // We expect our log code to be compatible with the templating - // functionality provided by the EELF framework, so make sure - // that this is the case before we try to decode it. - if (logCode instanceof LogMessageEnum) { - - // Cast our error code enum to make the EELF framework happy. - LogMessageEnum eelfLogCode = (LogMessageEnum) logCode; - - // Initialize the log line - LogLine logLine = getLogLine(); - initLogLine(logLine, Level.ERROR.toString(), EELFResourceManager.getIdentifier(eelfLogCode), - EELFResourceManager.format(eelfLogCode, arguments), - (fields == null) ? new LogFields() : fields); - - // Pass our log string to the EELF logging framework. - eelfLogger.error(logLine.getFormattedLine()); - - } else { - eelfLogger.error(BAD_ENUM_MSG + logCode.toString()); - } - } - - @Override - public void error(Enum logCode, Throwable ex, String... arguments) { - error(logCode, new LogFields(), ex, arguments); - } - - @Override - public void error(Enum logCode, LogFields fields, Throwable ex, String... arguments) { - - // We expect our log code to be compatible with the templating - // functionality provided by the EELF framework, so make sure - // that this is the case before we try to decode it. - if (logCode instanceof LogMessageEnum) { - // Cast our error code enum to make the EELF framework happy. - LogMessageEnum eelfLogCode = (LogMessageEnum) logCode; - - // Initialize the log line - LogLine logLine = getLogLine(); - initLogLine(logLine, Level.ERROR.toString(), EELFResourceManager.getIdentifier(eelfLogCode), - EELFResourceManager.format(eelfLogCode, arguments), - (fields == null) ? new LogFields() : fields); - - // Pass our log string to the EELF logging framework. - eelfLogger.error(logLine.getFormattedLine(), ex); - - } else { - eelfLogger.error(BAD_ENUM_MSG + logCode.toString()); - } - } - - @Override - public String formatMsg(Enum logCode, String... arguments) { - return EELFResourceManager.getMessage((EELFResolvableErrorEnum) logCode, arguments); - } - - private LogLine getLogLine() { - if (logLineType == LogLineType.AUDIT) { - return new AuditLogLine(); - } - - if (logLineType == LogLineType.ERROR) { - return new ErrorLogLine(); - } - - if (logLineType == LogLineType.METRICS) { - return new MetricsLogLine(); - } - - eelfLogger.warn("Unsupported LogLineType: " + logLineType); - return null; - } -} diff --git a/eelf-logging/src/main/java/org/openecomp/cl/eelf/AuditLogLine.java b/eelf-logging/src/main/java/org/openecomp/cl/eelf/AuditLogLine.java deleted file mode 100644 index c1bfb19..0000000 --- a/eelf-logging/src/main/java/org/openecomp/cl/eelf/AuditLogLine.java +++ /dev/null @@ -1,83 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * Copyright © 2017 Amdocs - * ================================================================================ - * 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========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - */ -package org.openecomp.cl.eelf; - -import org.openecomp.cl.api.LogLine; -import org.openecomp.cl.mdc.MdcContext; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; - -/** This class is used to help standardize how log lines are written and provide - * profiling info. */ -public class AuditLogLine extends LogLine { - - /** (non-Javadoc) - * @see org.openecomp.cl.api.LogLine#getFormattedLine() - */ - public String getFormattedLine() { - - // calculate start/end/elapsed times - Date currentDateTime = new Date(); - SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); - String startTimeString = getMdcValue(MdcContext.MDC_START_TIME); - String endTimeString = formatter.format(currentDateTime); - long elapsedTime = 0; - Date startDateTime; - try { - startDateTime = formatter.parse(startTimeString); - elapsedTime = currentDateTime.getTime() - startDateTime.getTime(); - } catch (ParseException e) { - // Leave an elapsed time of 0 if the start time was not properly formatted - } - String elapsedTimeString = Long.toString(elapsedTime); - - return startTimeString + "|" + // 1 start time - endTimeString + "|" + // 2 end time - getMdcValue(MdcContext.MDC_REQUEST_ID) + "|" + // 3 transaction id - getMdcValue(MdcContext.MDC_SERVICE_INSTANCE_ID) + "|" + // 4 service instance - Thread.currentThread().getName() + "|" + // 5 thread id - getMdcValue(MdcContext.MDC_SERVER_FQDN) + "|" + // 6 physical/virtual server name - getMdcValue(MdcContext.MDC_SERVICE_NAME) + "|" + // 7 service name - getMdcValue(MdcContext.MDC_PARTNER_NAME) + "|" + // 8 partner name - fieldValue(DefinedFields.STATUS_CODE) + "|" + // 9 status code - fieldValue(DefinedFields.RESPONSE_CODE) + "|" + // 10 response code - fieldValue(DefinedFields.RESPONSE_DESCRIPTION) + "|" + // 11 response description - fieldValue(DefinedFields.INSTANCE_UUID) + "|" + // 12 instance UUID - level + "|" + // 13 log level - fieldValue(DefinedFields.SEVERITY) + "|" + // 14 log severity - fieldValue(DefinedFields.SERVER_IP) + "|" + // 15 server ip - elapsedTimeString + "|" + // 16 elapsed time - getMdcValue(MdcContext.MDC_SERVER_FQDN) + "|" + // 17 server name - getMdcValue(MdcContext.MDC_CLIENT_ADDRESS) + "|" + // 18 client ip address - fieldValue(DefinedFields.CLASS_NAME) + "|" + // 19 class name - "" + "|" + // 20 deprecated - fieldValue(DefinedFields.PROCESS_KEY) + "|" + // 21 process key - fieldValue(DefinedFields.CUSTOM_1) + "|" + // 22 custom 1 - fieldValue(DefinedFields.CUSTOM_2) + "|" + // 23 custom 2 - fieldValue(DefinedFields.CUSTOM_3) + "|" + // 24 custom 3 - fieldValue(DefinedFields.CUSTOM_4) + "|" + // 25 custom 4 - message; // 26 details - } -} diff --git a/eelf-logging/src/main/java/org/openecomp/cl/eelf/ErrorLogLine.java b/eelf-logging/src/main/java/org/openecomp/cl/eelf/ErrorLogLine.java deleted file mode 100644 index 00ddbc0..0000000 --- a/eelf-logging/src/main/java/org/openecomp/cl/eelf/ErrorLogLine.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * Copyright © 2017 Amdocs - * ================================================================================ - * 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========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - */ -package org.openecomp.cl.eelf; - -import org.openecomp.cl.api.LogLine; - - -/** This class is used to help standardize how log lines are written and provide - * profiling info. */ -public class ErrorLogLine extends LogLine { - - /** (non-Javadoc) - * @see org.openecomp.cl.api.LogLine#getFormattedLine() - */ - public String getFormattedLine() { - - // The error logger fields should be defined in logback.xml using the following pattern: - // %d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX}|%mdc{RequestId}|%thread||%mdc{PartnerName}|%logger||%.-5level|%msg%n" - return logCode + "|" + // 9 error code - message + "|" + // 10 log message - ""; // 11 extra details - - } -} diff --git a/eelf-logging/src/main/java/org/openecomp/cl/eelf/LogMessageEnum.java b/eelf-logging/src/main/java/org/openecomp/cl/eelf/LogMessageEnum.java deleted file mode 100644 index f6d99cb..0000000 --- a/eelf-logging/src/main/java/org/openecomp/cl/eelf/LogMessageEnum.java +++ /dev/null @@ -1,33 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * Copyright © 2017 Amdocs - * ================================================================================ - * 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========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - */ -package org.openecomp.cl.eelf; - -import com.att.eelf.i18n.EELFResolvableErrorEnum; -import com.att.eelf.i18n.EELFResourceManager; - -/** This is a placeholder which client-specific message key enumerations should - * implement in order to tie into the log template functionality of the EELF - * framework. */ -public interface LogMessageEnum extends EELFResolvableErrorEnum { - -} diff --git a/eelf-logging/src/main/java/org/openecomp/cl/eelf/LoggerFactory.java b/eelf-logging/src/main/java/org/openecomp/cl/eelf/LoggerFactory.java deleted file mode 100644 index b0a7c3b..0000000 --- a/eelf-logging/src/main/java/org/openecomp/cl/eelf/LoggerFactory.java +++ /dev/null @@ -1,179 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * Copyright © 2017 Amdocs - * ================================================================================ - * 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========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - */ -package org.openecomp.cl.eelf; - -import com.att.eelf.configuration.EELFManager; - -import org.openecomp.cl.api.LogLine.LogLineType; -import org.openecomp.cl.api.Logger; -import org.openecomp.cl.api.LoggerFactoryInterface; - -import java.util.HashMap; -import java.util.Map; - -/** This is an implementation of the {@link LoggerFactoryInterface} which - * constructs a {@link Logger} implementation which is compatible with the EELF - * framework. */ -public class LoggerFactory implements LoggerFactoryInterface { - - /** The instance for our factory singleton. */ - private static LoggerFactory instance; - - /** An instance of the log factory provided by the EELF framework. We will use - * this to get an actual EELF logger instance that we will wrap within our - * own, more generalized logger. */ - private EELFManager eelfManager; - - /** This cache maintains a mapping of logger names to instances so that if a - * logger with the same name is requested multiple times we can return the - * same instance each time. */ - private Map errorLoggerCache = new HashMap(); - - /** This cache maintains a mapping of metric logger names to instances so that - * if a logger with the same name is requested multiple times we can return - * the same instance each time. */ - private Map metricLoggerCache = new HashMap(); - - /** This cache maintains a mapping of audit logger names to instances so that - * if a logger with the same name is requested multiple times we can return - * the same instance each time. */ - private Map auditLoggerCache = new HashMap(); - - /** Returns the single instance of our factory singleton. - * - * @return - An instance of the {@link LoggerFactory} */ - public static synchronized LoggerFactory getInstance() { - - // If we don't already have an instance then create it now. - if (instance == null) { - instance = new LoggerFactory(); - } - - // Return our singleton instance. - return instance; - } - - /** - * Instantiates a new {@link LoggerFactory}. - */ - protected LoggerFactory() { - - // We need an instance of the factory provided by the EELF - // framework so that we can instantiate the EELF logger that - // we will be wrapping, so get one now. - if (eelfManager == null) { - eelfManager = EELFManager.getInstance(); - } - } - - /** - * (non-Javadoc) - * - * @see org.ecomp.cl.api.LoggerFactoryInterface#getLogger(java.lang.String) - */ - public Logger getLogger(String name) { - - // Check the cache to see if we have already instantiated a logger - // with the supplied name. - if (!errorLoggerCache.containsKey(name)) { - - // Nothing in the cache, so let's instantiate a logger now. - Logger logger = new AaiLoggerAdapter(eelfManager.getLogger(name), LogLineType.ERROR, name); - errorLoggerCache.put(name, logger); - } - - // Return the requested logger instance. - return errorLoggerCache.get(name); - } - - /** - * (non-Javadoc) - * - * @see org.ecomp.cl.api.LoggerFactoryInterface#getLogger(java.lang.Class) - */ - public Logger getLogger(Class clazz) { - - return getLogger(clazz.getName()); - } - - /** - * (non-Javadoc) - * - * @see org.ecomp.cl.api.LoggerFactoryInterface#getAuditLogger(java.lang.String) - */ - public Logger getAuditLogger(String name) { - - // Check the cache to see if we have already instantiated a logger - // with the supplied name. - if (!auditLoggerCache.containsKey(name)) { - - // Nothing in the cache, so let's instantiate a logger now. - Logger logger = new AaiLoggerAdapter(eelfManager.getAuditLogger(), LogLineType.AUDIT, name); - auditLoggerCache.put(name, logger); - } - - // Return the requested logger instance. - return auditLoggerCache.get(name); - } - - /** - * (non-Javadoc) - * - * @see org.ecomp.cl.api.LoggerFactoryInterface#getAuditLogger(java.lang.Class) - */ - public Logger getAuditLogger(Class clazz) { - - return getAuditLogger(clazz.getName()); - } - - /** - * (non-Javadoc) - * - * @see org.ecomp.cl.api.LoggerFactoryInterface#getMetricsLogger(java.lang.String) - */ - public Logger getMetricsLogger(String name) { - - // Check the cache to see if we have already instantiated a logger - // with the supplied name. - if (!metricLoggerCache.containsKey(name)) { - - // Nothing in the cache, so let's instantiate a logger now. - Logger logger = new AaiLoggerAdapter(eelfManager.getMetricsLogger(), LogLineType.METRICS, - name); - metricLoggerCache.put(name, logger); - } - - // Return the requested logger instance. - return metricLoggerCache.get(name); - } - - /** - * (non-Javadoc) - * - * @see org.ecomp.cl.api.LoggerFactoryInterface#getMetricsLogger(java.lang.Class) - */ - public Logger getMetricsLogger(Class clazz) { - - return getMetricsLogger(clazz.getName()); - } -} diff --git a/eelf-logging/src/main/java/org/openecomp/cl/eelf/MetricsLogLine.java b/eelf-logging/src/main/java/org/openecomp/cl/eelf/MetricsLogLine.java deleted file mode 100644 index 454fb15..0000000 --- a/eelf-logging/src/main/java/org/openecomp/cl/eelf/MetricsLogLine.java +++ /dev/null @@ -1,85 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * Copyright © 2017 Amdocs - * ================================================================================ - * 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========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - */ -package org.openecomp.cl.eelf; - -import org.openecomp.cl.api.LogLine; -import org.openecomp.cl.mdc.MdcContext; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; - -/** This class is used to help standardize how log lines are written and provide - * profiling info. */ -public class MetricsLogLine extends LogLine { - - /** Return the log line based on what we have so far. */ - public String getFormattedLine() { - - // Calculate start/end/elapsed times - Date currentDateTime = new Date(); - SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); - String startTimeString = getMdcValue(MdcContext.MDC_START_TIME); - String endTimeString = formatter.format(currentDateTime); - long elapsedTime = 0; - Date startDateTime; - try { - startDateTime = formatter.parse(startTimeString); - elapsedTime = currentDateTime.getTime() - startDateTime.getTime(); - } catch (ParseException e) { - // Leave an elapsed time of 0 if the start time was not properly formatted - } - String elapsedTimeString = Long.toString(elapsedTime); - - return startTimeString + "|" + // 1 start time - endTimeString + "|" + // 2 end time - getMdcValue(MdcContext.MDC_REQUEST_ID) + "|" + // 3 transaction id - getMdcValue(MdcContext.MDC_SERVICE_INSTANCE_ID) + "|" + // 4 service instance - Thread.currentThread().getName() + "|" + // 5 thread id - getMdcValue(MdcContext.MDC_SERVER_FQDN) + "|" + // 6 physical/virtual server name - getMdcValue(MdcContext.MDC_SERVICE_NAME) + "|" + // 7 service name - getMdcValue(MdcContext.MDC_PARTNER_NAME) + "|" + // 8 partner name - fieldValue(DefinedFields.TARGET_ENTITY) + "|" + // 9 target entity - fieldValue(DefinedFields.TARGET_SVC_NAME) + "|" + // 10 target service - fieldValue(DefinedFields.STATUS_CODE) + "|" + // 11 status code - fieldValue(DefinedFields.RESPONSE_CODE) + "|" + // 12 response code - fieldValue(DefinedFields.RESPONSE_DESCRIPTION) + "|" + // 13 response description - fieldValue(DefinedFields.INSTANCE_UUID) + "|" + // 14 instance UUID - level + "|" + // 15 log level - fieldValue(DefinedFields.SEVERITY) + "|" + // 16 log severity - fieldValue(DefinedFields.SERVER_IP) + "|" + // 17 server ip - elapsedTimeString + "|" + // 18 elapsed time - getMdcValue(MdcContext.MDC_SERVER_FQDN) + "|" + // 19 server name - fieldValue(DefinedFields.CLIENT_IP) + "|" + // 20 client ip address - fieldValue(DefinedFields.CLASS_NAME) + "|" + // 21 class name - "" + "|" + // 22 deprecated - fieldValue(DefinedFields.PROCESS_KEY) + "|" + // 23 process key - fieldValue(DefinedFields.TARGET_ENTITY) + "|" + // 24 target virtual entity - fieldValue(DefinedFields.CUSTOM_1) + "|" + // 25 custom 1 - fieldValue(DefinedFields.CUSTOM_2) + "|" + // 26 custom 2 - fieldValue(DefinedFields.CUSTOM_3) + "|" + // 27 custom 3 - fieldValue(DefinedFields.CUSTOM_4) + "|" + // 28 custom 4 - message; // 29 detail message - } - -} diff --git a/eelf-logging/src/test/java/org/onap/aai/cl/eelf/AAILoggerAdapterTest.java b/eelf-logging/src/test/java/org/onap/aai/cl/eelf/AAILoggerAdapterTest.java new file mode 100644 index 0000000..924ee8f --- /dev/null +++ b/eelf-logging/src/test/java/org/onap/aai/cl/eelf/AAILoggerAdapterTest.java @@ -0,0 +1,824 @@ +/*- + * ============LICENSE_START======================================================= + * Common Logging Library + * ================================================================================ + * 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.onap.aai.cl.eelf; + +import static org.junit.Assert.*; + +import java.util.Locale; + +import org.junit.Before; +import org.junit.Test; +import org.onap.aai.cl.api.LogFields; +import org.onap.aai.cl.api.LogLine; +import org.onap.aai.cl.api.LogLine.DefinedFields; +import org.onap.aai.cl.api.LogLine.LogLineType; +import org.onap.aai.cl.eelf.AaiLoggerAdapter; +import org.onap.aai.cl.mdc.MdcContext; +import org.onap.aai.cl.mdc.MdcOverride; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.i18n.EELFResolvableErrorEnum; + +/** This suite of tests is intended to validate the functionality of our wrapper + * around the {@link EELFLogger}. */ +public class AAILoggerAdapterTest { + + private enum InvalidLogCodeEnum { + BAD_LOGCODE1 + } + + private static final String LOGGER_NAME = "UnitTestLogAdapter"; + private static final String METRICS_LOGGER_NAME = "UnitTestMetricsLogAdapter"; + private static final String AUDIT_LOGGER_NAME = "UnitTestAuditLogAdapter"; + + private TestLogger logger; + private AaiLoggerAdapter loggerAdapter; + private AaiLoggerAdapter metricsLoggerAdapter; + private AaiLoggerAdapter auditLoggerAdapter; + + @Before + public void setup() { + logger = new TestLogger(); + loggerAdapter = new AaiLoggerAdapter(logger, LogLineType.ERROR, LOGGER_NAME); + metricsLoggerAdapter = new AaiLoggerAdapter(logger, LogLineType.METRICS, METRICS_LOGGER_NAME); + auditLoggerAdapter = new AaiLoggerAdapter(logger, LogLineType.AUDIT, AUDIT_LOGGER_NAME); + } + + /** This test validates the the {@link AaiLoggerAdapter} is able to deal with + * log code enums which do not extend the {@link EELFResolvableEnum} + * placeholder (meaning that the EELF framework would not know how to parse + * them). */ + @Test + public void badLogCodeEnumTest() { + + // For each supported log level, validate that if a log code is + // specified which does not extend EELFResolvableEnum, then a + // generic 'unparsable log code' statement is generated instead + // of a correctly parsed log statement. + + loggerAdapter.info(InvalidLogCodeEnum.BAD_LOGCODE1, "arg1"); + assertBadLogCodeMessage(logger.getMessage(), InvalidLogCodeEnum.BAD_LOGCODE1); + + loggerAdapter.debug(InvalidLogCodeEnum.BAD_LOGCODE1, "arg1", "arg2"); + assertBadLogCodeMessage(logger.getMessage(), InvalidLogCodeEnum.BAD_LOGCODE1); + + loggerAdapter.warn(InvalidLogCodeEnum.BAD_LOGCODE1, "arg1", "arg2"); + assertBadLogCodeMessage(logger.getMessage(), InvalidLogCodeEnum.BAD_LOGCODE1); + + loggerAdapter.error(InvalidLogCodeEnum.BAD_LOGCODE1, "arg1", "arg2", "arg3"); + assertBadLogCodeMessage(logger.getMessage(), InvalidLogCodeEnum.BAD_LOGCODE1); + + loggerAdapter.error(InvalidLogCodeEnum.BAD_LOGCODE1, new LogFields(), + new Throwable("Some exception"), "arg1"); + assertBadLogCodeMessage(logger.getMessage(), InvalidLogCodeEnum.BAD_LOGCODE1); + } + + /** This test validates that INFO level logs are correctly parsed from the + * resource bundle. */ + @Test + public void logStatementInfoParsingTest() { + + String FIRST_ARG = "First Arg"; + String SECOND_ARG = "Second Arg"; + + // Generate a simple INFO log. + loggerAdapter.info(UnitTestMsgs.SIMPLE_INFO_LOG, null); + + // Validate that the message was parsed from the bundle resource. + logger.validateLogMsg("UT0001I This is a simple info log with no arguments."); + + // Generate an INFO log with arguments. + LogFields fields = new LogFields().setField(LogLine.DefinedFields.TARGET_SVC_NAME, "test"); + loggerAdapter.info(UnitTestMsgs.INFO_LOG_WITH_ARGS, fields, FIRST_ARG, SECOND_ARG); + + // Validate that the message was parsed from the bundle resource. + logger.validateLogMsg( + "UT0002I This is an info log with some arguments " + FIRST_ARG + " and " + SECOND_ARG); + + // Validate that log fields are being correctly populated. + logger.validateLogFields(LogLineType.ERROR, fields); + } + + /** Validate metrics log */ + @Test + public void logStatementMetricsTest() { + // Generate an INFO log with arguments. + MdcContext.initialize("xx-yy-zz", "MyService", "MyInstance", "MyPartner", "12.0.0.2"); + metricsLoggerAdapter.info(UnitTestMsgs.INFO_LOG_WITH_ARGS, + new LogFields().setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION, "Accepted") + .setField(LogLine.DefinedFields.RESPONSE_CODE, 202), + "arg1", "arg2"); + + // Validate that the log code is correctly encoded in the log statement + // and that the message was parsed from the bundle resource. + logger.validateMetricsMsg("UT0002I This is an info log with some arguments arg1 and arg2"); + logger.validateMetricsRespStatus("202", "Accepted"); + + // Validate MDC override + MdcOverride override = new MdcOverride(); + override.addAttribute(MdcContext.MDC_REQUEST_ID, "New-requestID"); + + LogFields fields = new LogFields() + .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION, "Accepted") + .setField(LogLine.DefinedFields.RESPONSE_CODE, 202); + + metricsLoggerAdapter.info(UnitTestMsgs.INFO_LOG_WITH_ARGS, fields, override, "arg1", "arg2"); + logger.validateMetricsRequestId("New-requestID"); + + // Validate that log fields are being correctly populated. + logger.validateLogFields(LogLineType.METRICS, fields); + } + + /** Validate metrics log */ + @Test + public void logStatementAuditTest() { + // Generate an INFO log with arguments. + MdcContext.initialize("xx-yy-aa", "MyService", "MyInstance", "MyPartner", "12.0.0.8"); + LogFields fields = new LogFields() + .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION, "Accepted") + .setField(LogLine.DefinedFields.RESPONSE_CODE, 202); + auditLoggerAdapter.info(UnitTestMsgs.INFO_LOG_WITH_ARGS, fields, "arg1", "arg2"); + + // Validate that the log code is correctly encoded in the log statement + // and that the message was parsed from the bundle resource. + logger.validateAuditMsg("UT0002I This is an info log with some arguments arg1 and arg2"); + logger.validateAuditRespStatus("202", "Accepted"); + + // Validate that log fields are being correctly populated. + logger.validateLogFields(LogLineType.AUDIT, fields); + } + + /** This test validates that ERROR level logs are correctly parsed from the + * resource bundle. */ + @Test + public void logStatementErrorParsingTest() { + + String FIRST_ARG = "First Arg"; + String SECOND_ARG = "Second Arg"; + + // Generate a simple ERROR log. + loggerAdapter.error(UnitTestMsgs.SIMPLE_ERROR_LOG, null); + + // Validate that the message was parsed from the bundle resource. + logger.validateLogMsg("UT0001E This is a simple error log with no arguments."); + + // Generate an ERROR log with arguments. + loggerAdapter.error(UnitTestMsgs.ERROR_LOG_WITH_ARGS, new LogFields(), FIRST_ARG, SECOND_ARG); + + // Validate that the message was parsed from the bundle resource. + logger.validateLogMsg( + "UT0002E This is an error log with some arguments " + FIRST_ARG + " and " + SECOND_ARG); + } + + /** This test validates that WARNING level logs are correctly parsed from the + * resource bundle. */ + @Test + public void logStatementWarnParsingTest() { + + String FIRST_ARG = "First Arg"; + String SECOND_ARG = "Second Arg"; + + // Generate a simple ERROR log. + loggerAdapter.warn(UnitTestMsgs.SIMPLE_WARN_LOG, null); + + // Validate that the message was parsed from the bundle resource. + logger.validateLogMsg("UT0001W This is a simple warning log with no arguments."); + + // Generate a WARNING log with arguments. + loggerAdapter.warn(UnitTestMsgs.WARN_LOG_WITH_ARGS, FIRST_ARG, SECOND_ARG); + + // Validate that the message was parsed from the bundle resource. + logger.validateLogMsg( + "UT0002W This is a warning log with some arguments " + FIRST_ARG + " and " + SECOND_ARG); + } + + /** This test validates that DEBUG level logs are correctly parsed from the + * resource bundle. */ + @Test + public void logStatementDebugParsingTest() { + + String FIRST_ARG = "First Arg"; + String SECOND_ARG = "Second Arg"; + String SIMPLE_DEBUG_MSG = "My simple debug message"; + + // Generate a simple DEBUG log with no error code. + loggerAdapter.debug(SIMPLE_DEBUG_MSG); + + // Validate that the message was parsed from the bundle resource. + logger.validateLogMsg(SIMPLE_DEBUG_MSG); + + // Generate an ERROR log with arguments. + loggerAdapter.debug(UnitTestMsgs.DEBUG_LOG_WITH_ARGS, FIRST_ARG, SECOND_ARG); + + // Validate that the message was parsed from the bundle resource. + logger.validateLogMsg( + "UT0001D This is a debug log with some arguments " + FIRST_ARG + " and " + SECOND_ARG); + } + + /** This test validates that TRACE level logs are correctly parsed from the + * resource bundle. */ + @Test + public void logStatementTraceParsingTest() { + + String FIRST_ARG = "First Arg"; + String SECOND_ARG = "Second Arg"; + + // Generate a simple TRACE log with no error code. + loggerAdapter.trace(UnitTestMsgs.SIMPLE_TRACE_LOG, null); + + // Validate that the message was parsed from the bundle resource. + logger.validateLogMsg("UT0001T This is a simple trace log with no arguments."); + logger.validateLogLevel(EELFLogger.Level.TRACE); + + // Generate an ERROR log with arguments. + loggerAdapter.trace(UnitTestMsgs.TRACE_LOG_WITH_ARGS, FIRST_ARG, SECOND_ARG); + + // Validate that the message was parsed from the bundle resource. + logger.validateLogMsg( + "UT0002T This is a trace log with some arguments " + FIRST_ARG + " and " + SECOND_ARG); + logger.validateLogLevel(EELFLogger.Level.TRACE); + } + + /** This is a convenience method that validates that a generated log message + * contains the expected values when a log code could not be parsed. + * + * @param aLogMessage + * - The log message to be validated. + * @param aLogCode + * - The error code that was passed to the logger. */ + private void assertBadLogCodeMessage(String aLogMessage, Enum aLogCode) { + + assertTrue("Expected 'unparseable log code' generic error string", + logger.getMessage().contains(AaiLoggerAdapter.BAD_ENUM_MSG)); + assertTrue("Expected error string to include log code", + logger.getMessage().contains(aLogCode.toString())); + } + + /** This test validates the formatMsg method returns a properly formatted + * message */ + @Test + public void formatMsgTest() { + + String FIRST_ARG = "First Arg"; + String SECOND_ARG = "Second Arg"; + String EXPECTED1 = "UT0001I This is a simple info log with no arguments."; + String EXPECTED2 = "UT0002I This is an info log with some arguments " + FIRST_ARG + " and " + + SECOND_ARG; + + String message1 = loggerAdapter.formatMsg(UnitTestMsgs.SIMPLE_INFO_LOG); + assertEquals("Invalid formatted msg1", message1, EXPECTED1); + + String message2 = loggerAdapter.formatMsg(UnitTestMsgs.INFO_LOG_WITH_ARGS, FIRST_ARG, + SECOND_ARG); + assertEquals("Invalid formatted msg2", message2, EXPECTED2); + } + + /** This is an implementation of the {@link EELFLogger} which just caches the + * last log statement passed to it and provides some convenience methods for + * validating the contents of the log message. + *

+ * The instance of the {@link AaiLoggerAdapter} that we are testing against + * will use this implementation instead of a real {@link EELFLogger}. */ + private class TestLogger implements EELFLogger { + + // Some indices to use for extracting specific fields from the + // log statement. + private static final int MESSAGE_INDEX = 1; + + private static final int METRICE_TRANS_ID_INDEX = 2; + private static final int METRICS_RESP_CODE_INDEX = 11; + private static final int METRICS_RESP_STRING_INDEX = 12; + private static final int METRICS_MSG_INDEX = 28; + + private static final int AUDIT_RESP_CODE_INDEX = 9; + private static final int AUDIT_RESP_STRING_INDEX = 10; + private static final int AUDIT_MSG_INDEX = 25; + + /** Stores the last log statement passed to the logger. */ + private String logMessage; + + private EELFLogger.Level logLevel; + + @Override + public void warn(String msg) { + logMessage = msg; + logLevel = EELFLogger.Level.WARN; + } + + @Override + public void debug(String msg) { + logMessage = msg; + logLevel = EELFLogger.Level.DEBUG; + } + + @Override + public void trace(String msg) { + logMessage = msg; + logLevel = EELFLogger.Level.TRACE; + } + + @Override + public void info(String msg) { + logMessage = msg; + logLevel = EELFLogger.Level.INFO; + } + + @Override + public void error(String msg) { + logMessage = msg; + logLevel = EELFLogger.Level.ERROR; + + } + + @Override + public void warn(String msg, Object... arguments) { + throw new UnsupportedOperationException( + "AAILoggerAdapter is not expected to call into this method."); + } + + @Override + public void warn(String msg, Throwable th) { + throw new UnsupportedOperationException( + "AAILoggerAdapter is not expected to call into this method."); + } + + @Override + public void debug(String msg, Object... arguments) { + throw new UnsupportedOperationException( + "AAILoggerAdapter is not expected to call into this method."); + } + + @Override + public void debug(String msg, Throwable th) { + throw new UnsupportedOperationException( + "AAILoggerAdapter is not expected to call into this method."); + } + + @Override + public void info(String msg, Object... arguments) { + throw new UnsupportedOperationException( + "AAILoggerAdapter is not expected to call into this method."); + } + + @Override + public void trace(String msg, Object... arguments) { + throw new UnsupportedOperationException( + "AAILoggerAdapter is not expected to call into this method."); + } + + @Override + public void trace(String msg, Throwable th) { + throw new UnsupportedOperationException( + "AAILoggerAdapter is not expected to call into this method."); + } + + @Override + public void error(String msg, Object... arguments) { + throw new UnsupportedOperationException( + "AAILoggerAdapter is not expected to call into this method."); + } + + @Override + public void error(String msg, Throwable th) { + throw new UnsupportedOperationException( + "AAILoggerAdapter is not expected to call into this method."); + } + + @Override + public boolean isTraceEnabled() { + return false; + } + + @Override + public boolean isInfoEnabled() { + return false; + } + + @Override + public boolean isErrorEnabled() { + return false; + } + + @Override + public boolean isWarnEnabled() { + return false; + } + + @Override + public boolean isDebugEnabled() { + return false; + } + + @Override + public void log(Level level, String msg, Throwable th, Object... arguments) { + throw new UnsupportedOperationException( + "AAILoggerAdapter is not expected to call into this method."); + } + + @Override + public void auditEvent(String msg, Object... arguments) { + throw new UnsupportedOperationException( + "AAILoggerAdapter is not expected to call into this method."); + } + + @Override + public void auditEvent(Level level, String msg, Object... arguments) { + throw new UnsupportedOperationException( + "AAILoggerAdapter is not expected to call into this method."); + } + + @Override + public void metricsEvent(String msg, Object... arguments) { + throw new UnsupportedOperationException( + "AAILoggerAdapter is not expected to call into this method."); + } + + @Override + public void metricsEvent(Level level, String msg, Object... arguments) { + throw new UnsupportedOperationException( + "AAILoggerAdapter is not expected to call into this method."); + } + + @Override + public void securityEvent(String msg, Object... arguments) { + throw new UnsupportedOperationException( + "AAILoggerAdapter is not expected to call into this method."); + } + + @Override + public void securityEvent(Level level, String msg, Object... arguments) { + throw new UnsupportedOperationException( + "AAILoggerAdapter is not expected to call into this method."); + } + + @Override + public void performanceEvent(String msg, Object... arguments) { + throw new UnsupportedOperationException( + "AAILoggerAdapter is not expected to call into this method."); + } + + @Override + public void performanceEvent(Level level, String msg, Object... arguments) { + throw new UnsupportedOperationException( + "AAILoggerAdapter is not expected to call into this method."); + } + + @Override + public void applicationEvent(String msg, Object... arguments) { + throw new UnsupportedOperationException( + "AAILoggerAdapter is not expected to call into this method."); + } + + @Override + public void applicationEvent(Level level, String msg, Object... arguments) { + throw new UnsupportedOperationException( + "AAILoggerAdapter is not expected to call into this method."); + } + + @Override + public void serverEvent(String msg, Object... arguments) { + throw new UnsupportedOperationException( + "AAILoggerAdapter is not expected to call into this method."); + } + + @Override + public void serverEvent(Level level, String msg, Object... arguments) { + throw new UnsupportedOperationException( + "AAILoggerAdapter is not expected to call into this method."); + } + + @Override + public void policyEvent(String msg, Object... arguments) { + throw new UnsupportedOperationException( + "AAILoggerAdapter is not expected to call into this method."); + } + + @Override + public void policyEvent(Level level, String msg, Object... arguments) { + throw new UnsupportedOperationException( + "AAILoggerAdapter is not expected to call into this method."); + } + + @Override + public void warn(Locale locale, EELFResolvableErrorEnum errorCode, Throwable th, + String... args) { + throw new UnsupportedOperationException( + "AAILoggerAdapter is not expected to call into this method."); + } + + @Override + public void info(Locale locale, EELFResolvableErrorEnum errorCode, Throwable th, + String... args) { + throw new UnsupportedOperationException( + "AAILoggerAdapter is not expected to call into this method."); + } + + @Override + public void debug(Locale locale, EELFResolvableErrorEnum errorCode, Throwable th, + String... args) { + throw new UnsupportedOperationException( + "AAILoggerAdapter is not expected to call into this method."); + } + + @Override + public void error(Locale locale, EELFResolvableErrorEnum errorCode, Throwable th, + String... args) { + throw new UnsupportedOperationException( + "AAILoggerAdapter is not expected to call into this method."); + } + + @Override + public void trace(Locale locale, EELFResolvableErrorEnum errorCode, Throwable th, + String... args) { + throw new UnsupportedOperationException( + "AAILoggerAdapter is not expected to call into this method."); + } + + @Override + public void warn(Locale locale, EELFResolvableErrorEnum errorCode, String... args) { + throw new UnsupportedOperationException( + "AAILoggerAdapter is not expected to call into this method."); + } + + @Override + public void info(Locale locale, EELFResolvableErrorEnum errorCode, String... args) { + throw new UnsupportedOperationException( + "AAILoggerAdapter is not expected to call into this method."); + } + + @Override + public void debug(Locale locale, EELFResolvableErrorEnum errorCode, String... args) { + throw new UnsupportedOperationException( + "AAILoggerAdapter is not expected to call into this method."); + } + + @Override + public void error(Locale locale, EELFResolvableErrorEnum errorCode, String... args) { + throw new UnsupportedOperationException( + "AAILoggerAdapter is not expected to call into this method."); + } + + @Override + public void trace(Locale locale, EELFResolvableErrorEnum errorCode, String... args) { + throw new UnsupportedOperationException( + "AAILoggerAdapter is not expected to call into this method."); + } + + @Override + public void warn(EELFResolvableErrorEnum errorCode, String... args) { + throw new UnsupportedOperationException( + "AAILoggerAdapter is not expected to call into this method."); + } + + @Override + public void info(EELFResolvableErrorEnum errorCode, String... args) { + throw new UnsupportedOperationException( + "AAILoggerAdapter is not expected to call into this method."); + } + + @Override + public void debug(EELFResolvableErrorEnum errorCode, String... args) { + throw new UnsupportedOperationException( + "AAILoggerAdapter is not expected to call into this method."); + } + + @Override + public void error(EELFResolvableErrorEnum errorCode, String... args) { + throw new UnsupportedOperationException( + "AAILoggerAdapter is not expected to call into this method."); + } + + @Override + public void trace(EELFResolvableErrorEnum errorCode, String... args) { + throw new UnsupportedOperationException( + "AAILoggerAdapter is not expected to call into this method."); + } + + @Override + public void warn(EELFResolvableErrorEnum errorCode, Throwable th, String... args) { + throw new UnsupportedOperationException( + "AAILoggerAdapter is not expected to call into this method."); + } + + @Override + public void info(EELFResolvableErrorEnum errorCode, Throwable th, String... args) { + throw new UnsupportedOperationException( + "AAILoggerAdapter is not expected to call into this method."); + } + + @Override + public void debug(EELFResolvableErrorEnum errorCode, Throwable th, String... args) { + throw new UnsupportedOperationException( + "AAILoggerAdapter is not expected to call into this method."); + } + + @Override + public void error(EELFResolvableErrorEnum errorCode, Throwable th, String... args) { + throw new UnsupportedOperationException( + "AAILoggerAdapter is not expected to call into this method."); + } + + @Override + public void trace(EELFResolvableErrorEnum errorCode, Throwable th, String... args) { + throw new UnsupportedOperationException( + "AAILoggerAdapter is not expected to call into this method."); + } + + @Override + public void setLevel(Level level) { + throw new UnsupportedOperationException( + "AAILoggerAdapter is not expected to call into this method."); + } + + @Override + public void disableLogging() { + throw new UnsupportedOperationException( + "AAILoggerAdapter is not expected to call into this method."); + } + + /** Convenience method to retrieve the log string that was produced by the + * logger. + * + * @return - A log string. */ + public String getMessage() { + return logMessage; + } + + /** Validates that the parsed log message encoded in the last produced log + * message matches the supplied expected value. + * + * @param aMessage + * - The expected log message. */ + public void validateLogMsg(String aMessage) { + + // Tokenize the log string. + String[] tokens = tokenizeLogString(); + + // Verify the log message. + assertTrue("Unexpected log message in log string", aMessage.equals(tokens[MESSAGE_INDEX])); + } + + public void validateLogFields(LogLineType logType, LogFields fields) { + + // Tokenize the log string. + String[] tokens = tokenizeLogString(); + + switch (logType) { + + case ERROR: + break; + + case METRICS: + if (fields.getField(DefinedFields.TARGET_SVC_NAME) != null) { + assertTrue(fields.getField(DefinedFields.TARGET_SVC_NAME).equals(tokens[9])); + } + if (fields.getField(DefinedFields.STATUS_CODE) != null) { + assertTrue(fields.getField(DefinedFields.STATUS_CODE).equals(tokens[10])); + } + if (fields.getField(DefinedFields.RESPONSE_CODE) != null) { + assertTrue(fields.getField(DefinedFields.RESPONSE_CODE).equals(tokens[11])); + } + if (fields.getField(DefinedFields.RESPONSE_DESCRIPTION) != null) { + assertTrue(fields.getField(DefinedFields.RESPONSE_DESCRIPTION).equals(tokens[12])); + } + if (fields.getField(DefinedFields.INSTANCE_UUID) != null) { + assertTrue(fields.getField(DefinedFields.INSTANCE_UUID).equals(tokens[13])); + } + if (fields.getField(DefinedFields.SEVERITY) != null) { + assertTrue(fields.getField(DefinedFields.SEVERITY).equals(tokens[15])); + } + if (fields.getField(DefinedFields.SERVER_IP) != null) { + assertTrue(fields.getField(DefinedFields.SERVER_IP).equals(tokens[16])); + } + if (fields.getField(DefinedFields.CLIENT_IP) != null) { + assertTrue(fields.getField(DefinedFields.CLIENT_IP).equals(tokens[19])); + } + if (fields.getField(DefinedFields.CLASS_NAME) != null) { + assertTrue(fields.getField(DefinedFields.CLASS_NAME).equals(tokens[20])); + } + if (fields.getField(DefinedFields.PROCESS_KEY) != null) { + assertTrue(fields.getField(DefinedFields.PROCESS_KEY).equals(tokens[22])); + } + if (fields.getField(DefinedFields.TARGET_ENTITY) != null) { + assertTrue(fields.getField(DefinedFields.TARGET_ENTITY).equals(tokens[23])); + } + if (fields.getField(DefinedFields.CUSTOM_1) != null) { + assertTrue(fields.getField(DefinedFields.CUSTOM_1).equals(tokens[24])); + } + if (fields.getField(DefinedFields.CUSTOM_2) != null) { + assertTrue(fields.getField(DefinedFields.CUSTOM_2).equals(tokens[25])); + } + if (fields.getField(DefinedFields.CUSTOM_3) != null) { + assertTrue(fields.getField(DefinedFields.CUSTOM_3).equals(tokens[26])); + } + if (fields.getField(DefinedFields.CUSTOM_4) != null) { + assertTrue(fields.getField(DefinedFields.CUSTOM_4).equals(tokens[27])); + } + break; + + case AUDIT: + if (fields.getField(DefinedFields.STATUS_CODE) != null) { + assertTrue(fields.getField(DefinedFields.STATUS_CODE).equals(tokens[8])); + } + if (fields.getField(DefinedFields.RESPONSE_CODE) != null) { + assertTrue(fields.getField(DefinedFields.RESPONSE_CODE).equals(tokens[9])); + } + if (fields.getField(DefinedFields.RESPONSE_DESCRIPTION) != null) { + assertTrue(fields.getField(DefinedFields.RESPONSE_DESCRIPTION).equals(tokens[10])); + } + if (fields.getField(DefinedFields.INSTANCE_UUID) != null) { + assertTrue(fields.getField(DefinedFields.INSTANCE_UUID).equals(tokens[11])); + } + if (fields.getField(DefinedFields.SEVERITY) != null) { + assertTrue(fields.getField(DefinedFields.SEVERITY).equals(tokens[13])); + } + if (fields.getField(DefinedFields.SERVER_IP) != null) { + assertTrue(fields.getField(DefinedFields.SERVER_IP).equals(tokens[14])); + } + if (fields.getField(DefinedFields.CLASS_NAME) != null) { + assertTrue(fields.getField(DefinedFields.CLASS_NAME).equals(tokens[18])); + } + if (fields.getField(DefinedFields.PROCESS_KEY) != null) { + assertTrue(fields.getField(DefinedFields.PROCESS_KEY).equals(tokens[20])); + } + if (fields.getField(DefinedFields.CUSTOM_1) != null) { + assertTrue(fields.getField(DefinedFields.CUSTOM_1).equals(tokens[21])); + } + if (fields.getField(DefinedFields.CUSTOM_2) != null) { + assertTrue(fields.getField(DefinedFields.CUSTOM_2).equals(tokens[22])); + } + if (fields.getField(DefinedFields.CUSTOM_3) != null) { + assertTrue(fields.getField(DefinedFields.CUSTOM_3).equals(tokens[23])); + } + if (fields.getField(DefinedFields.CUSTOM_4) != null) { + assertTrue(fields.getField(DefinedFields.CUSTOM_4).equals(tokens[24])); + } + break; + } + } + + private void validateMetricsMsg(String value) { + String[] tokens = tokenizeLogString(); + assertTrue("Unexpected message in log string", value.equals(tokens[METRICS_MSG_INDEX])); + } + + private void validateMetricsRespStatus(String code, String codeStr) { + String[] tokens = tokenizeLogString(); + assertTrue("Unexpected resp code in log string", + code.equals(tokens[METRICS_RESP_CODE_INDEX])); + assertTrue("Unexpected resp string in log string", + codeStr.equals(tokens[METRICS_RESP_STRING_INDEX])); + } + + private void validateMetricsRequestId(String value) { + String[] tokens = tokenizeLogString(); + assertTrue("Unexpected req id in log string", value.equals(tokens[METRICE_TRANS_ID_INDEX])); + } + + private void validateAuditMsg(String value) { + String[] tokens = tokenizeLogString(); + assertTrue("Unexpected message in log string", value.equals(tokens[AUDIT_MSG_INDEX])); + } + + private void validateAuditRespStatus(String code, String codeStr) { + String[] tokens = tokenizeLogString(); + assertTrue("Unexpected resp code in log string", code.equals(tokens[AUDIT_RESP_CODE_INDEX])); + assertTrue("Unexpected resp string in log string", + codeStr.equals(tokens[AUDIT_RESP_STRING_INDEX])); + } + + public void validateLogLevel(EELFLogger.Level expectedLevel) { + + assertEquals("Unexpected log level", expectedLevel, logLevel); + } + + /** This method breaks up the log string into individual tokenized fields, + * delimited by the '|' character. + * + * @return - Array of log message tokens. */ + private String[] tokenizeLogString() { + System.out.println("\n\n---\n" + logMessage + "\n-------"); + return logMessage.split("\\|"); + } + + } +} diff --git a/eelf-logging/src/test/java/org/onap/aai/cl/eelf/LoggerFactoryTest.java b/eelf-logging/src/test/java/org/onap/aai/cl/eelf/LoggerFactoryTest.java new file mode 100644 index 0000000..ebce994 --- /dev/null +++ b/eelf-logging/src/test/java/org/onap/aai/cl/eelf/LoggerFactoryTest.java @@ -0,0 +1,135 @@ +/*- + * ============LICENSE_START======================================================= + * Common Logging Library + * ================================================================================ + * 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.onap.aai.cl.eelf; + +import static org.junit.Assert.*; + +import org.junit.Test; +import org.onap.aai.cl.api.Logger; +import org.onap.aai.cl.eelf.LoggerFactory; + +/** This suite of tests is intended to exercise the basic functionality of the + * {@link LoggerFactory}. */ +public class LoggerFactoryTest { + + /** This test validates that the {@link LoggerFactory} is a singleton. */ + @Test + public void loggerFactorySingletonTest() { + + // Call getInstance() on the LoggerFactory twice. + LoggerFactory loggerFactory1 = LoggerFactory.getInstance(); + LoggerFactory loggerFactory2 = LoggerFactory.getInstance(); + + // Validate that what we got was two references to the same instance + // of the LoggerFactory (ie: yes, it really is a singleton). + assertTrue("Expected references to the SAME LoggerFactory instance", + loggerFactory1 == loggerFactory2); + } + + /** This test validates that we can request {@link Logger} instances from the + * {@link LoggerFactory} by specifying either a name to use as the logger's + * identifier, or a class. */ + @Test + public void getLoggerTest() { + + // Get an instance of the LoggerFactory. + LoggerFactory loggerFactory = LoggerFactory.getInstance(); + + // Request a Logger instance by specifying the name we want for + // the logger. + Logger myLoggerByName = loggerFactory.getLogger("UnitTestLogger"); + + // Validate that we got a logger back. + assertNotNull(myLoggerByName); + + // Now, request a Logger instance by specifying a class as our logger + // identifier. + Logger myLoggerByClass = loggerFactory.getLogger(LoggerFactoryTest.class); + + // Validate that we got a logger back. + assertNotNull(myLoggerByClass); + } + + /** This test validates that the {@link LoggerFactory} will only produce a + * single unique {@link Logger} instance for each requested log name. + *

+ * In other words, two requests for a {@link Logger} with the same name will + * produce two references to the same instance, not two unique {@link Logger} + * instances. */ + @Test + public void getLoggerSingleInstanceForNameTest() { + + // Get an instance of the LoggerFactory. + LoggerFactory loggerFactory = LoggerFactory.getInstance(); + + // Request a Logger instance by specifying the name we want for + // the logger. + Logger myFirstLogger = loggerFactory.getLogger("UnitTestLogger"); + + // Request another Logger instance, but specify the same name for + // the logger's identifier. + Logger mySecondLogger = loggerFactory.getLogger("UnitTestLogger"); + + // Validate, that because there was already a Logger instance with the + // specified name, we just get back a reference to that instance. + assertTrue("Expected references to the same logger instance", myFirstLogger == mySecondLogger); + + // Now, make a third logger request, but specify a different name. + Logger myThirdLogger = loggerFactory.getLogger("AnotherUnitTestLogger"); + + // Validate that, in this case, we really do get a new instance. + assertFalse("Expected a unique logger instance", myFirstLogger == myThirdLogger); + assertFalse("Expected a unique logger instance", mySecondLogger == myThirdLogger); + } + + /** This test validates that the {@link LoggerFactory} will only produce a + * single unique {@link Logger} instance for each requested class. + *

+ * In other words, two requests for a {@link Logger} with the same class will + * produce two references to the same instance, not two unique {@link Logger} + * instances. */ + @Test + public void getLoggerSingleInstanceForClassTest() { + + // Get an instance of the LoggerFactory. + LoggerFactory loggerFactory = LoggerFactory.getInstance(); + + // Request a Logger instance by specifying the class to use as the + // logger's identifier. + Logger myFirstLogger = loggerFactory.getLogger(LoggerFactoryTest.class); + + // Request another Logger instance, but specify the same class for + // the logger's identifier. + Logger mySecondLogger = loggerFactory.getLogger(LoggerFactoryTest.class); + + // Validate, that because there was already a Logger instance with the + // specified class, we just get back a reference to that instance. + assertTrue("Expected references to the same logger instance", myFirstLogger == mySecondLogger); + + // Now, make a third logger request, but specify a different class. + Logger myThirdLogger = loggerFactory.getLogger(LoggerFactory.class); + + // Validate that, in this case, we really do get a new instance. + assertFalse("Expected a unique logger instance", myFirstLogger == myThirdLogger); + assertFalse("Expected a unique logger instance", mySecondLogger == myThirdLogger); + } +} diff --git a/eelf-logging/src/test/java/org/onap/aai/cl/eelf/UnitTestMsgs.java b/eelf-logging/src/test/java/org/onap/aai/cl/eelf/UnitTestMsgs.java new file mode 100644 index 0000000..228ec08 --- /dev/null +++ b/eelf-logging/src/test/java/org/onap/aai/cl/eelf/UnitTestMsgs.java @@ -0,0 +1,45 @@ +/*- + * ============LICENSE_START======================================================= + * Common Logging Library + * ================================================================================ + * 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.onap.aai.cl.eelf; + +import org.onap.aai.cl.eelf.LogMessageEnum; + +import com.att.eelf.i18n.EELFResourceManager; + +public enum UnitTestMsgs implements LogMessageEnum { + + SIMPLE_INFO_LOG, + INFO_LOG_WITH_ARGS, + SIMPLE_ERROR_LOG, + ERROR_LOG_WITH_ARGS, + SIMPLE_WARN_LOG, + WARN_LOG_WITH_ARGS, + SIMPLE_TRACE_LOG, + TRACE_LOG_WITH_ARGS, + DEBUG_LOG_WITH_ARGS; + + /** Static initializer to ensure the resource bundles for this class are + * loaded... */ + static { + EELFResourceManager.loadMessageBundle("logging/UnitTestMsgs"); + } +} diff --git a/eelf-logging/src/test/java/org/openecomp/cl/eelf/AAILoggerAdapterTest.java b/eelf-logging/src/test/java/org/openecomp/cl/eelf/AAILoggerAdapterTest.java deleted file mode 100644 index 0992d5f..0000000 --- a/eelf-logging/src/test/java/org/openecomp/cl/eelf/AAILoggerAdapterTest.java +++ /dev/null @@ -1,824 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Common Logging Library - * ================================================================================ - * 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.cl.eelf; - -import static org.junit.Assert.*; - -import java.util.Locale; - -import org.junit.Before; -import org.junit.Test; -import org.openecomp.cl.eelf.AaiLoggerAdapter; -import org.openecomp.cl.api.LogFields; -import org.openecomp.cl.api.LogLine; -import org.openecomp.cl.api.LogLine.DefinedFields; -import org.openecomp.cl.api.LogLine.LogLineType; -import org.openecomp.cl.mdc.MdcContext; -import org.openecomp.cl.mdc.MdcOverride; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.i18n.EELFResolvableErrorEnum; - -/** This suite of tests is intended to validate the functionality of our wrapper - * around the {@link EELFLogger}. */ -public class AAILoggerAdapterTest { - - private enum InvalidLogCodeEnum { - BAD_LOGCODE1 - } - - private static final String LOGGER_NAME = "UnitTestLogAdapter"; - private static final String METRICS_LOGGER_NAME = "UnitTestMetricsLogAdapter"; - private static final String AUDIT_LOGGER_NAME = "UnitTestAuditLogAdapter"; - - private TestLogger logger; - private AaiLoggerAdapter loggerAdapter; - private AaiLoggerAdapter metricsLoggerAdapter; - private AaiLoggerAdapter auditLoggerAdapter; - - @Before - public void setup() { - logger = new TestLogger(); - loggerAdapter = new AaiLoggerAdapter(logger, LogLineType.ERROR, LOGGER_NAME); - metricsLoggerAdapter = new AaiLoggerAdapter(logger, LogLineType.METRICS, METRICS_LOGGER_NAME); - auditLoggerAdapter = new AaiLoggerAdapter(logger, LogLineType.AUDIT, AUDIT_LOGGER_NAME); - } - - /** This test validates the the {@link AaiLoggerAdapter} is able to deal with - * log code enums which do not extend the {@link EELFResolvableEnum} - * placeholder (meaning that the EELF framework would not know how to parse - * them). */ - @Test - public void badLogCodeEnumTest() { - - // For each supported log level, validate that if a log code is - // specified which does not extend EELFResolvableEnum, then a - // generic 'unparsable log code' statement is generated instead - // of a correctly parsed log statement. - - loggerAdapter.info(InvalidLogCodeEnum.BAD_LOGCODE1, "arg1"); - assertBadLogCodeMessage(logger.getMessage(), InvalidLogCodeEnum.BAD_LOGCODE1); - - loggerAdapter.debug(InvalidLogCodeEnum.BAD_LOGCODE1, "arg1", "arg2"); - assertBadLogCodeMessage(logger.getMessage(), InvalidLogCodeEnum.BAD_LOGCODE1); - - loggerAdapter.warn(InvalidLogCodeEnum.BAD_LOGCODE1, "arg1", "arg2"); - assertBadLogCodeMessage(logger.getMessage(), InvalidLogCodeEnum.BAD_LOGCODE1); - - loggerAdapter.error(InvalidLogCodeEnum.BAD_LOGCODE1, "arg1", "arg2", "arg3"); - assertBadLogCodeMessage(logger.getMessage(), InvalidLogCodeEnum.BAD_LOGCODE1); - - loggerAdapter.error(InvalidLogCodeEnum.BAD_LOGCODE1, new LogFields(), - new Throwable("Some exception"), "arg1"); - assertBadLogCodeMessage(logger.getMessage(), InvalidLogCodeEnum.BAD_LOGCODE1); - } - - /** This test validates that INFO level logs are correctly parsed from the - * resource bundle. */ - @Test - public void logStatementInfoParsingTest() { - - String FIRST_ARG = "First Arg"; - String SECOND_ARG = "Second Arg"; - - // Generate a simple INFO log. - loggerAdapter.info(UnitTestMsgs.SIMPLE_INFO_LOG, null); - - // Validate that the message was parsed from the bundle resource. - logger.validateLogMsg("UT0001I This is a simple info log with no arguments."); - - // Generate an INFO log with arguments. - LogFields fields = new LogFields().setField(LogLine.DefinedFields.TARGET_SVC_NAME, "test"); - loggerAdapter.info(UnitTestMsgs.INFO_LOG_WITH_ARGS, fields, FIRST_ARG, SECOND_ARG); - - // Validate that the message was parsed from the bundle resource. - logger.validateLogMsg( - "UT0002I This is an info log with some arguments " + FIRST_ARG + " and " + SECOND_ARG); - - // Validate that log fields are being correctly populated. - logger.validateLogFields(LogLineType.ERROR, fields); - } - - /** Validate metrics log */ - @Test - public void logStatementMetricsTest() { - // Generate an INFO log with arguments. - MdcContext.initialize("xx-yy-zz", "MyService", "MyInstance", "MyPartner", "12.0.0.2"); - metricsLoggerAdapter.info(UnitTestMsgs.INFO_LOG_WITH_ARGS, - new LogFields().setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION, "Accepted") - .setField(LogLine.DefinedFields.RESPONSE_CODE, 202), - "arg1", "arg2"); - - // Validate that the log code is correctly encoded in the log statement - // and that the message was parsed from the bundle resource. - logger.validateMetricsMsg("UT0002I This is an info log with some arguments arg1 and arg2"); - logger.validateMetricsRespStatus("202", "Accepted"); - - // Validate MDC override - MdcOverride override = new MdcOverride(); - override.addAttribute(MdcContext.MDC_REQUEST_ID, "New-requestID"); - - LogFields fields = new LogFields() - .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION, "Accepted") - .setField(LogLine.DefinedFields.RESPONSE_CODE, 202); - - metricsLoggerAdapter.info(UnitTestMsgs.INFO_LOG_WITH_ARGS, fields, override, "arg1", "arg2"); - logger.validateMetricsRequestId("New-requestID"); - - // Validate that log fields are being correctly populated. - logger.validateLogFields(LogLineType.METRICS, fields); - } - - /** Validate metrics log */ - @Test - public void logStatementAuditTest() { - // Generate an INFO log with arguments. - MdcContext.initialize("xx-yy-aa", "MyService", "MyInstance", "MyPartner", "12.0.0.8"); - LogFields fields = new LogFields() - .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION, "Accepted") - .setField(LogLine.DefinedFields.RESPONSE_CODE, 202); - auditLoggerAdapter.info(UnitTestMsgs.INFO_LOG_WITH_ARGS, fields, "arg1", "arg2"); - - // Validate that the log code is correctly encoded in the log statement - // and that the message was parsed from the bundle resource. - logger.validateAuditMsg("UT0002I This is an info log with some arguments arg1 and arg2"); - logger.validateAuditRespStatus("202", "Accepted"); - - // Validate that log fields are being correctly populated. - logger.validateLogFields(LogLineType.AUDIT, fields); - } - - /** This test validates that ERROR level logs are correctly parsed from the - * resource bundle. */ - @Test - public void logStatementErrorParsingTest() { - - String FIRST_ARG = "First Arg"; - String SECOND_ARG = "Second Arg"; - - // Generate a simple ERROR log. - loggerAdapter.error(UnitTestMsgs.SIMPLE_ERROR_LOG, null); - - // Validate that the message was parsed from the bundle resource. - logger.validateLogMsg("UT0001E This is a simple error log with no arguments."); - - // Generate an ERROR log with arguments. - loggerAdapter.error(UnitTestMsgs.ERROR_LOG_WITH_ARGS, new LogFields(), FIRST_ARG, SECOND_ARG); - - // Validate that the message was parsed from the bundle resource. - logger.validateLogMsg( - "UT0002E This is an error log with some arguments " + FIRST_ARG + " and " + SECOND_ARG); - } - - /** This test validates that WARNING level logs are correctly parsed from the - * resource bundle. */ - @Test - public void logStatementWarnParsingTest() { - - String FIRST_ARG = "First Arg"; - String SECOND_ARG = "Second Arg"; - - // Generate a simple ERROR log. - loggerAdapter.warn(UnitTestMsgs.SIMPLE_WARN_LOG, null); - - // Validate that the message was parsed from the bundle resource. - logger.validateLogMsg("UT0001W This is a simple warning log with no arguments."); - - // Generate a WARNING log with arguments. - loggerAdapter.warn(UnitTestMsgs.WARN_LOG_WITH_ARGS, FIRST_ARG, SECOND_ARG); - - // Validate that the message was parsed from the bundle resource. - logger.validateLogMsg( - "UT0002W This is a warning log with some arguments " + FIRST_ARG + " and " + SECOND_ARG); - } - - /** This test validates that DEBUG level logs are correctly parsed from the - * resource bundle. */ - @Test - public void logStatementDebugParsingTest() { - - String FIRST_ARG = "First Arg"; - String SECOND_ARG = "Second Arg"; - String SIMPLE_DEBUG_MSG = "My simple debug message"; - - // Generate a simple DEBUG log with no error code. - loggerAdapter.debug(SIMPLE_DEBUG_MSG); - - // Validate that the message was parsed from the bundle resource. - logger.validateLogMsg(SIMPLE_DEBUG_MSG); - - // Generate an ERROR log with arguments. - loggerAdapter.debug(UnitTestMsgs.DEBUG_LOG_WITH_ARGS, FIRST_ARG, SECOND_ARG); - - // Validate that the message was parsed from the bundle resource. - logger.validateLogMsg( - "UT0001D This is a debug log with some arguments " + FIRST_ARG + " and " + SECOND_ARG); - } - - /** This test validates that TRACE level logs are correctly parsed from the - * resource bundle. */ - @Test - public void logStatementTraceParsingTest() { - - String FIRST_ARG = "First Arg"; - String SECOND_ARG = "Second Arg"; - - // Generate a simple TRACE log with no error code. - loggerAdapter.trace(UnitTestMsgs.SIMPLE_TRACE_LOG, null); - - // Validate that the message was parsed from the bundle resource. - logger.validateLogMsg("UT0001T This is a simple trace log with no arguments."); - logger.validateLogLevel(EELFLogger.Level.TRACE); - - // Generate an ERROR log with arguments. - loggerAdapter.trace(UnitTestMsgs.TRACE_LOG_WITH_ARGS, FIRST_ARG, SECOND_ARG); - - // Validate that the message was parsed from the bundle resource. - logger.validateLogMsg( - "UT0002T This is a trace log with some arguments " + FIRST_ARG + " and " + SECOND_ARG); - logger.validateLogLevel(EELFLogger.Level.TRACE); - } - - /** This is a convenience method that validates that a generated log message - * contains the expected values when a log code could not be parsed. - * - * @param aLogMessage - * - The log message to be validated. - * @param aLogCode - * - The error code that was passed to the logger. */ - private void assertBadLogCodeMessage(String aLogMessage, Enum aLogCode) { - - assertTrue("Expected 'unparseable log code' generic error string", - logger.getMessage().contains(AaiLoggerAdapter.BAD_ENUM_MSG)); - assertTrue("Expected error string to include log code", - logger.getMessage().contains(aLogCode.toString())); - } - - /** This test validates the formatMsg method returns a properly formatted - * message */ - @Test - public void formatMsgTest() { - - String FIRST_ARG = "First Arg"; - String SECOND_ARG = "Second Arg"; - String EXPECTED1 = "UT0001I This is a simple info log with no arguments."; - String EXPECTED2 = "UT0002I This is an info log with some arguments " + FIRST_ARG + " and " - + SECOND_ARG; - - String message1 = loggerAdapter.formatMsg(UnitTestMsgs.SIMPLE_INFO_LOG); - assertEquals("Invalid formatted msg1", message1, EXPECTED1); - - String message2 = loggerAdapter.formatMsg(UnitTestMsgs.INFO_LOG_WITH_ARGS, FIRST_ARG, - SECOND_ARG); - assertEquals("Invalid formatted msg2", message2, EXPECTED2); - } - - /** This is an implementation of the {@link EELFLogger} which just caches the - * last log statement passed to it and provides some convenience methods for - * validating the contents of the log message. - *

- * The instance of the {@link AaiLoggerAdapter} that we are testing against - * will use this implementation instead of a real {@link EELFLogger}. */ - private class TestLogger implements EELFLogger { - - // Some indices to use for extracting specific fields from the - // log statement. - private static final int MESSAGE_INDEX = 1; - - private static final int METRICE_TRANS_ID_INDEX = 2; - private static final int METRICS_RESP_CODE_INDEX = 11; - private static final int METRICS_RESP_STRING_INDEX = 12; - private static final int METRICS_MSG_INDEX = 28; - - private static final int AUDIT_RESP_CODE_INDEX = 9; - private static final int AUDIT_RESP_STRING_INDEX = 10; - private static final int AUDIT_MSG_INDEX = 25; - - /** Stores the last log statement passed to the logger. */ - private String logMessage; - - private EELFLogger.Level logLevel; - - @Override - public void warn(String msg) { - logMessage = msg; - logLevel = EELFLogger.Level.WARN; - } - - @Override - public void debug(String msg) { - logMessage = msg; - logLevel = EELFLogger.Level.DEBUG; - } - - @Override - public void trace(String msg) { - logMessage = msg; - logLevel = EELFLogger.Level.TRACE; - } - - @Override - public void info(String msg) { - logMessage = msg; - logLevel = EELFLogger.Level.INFO; - } - - @Override - public void error(String msg) { - logMessage = msg; - logLevel = EELFLogger.Level.ERROR; - - } - - @Override - public void warn(String msg, Object... arguments) { - throw new UnsupportedOperationException( - "AAILoggerAdapter is not expected to call into this method."); - } - - @Override - public void warn(String msg, Throwable th) { - throw new UnsupportedOperationException( - "AAILoggerAdapter is not expected to call into this method."); - } - - @Override - public void debug(String msg, Object... arguments) { - throw new UnsupportedOperationException( - "AAILoggerAdapter is not expected to call into this method."); - } - - @Override - public void debug(String msg, Throwable th) { - throw new UnsupportedOperationException( - "AAILoggerAdapter is not expected to call into this method."); - } - - @Override - public void info(String msg, Object... arguments) { - throw new UnsupportedOperationException( - "AAILoggerAdapter is not expected to call into this method."); - } - - @Override - public void trace(String msg, Object... arguments) { - throw new UnsupportedOperationException( - "AAILoggerAdapter is not expected to call into this method."); - } - - @Override - public void trace(String msg, Throwable th) { - throw new UnsupportedOperationException( - "AAILoggerAdapter is not expected to call into this method."); - } - - @Override - public void error(String msg, Object... arguments) { - throw new UnsupportedOperationException( - "AAILoggerAdapter is not expected to call into this method."); - } - - @Override - public void error(String msg, Throwable th) { - throw new UnsupportedOperationException( - "AAILoggerAdapter is not expected to call into this method."); - } - - @Override - public boolean isTraceEnabled() { - return false; - } - - @Override - public boolean isInfoEnabled() { - return false; - } - - @Override - public boolean isErrorEnabled() { - return false; - } - - @Override - public boolean isWarnEnabled() { - return false; - } - - @Override - public boolean isDebugEnabled() { - return false; - } - - @Override - public void log(Level level, String msg, Throwable th, Object... arguments) { - throw new UnsupportedOperationException( - "AAILoggerAdapter is not expected to call into this method."); - } - - @Override - public void auditEvent(String msg, Object... arguments) { - throw new UnsupportedOperationException( - "AAILoggerAdapter is not expected to call into this method."); - } - - @Override - public void auditEvent(Level level, String msg, Object... arguments) { - throw new UnsupportedOperationException( - "AAILoggerAdapter is not expected to call into this method."); - } - - @Override - public void metricsEvent(String msg, Object... arguments) { - throw new UnsupportedOperationException( - "AAILoggerAdapter is not expected to call into this method."); - } - - @Override - public void metricsEvent(Level level, String msg, Object... arguments) { - throw new UnsupportedOperationException( - "AAILoggerAdapter is not expected to call into this method."); - } - - @Override - public void securityEvent(String msg, Object... arguments) { - throw new UnsupportedOperationException( - "AAILoggerAdapter is not expected to call into this method."); - } - - @Override - public void securityEvent(Level level, String msg, Object... arguments) { - throw new UnsupportedOperationException( - "AAILoggerAdapter is not expected to call into this method."); - } - - @Override - public void performanceEvent(String msg, Object... arguments) { - throw new UnsupportedOperationException( - "AAILoggerAdapter is not expected to call into this method."); - } - - @Override - public void performanceEvent(Level level, String msg, Object... arguments) { - throw new UnsupportedOperationException( - "AAILoggerAdapter is not expected to call into this method."); - } - - @Override - public void applicationEvent(String msg, Object... arguments) { - throw new UnsupportedOperationException( - "AAILoggerAdapter is not expected to call into this method."); - } - - @Override - public void applicationEvent(Level level, String msg, Object... arguments) { - throw new UnsupportedOperationException( - "AAILoggerAdapter is not expected to call into this method."); - } - - @Override - public void serverEvent(String msg, Object... arguments) { - throw new UnsupportedOperationException( - "AAILoggerAdapter is not expected to call into this method."); - } - - @Override - public void serverEvent(Level level, String msg, Object... arguments) { - throw new UnsupportedOperationException( - "AAILoggerAdapter is not expected to call into this method."); - } - - @Override - public void policyEvent(String msg, Object... arguments) { - throw new UnsupportedOperationException( - "AAILoggerAdapter is not expected to call into this method."); - } - - @Override - public void policyEvent(Level level, String msg, Object... arguments) { - throw new UnsupportedOperationException( - "AAILoggerAdapter is not expected to call into this method."); - } - - @Override - public void warn(Locale locale, EELFResolvableErrorEnum errorCode, Throwable th, - String... args) { - throw new UnsupportedOperationException( - "AAILoggerAdapter is not expected to call into this method."); - } - - @Override - public void info(Locale locale, EELFResolvableErrorEnum errorCode, Throwable th, - String... args) { - throw new UnsupportedOperationException( - "AAILoggerAdapter is not expected to call into this method."); - } - - @Override - public void debug(Locale locale, EELFResolvableErrorEnum errorCode, Throwable th, - String... args) { - throw new UnsupportedOperationException( - "AAILoggerAdapter is not expected to call into this method."); - } - - @Override - public void error(Locale locale, EELFResolvableErrorEnum errorCode, Throwable th, - String... args) { - throw new UnsupportedOperationException( - "AAILoggerAdapter is not expected to call into this method."); - } - - @Override - public void trace(Locale locale, EELFResolvableErrorEnum errorCode, Throwable th, - String... args) { - throw new UnsupportedOperationException( - "AAILoggerAdapter is not expected to call into this method."); - } - - @Override - public void warn(Locale locale, EELFResolvableErrorEnum errorCode, String... args) { - throw new UnsupportedOperationException( - "AAILoggerAdapter is not expected to call into this method."); - } - - @Override - public void info(Locale locale, EELFResolvableErrorEnum errorCode, String... args) { - throw new UnsupportedOperationException( - "AAILoggerAdapter is not expected to call into this method."); - } - - @Override - public void debug(Locale locale, EELFResolvableErrorEnum errorCode, String... args) { - throw new UnsupportedOperationException( - "AAILoggerAdapter is not expected to call into this method."); - } - - @Override - public void error(Locale locale, EELFResolvableErrorEnum errorCode, String... args) { - throw new UnsupportedOperationException( - "AAILoggerAdapter is not expected to call into this method."); - } - - @Override - public void trace(Locale locale, EELFResolvableErrorEnum errorCode, String... args) { - throw new UnsupportedOperationException( - "AAILoggerAdapter is not expected to call into this method."); - } - - @Override - public void warn(EELFResolvableErrorEnum errorCode, String... args) { - throw new UnsupportedOperationException( - "AAILoggerAdapter is not expected to call into this method."); - } - - @Override - public void info(EELFResolvableErrorEnum errorCode, String... args) { - throw new UnsupportedOperationException( - "AAILoggerAdapter is not expected to call into this method."); - } - - @Override - public void debug(EELFResolvableErrorEnum errorCode, String... args) { - throw new UnsupportedOperationException( - "AAILoggerAdapter is not expected to call into this method."); - } - - @Override - public void error(EELFResolvableErrorEnum errorCode, String... args) { - throw new UnsupportedOperationException( - "AAILoggerAdapter is not expected to call into this method."); - } - - @Override - public void trace(EELFResolvableErrorEnum errorCode, String... args) { - throw new UnsupportedOperationException( - "AAILoggerAdapter is not expected to call into this method."); - } - - @Override - public void warn(EELFResolvableErrorEnum errorCode, Throwable th, String... args) { - throw new UnsupportedOperationException( - "AAILoggerAdapter is not expected to call into this method."); - } - - @Override - public void info(EELFResolvableErrorEnum errorCode, Throwable th, String... args) { - throw new UnsupportedOperationException( - "AAILoggerAdapter is not expected to call into this method."); - } - - @Override - public void debug(EELFResolvableErrorEnum errorCode, Throwable th, String... args) { - throw new UnsupportedOperationException( - "AAILoggerAdapter is not expected to call into this method."); - } - - @Override - public void error(EELFResolvableErrorEnum errorCode, Throwable th, String... args) { - throw new UnsupportedOperationException( - "AAILoggerAdapter is not expected to call into this method."); - } - - @Override - public void trace(EELFResolvableErrorEnum errorCode, Throwable th, String... args) { - throw new UnsupportedOperationException( - "AAILoggerAdapter is not expected to call into this method."); - } - - @Override - public void setLevel(Level level) { - throw new UnsupportedOperationException( - "AAILoggerAdapter is not expected to call into this method."); - } - - @Override - public void disableLogging() { - throw new UnsupportedOperationException( - "AAILoggerAdapter is not expected to call into this method."); - } - - /** Convenience method to retrieve the log string that was produced by the - * logger. - * - * @return - A log string. */ - public String getMessage() { - return logMessage; - } - - /** Validates that the parsed log message encoded in the last produced log - * message matches the supplied expected value. - * - * @param aMessage - * - The expected log message. */ - public void validateLogMsg(String aMessage) { - - // Tokenize the log string. - String[] tokens = tokenizeLogString(); - - // Verify the log message. - assertTrue("Unexpected log message in log string", aMessage.equals(tokens[MESSAGE_INDEX])); - } - - public void validateLogFields(LogLineType logType, LogFields fields) { - - // Tokenize the log string. - String[] tokens = tokenizeLogString(); - - switch (logType) { - - case ERROR: - break; - - case METRICS: - if (fields.getField(DefinedFields.TARGET_SVC_NAME) != null) { - assertTrue(fields.getField(DefinedFields.TARGET_SVC_NAME).equals(tokens[9])); - } - if (fields.getField(DefinedFields.STATUS_CODE) != null) { - assertTrue(fields.getField(DefinedFields.STATUS_CODE).equals(tokens[10])); - } - if (fields.getField(DefinedFields.RESPONSE_CODE) != null) { - assertTrue(fields.getField(DefinedFields.RESPONSE_CODE).equals(tokens[11])); - } - if (fields.getField(DefinedFields.RESPONSE_DESCRIPTION) != null) { - assertTrue(fields.getField(DefinedFields.RESPONSE_DESCRIPTION).equals(tokens[12])); - } - if (fields.getField(DefinedFields.INSTANCE_UUID) != null) { - assertTrue(fields.getField(DefinedFields.INSTANCE_UUID).equals(tokens[13])); - } - if (fields.getField(DefinedFields.SEVERITY) != null) { - assertTrue(fields.getField(DefinedFields.SEVERITY).equals(tokens[15])); - } - if (fields.getField(DefinedFields.SERVER_IP) != null) { - assertTrue(fields.getField(DefinedFields.SERVER_IP).equals(tokens[16])); - } - if (fields.getField(DefinedFields.CLIENT_IP) != null) { - assertTrue(fields.getField(DefinedFields.CLIENT_IP).equals(tokens[19])); - } - if (fields.getField(DefinedFields.CLASS_NAME) != null) { - assertTrue(fields.getField(DefinedFields.CLASS_NAME).equals(tokens[20])); - } - if (fields.getField(DefinedFields.PROCESS_KEY) != null) { - assertTrue(fields.getField(DefinedFields.PROCESS_KEY).equals(tokens[22])); - } - if (fields.getField(DefinedFields.TARGET_ENTITY) != null) { - assertTrue(fields.getField(DefinedFields.TARGET_ENTITY).equals(tokens[23])); - } - if (fields.getField(DefinedFields.CUSTOM_1) != null) { - assertTrue(fields.getField(DefinedFields.CUSTOM_1).equals(tokens[24])); - } - if (fields.getField(DefinedFields.CUSTOM_2) != null) { - assertTrue(fields.getField(DefinedFields.CUSTOM_2).equals(tokens[25])); - } - if (fields.getField(DefinedFields.CUSTOM_3) != null) { - assertTrue(fields.getField(DefinedFields.CUSTOM_3).equals(tokens[26])); - } - if (fields.getField(DefinedFields.CUSTOM_4) != null) { - assertTrue(fields.getField(DefinedFields.CUSTOM_4).equals(tokens[27])); - } - break; - - case AUDIT: - if (fields.getField(DefinedFields.STATUS_CODE) != null) { - assertTrue(fields.getField(DefinedFields.STATUS_CODE).equals(tokens[8])); - } - if (fields.getField(DefinedFields.RESPONSE_CODE) != null) { - assertTrue(fields.getField(DefinedFields.RESPONSE_CODE).equals(tokens[9])); - } - if (fields.getField(DefinedFields.RESPONSE_DESCRIPTION) != null) { - assertTrue(fields.getField(DefinedFields.RESPONSE_DESCRIPTION).equals(tokens[10])); - } - if (fields.getField(DefinedFields.INSTANCE_UUID) != null) { - assertTrue(fields.getField(DefinedFields.INSTANCE_UUID).equals(tokens[11])); - } - if (fields.getField(DefinedFields.SEVERITY) != null) { - assertTrue(fields.getField(DefinedFields.SEVERITY).equals(tokens[13])); - } - if (fields.getField(DefinedFields.SERVER_IP) != null) { - assertTrue(fields.getField(DefinedFields.SERVER_IP).equals(tokens[14])); - } - if (fields.getField(DefinedFields.CLASS_NAME) != null) { - assertTrue(fields.getField(DefinedFields.CLASS_NAME).equals(tokens[18])); - } - if (fields.getField(DefinedFields.PROCESS_KEY) != null) { - assertTrue(fields.getField(DefinedFields.PROCESS_KEY).equals(tokens[20])); - } - if (fields.getField(DefinedFields.CUSTOM_1) != null) { - assertTrue(fields.getField(DefinedFields.CUSTOM_1).equals(tokens[21])); - } - if (fields.getField(DefinedFields.CUSTOM_2) != null) { - assertTrue(fields.getField(DefinedFields.CUSTOM_2).equals(tokens[22])); - } - if (fields.getField(DefinedFields.CUSTOM_3) != null) { - assertTrue(fields.getField(DefinedFields.CUSTOM_3).equals(tokens[23])); - } - if (fields.getField(DefinedFields.CUSTOM_4) != null) { - assertTrue(fields.getField(DefinedFields.CUSTOM_4).equals(tokens[24])); - } - break; - } - } - - private void validateMetricsMsg(String value) { - String[] tokens = tokenizeLogString(); - assertTrue("Unexpected message in log string", value.equals(tokens[METRICS_MSG_INDEX])); - } - - private void validateMetricsRespStatus(String code, String codeStr) { - String[] tokens = tokenizeLogString(); - assertTrue("Unexpected resp code in log string", - code.equals(tokens[METRICS_RESP_CODE_INDEX])); - assertTrue("Unexpected resp string in log string", - codeStr.equals(tokens[METRICS_RESP_STRING_INDEX])); - } - - private void validateMetricsRequestId(String value) { - String[] tokens = tokenizeLogString(); - assertTrue("Unexpected req id in log string", value.equals(tokens[METRICE_TRANS_ID_INDEX])); - } - - private void validateAuditMsg(String value) { - String[] tokens = tokenizeLogString(); - assertTrue("Unexpected message in log string", value.equals(tokens[AUDIT_MSG_INDEX])); - } - - private void validateAuditRespStatus(String code, String codeStr) { - String[] tokens = tokenizeLogString(); - assertTrue("Unexpected resp code in log string", code.equals(tokens[AUDIT_RESP_CODE_INDEX])); - assertTrue("Unexpected resp string in log string", - codeStr.equals(tokens[AUDIT_RESP_STRING_INDEX])); - } - - public void validateLogLevel(EELFLogger.Level expectedLevel) { - - assertEquals("Unexpected log level", expectedLevel, logLevel); - } - - /** This method breaks up the log string into individual tokenized fields, - * delimited by the '|' character. - * - * @return - Array of log message tokens. */ - private String[] tokenizeLogString() { - System.out.println("\n\n---\n" + logMessage + "\n-------"); - return logMessage.split("\\|"); - } - - } -} diff --git a/eelf-logging/src/test/java/org/openecomp/cl/eelf/LoggerFactoryTest.java b/eelf-logging/src/test/java/org/openecomp/cl/eelf/LoggerFactoryTest.java deleted file mode 100644 index 0b61f4e..0000000 --- a/eelf-logging/src/test/java/org/openecomp/cl/eelf/LoggerFactoryTest.java +++ /dev/null @@ -1,135 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Common Logging Library - * ================================================================================ - * 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.cl.eelf; - -import static org.junit.Assert.*; - -import org.junit.Test; -import org.openecomp.cl.api.Logger; -import org.openecomp.cl.eelf.LoggerFactory; - -/** This suite of tests is intended to exercise the basic functionality of the - * {@link LoggerFactory}. */ -public class LoggerFactoryTest { - - /** This test validates that the {@link LoggerFactory} is a singleton. */ - @Test - public void loggerFactorySingletonTest() { - - // Call getInstance() on the LoggerFactory twice. - LoggerFactory loggerFactory1 = LoggerFactory.getInstance(); - LoggerFactory loggerFactory2 = LoggerFactory.getInstance(); - - // Validate that what we got was two references to the same instance - // of the LoggerFactory (ie: yes, it really is a singleton). - assertTrue("Expected references to the SAME LoggerFactory instance", - loggerFactory1 == loggerFactory2); - } - - /** This test validates that we can request {@link Logger} instances from the - * {@link LoggerFactory} by specifying either a name to use as the logger's - * identifier, or a class. */ - @Test - public void getLoggerTest() { - - // Get an instance of the LoggerFactory. - LoggerFactory loggerFactory = LoggerFactory.getInstance(); - - // Request a Logger instance by specifying the name we want for - // the logger. - Logger myLoggerByName = loggerFactory.getLogger("UnitTestLogger"); - - // Validate that we got a logger back. - assertNotNull(myLoggerByName); - - // Now, request a Logger instance by specifying a class as our logger - // identifier. - Logger myLoggerByClass = loggerFactory.getLogger(LoggerFactoryTest.class); - - // Validate that we got a logger back. - assertNotNull(myLoggerByClass); - } - - /** This test validates that the {@link LoggerFactory} will only produce a - * single unique {@link Logger} instance for each requested log name. - *

- * In other words, two requests for a {@link Logger} with the same name will - * produce two references to the same instance, not two unique {@link Logger} - * instances. */ - @Test - public void getLoggerSingleInstanceForNameTest() { - - // Get an instance of the LoggerFactory. - LoggerFactory loggerFactory = LoggerFactory.getInstance(); - - // Request a Logger instance by specifying the name we want for - // the logger. - Logger myFirstLogger = loggerFactory.getLogger("UnitTestLogger"); - - // Request another Logger instance, but specify the same name for - // the logger's identifier. - Logger mySecondLogger = loggerFactory.getLogger("UnitTestLogger"); - - // Validate, that because there was already a Logger instance with the - // specified name, we just get back a reference to that instance. - assertTrue("Expected references to the same logger instance", myFirstLogger == mySecondLogger); - - // Now, make a third logger request, but specify a different name. - Logger myThirdLogger = loggerFactory.getLogger("AnotherUnitTestLogger"); - - // Validate that, in this case, we really do get a new instance. - assertFalse("Expected a unique logger instance", myFirstLogger == myThirdLogger); - assertFalse("Expected a unique logger instance", mySecondLogger == myThirdLogger); - } - - /** This test validates that the {@link LoggerFactory} will only produce a - * single unique {@link Logger} instance for each requested class. - *

- * In other words, two requests for a {@link Logger} with the same class will - * produce two references to the same instance, not two unique {@link Logger} - * instances. */ - @Test - public void getLoggerSingleInstanceForClassTest() { - - // Get an instance of the LoggerFactory. - LoggerFactory loggerFactory = LoggerFactory.getInstance(); - - // Request a Logger instance by specifying the class to use as the - // logger's identifier. - Logger myFirstLogger = loggerFactory.getLogger(LoggerFactoryTest.class); - - // Request another Logger instance, but specify the same class for - // the logger's identifier. - Logger mySecondLogger = loggerFactory.getLogger(LoggerFactoryTest.class); - - // Validate, that because there was already a Logger instance with the - // specified class, we just get back a reference to that instance. - assertTrue("Expected references to the same logger instance", myFirstLogger == mySecondLogger); - - // Now, make a third logger request, but specify a different class. - Logger myThirdLogger = loggerFactory.getLogger(LoggerFactory.class); - - // Validate that, in this case, we really do get a new instance. - assertFalse("Expected a unique logger instance", myFirstLogger == myThirdLogger); - assertFalse("Expected a unique logger instance", mySecondLogger == myThirdLogger); - } -} diff --git a/eelf-logging/src/test/java/org/openecomp/cl/eelf/UnitTestMsgs.java b/eelf-logging/src/test/java/org/openecomp/cl/eelf/UnitTestMsgs.java deleted file mode 100644 index 58202ba..0000000 --- a/eelf-logging/src/test/java/org/openecomp/cl/eelf/UnitTestMsgs.java +++ /dev/null @@ -1,45 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Common Logging Library - * ================================================================================ - * 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.cl.eelf; - -import org.openecomp.cl.eelf.LogMessageEnum; - -import com.att.eelf.i18n.EELFResourceManager; - -public enum UnitTestMsgs implements LogMessageEnum { - - SIMPLE_INFO_LOG, - INFO_LOG_WITH_ARGS, - SIMPLE_ERROR_LOG, - ERROR_LOG_WITH_ARGS, - SIMPLE_WARN_LOG, - WARN_LOG_WITH_ARGS, - SIMPLE_TRACE_LOG, - TRACE_LOG_WITH_ARGS, - DEBUG_LOG_WITH_ARGS; - - /** Static initializer to ensure the resource bundles for this class are - * loaded... */ - static { - EELFResourceManager.loadMessageBundle("logging/UnitTestMsgs"); - } -} diff --git a/logging-api/pom.xml b/logging-api/pom.xml index 1dbb2fc..8bc97e5 100644 --- a/logging-api/pom.xml +++ b/logging-api/pom.xml @@ -23,7 +23,7 @@ 4.0.0 - org.openecomp.aai.logging-service + org.onap.aai.logging-service logging-service 1.1.0-SNAPSHOT diff --git a/logging-api/src/main/java/org/onap/aai/cl/api/LogFields.java b/logging-api/src/main/java/org/onap/aai/cl/api/LogFields.java new file mode 100644 index 0000000..80a4507 --- /dev/null +++ b/logging-api/src/main/java/org/onap/aai/cl/api/LogFields.java @@ -0,0 +1,86 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * Copyright © 2017 Amdocs + * ================================================================================ + * 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.cl.api; + +import java.util.HashMap; +import java.util.Map; + +public class LogFields { + + /** Map of field names to values. */ + private Map fields = new HashMap(); + + /** + * Retrieve the contents of the specified field entry. + * + * @param field + * - The field to retrieve the value for. + * + * @return - The value associated with the specified field, or null if there + * is no such entry. + */ + public String getField(Enum field) { + return fields.get(field.ordinal()); + } + + /** + * Assigns a value to a specific field. + * + * @param field + * - The field to assign a value to. + * @param value + * - The value to assign to the field. + * + * @return - The {@link LogFields} object (this is useful for parameter + * chaining. + */ + public LogFields setField(Enum field, String value) { + fields.put(field.ordinal(), value); + return this; + } + + /** + * Assigns a value to a specific field. + * + * @param field - The field to assign a value to. + * @param value - The value to assign to the field. + * + * @return - The {@link LogFields} object (this is useful for parameter + * chaining. + */ + public LogFields setField(Enum field, int value) { + fields.put(field.ordinal(), String.valueOf(value)); + return this; + } + + /** + * Determines whether or not a value has been assigned to a particular field. + * + * @param field - The field to be checked. + * + * @return - true if an entry exists for the specified field, false otherwise. + */ + public boolean fieldIsSet(Enum field) { + return fields.containsKey(field.ordinal()) && (fields.get(field.ordinal()) != null); + } +} diff --git a/logging-api/src/main/java/org/onap/aai/cl/api/LogLine.java b/logging-api/src/main/java/org/onap/aai/cl/api/LogLine.java new file mode 100644 index 0000000..eb6dcc8 --- /dev/null +++ b/logging-api/src/main/java/org/onap/aai/cl/api/LogLine.java @@ -0,0 +1,116 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * Copyright © 2017 Amdocs + * ================================================================================ + * 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.cl.api; + +import org.onap.aai.cl.mdc.MdcContext; +import org.onap.aai.cl.mdc.MdcOverride; +import org.slf4j.MDC; + +/** + * This class is used to help standardize how log lines are written and provide + * profiling info. + */ +public abstract class LogLine { + + public static enum LogLineType { + AUDIT, ERROR, METRICS + } + + /** + * Enumerates the predefined fields of the log line. Note that this + * enumeration only exposes those fields that the client may set via the + * {@link LogFields} object. Fields which are automatically populated by the + * logging service or sourced from the {@link MdcContext} do not appear here. + */ + public enum DefinedFields { + + STATUS_CODE, + RESPONSE_CODE, + RESPONSE_DESCRIPTION, + INSTANCE_UUID, + SEVERITY, + SERVER_IP, + CLIENT_IP, + CLASS_NAME, + PROCESS_KEY, + TARGET_SVC_NAME, + TARGET_ENTITY, + ERROR_CODE, + ERROR_DESCRIPTION, + CUSTOM_1, + CUSTOM_2, + CUSTOM_3, + CUSTOM_4; + } + + protected String component = ""; + protected String logCode = ""; + protected String level = ""; + protected String message = ""; + protected MdcOverride override = new MdcOverride(); + protected LogFields fields = new LogFields(); + + /** + * Sets common values that the log line will use for populating the log + * string. + * + * @param component + * - The entity invoking the log. + * @param logCode + * - String version of the log message code. + * @param level + * - Log level (DEBUG, TRACE, INFO, WARN, ERROR...) + * @param msg + * - The log message + * @param fields + * - A map of predefined log line fields to values. + * @param override + * - Structure which overrides selective fields in the + * {@link MdcContext} + */ + public void init(String component, String logCode, String level, String msg, LogFields fields, + MdcOverride override) { + + this.component = component; + this.logCode = logCode; + this.level = level; + this.message = msg; + this.override = override; + this.fields = fields; + } + + protected String getMdcValue(String attribute) { + if (override.hasOverride(attribute)) { + return override.getAttributeValue(attribute); + } + + String value = (String) MDC.get(attribute) == null ? "" : (String) MDC.get(attribute); + return value; + } + + public abstract String getFormattedLine(); + + protected String fieldValue(Enum field) { + return (fields.fieldIsSet(field) ? fields.getField(field) : ""); + } +} diff --git a/logging-api/src/main/java/org/onap/aai/cl/api/Logger.java b/logging-api/src/main/java/org/onap/aai/cl/api/Logger.java new file mode 100644 index 0000000..df38692 --- /dev/null +++ b/logging-api/src/main/java/org/onap/aai/cl/api/Logger.java @@ -0,0 +1,218 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * Copyright © 2017 Amdocs + * ================================================================================ + * 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.cl.api; + +import org.onap.aai.cl.mdc.MdcOverride; + +/** Defines the common API which all Logger implementations must expose. */ +public interface Logger { + + /** + * Indicate whether or not TRACE level logging is enabled. + * + * @return true if TRACE level logs are enabled, false otherwise + */ + public boolean isTraceEnabled(); + + /** + * Indicate whether or not INFO level logging is enabled. + * + * @return true if INFO level logs are enabled, false otherwise + */ + public boolean isInfoEnabled(); + + /** + * Indicate whether or not ERROR level logging is enabled. + * + * @return true if ERROR level logs are enabled, false otherwise + */ + public boolean isErrorEnabled(); + + /** + * Indicate whether or not WARNING level logging is enabled. + * + * @return true if WARNING level logs are enabled, false otherwise + */ + public boolean isWarnEnabled(); + + /** + * Indicate whether or not DEBUG level logging is enabled. + * + * @return true if DEBUG level logs are enabled, false otherwise + */ + public boolean isDebugEnabled(); + + /** + * Log an INFO message based on a message key defined in a resource bundle + * with arguments. + * + * @param logCode + * - Log message identifier. + * @param arguments + * - Arguments to populate the log message template with. + */ + public void info(Enum logCode, String... arguments); + + /** + * Log an INFO message based on a message key defined in a resource bundle + * with arguments. + * + * @param logCode + * - Log message identifier. + * @param fields + * - Map containing values for any log fields which the client wants + * to populate. + * @param arguments + * - Arguments to populate the log message template with. + */ + public void info(Enum logCode, LogFields fields, String... arguments); + + /** + * Log an INFO message based on a message key defined in a resource bundle + * with arguments. + * + * @param logCode - Log message identifier. + * @param fields - Map containing values for any log fields which the + * client wants to populate. + * @param override - A set of values to override values stored in the MDC context + * @param arguments - Arguments to populate the log message template with. + */ + public void info(Enum logCode, LogFields fields, MdcOverride override, String... arguments); + + /** + * Log a WARNING message based on a message key defined in a resource bundle + * with arguments. + * + * @param logCode - Log message identifier. + * @param arguments - Arguments to populate the log message template with. + */ + public void warn(Enum logCode, String... arguments); + + /** + * Log a WARNING message based on a message key defined in a resource bundle + * with arguments. + * + * @param logCode - Log message identifier. + * @param fields - Map containing values for any log fields which the + * client wants to populate. + * @param arguments - Arguments to populate the log message template with. + */ + public void warn(Enum logCode, LogFields fields, String... arguments); + + /** + * Log a TRACE message based on a message key defined in a resource bundle + * with arguments. + * + * @param logCode - Log message identifier. + * @param arguments - Arguments to populate the log message template with. + */ + public void trace(Enum logCode, String... arguments); + + /** + * Log a TRACE message based on a message key defined in a resource bundle + * with arguments. + * + * @param logCode - Log message identifier. + * @param fields - Map containing values for any log fields which the + * client wants to populate. + * @param arguments - Arguments to populate the log message template with. + */ + public void trace(Enum logCode, LogFields fields, String... arguments); + + /** + * Log a simple, non-templated DEBUG message. + * + * @param logMessage - The message to be logged. + */ + public void debug(String logMessage); + + /** + * Log a DEBUG message based on a message key defined in a resource bundle + * with arguments. + * + * @param logCode - Log message identifier. + * @param arguments - Arguments to populate the log message template with. + */ + public void debug(Enum logCode, String... arguments); + + /** + * Log a DEBUG message based on a message key defined in a resource bundle + * with arguments. + * + * @param logCode - Log message identifier. + * @param fields - Map containing values for any log fields which the + * client wants to populate. + * @param arguments - Arguments to populate the log message template with. + */ + public void debug(Enum logCode, LogFields fields, String... arguments); + + /** + * Log an ERROR message based on a message key defined in a resource bundle + * with arguments. + * + * @param logCode - Log message identifier. + * @param arguments - Arguments to populate the log message template with. + */ + public void error(Enum logCode, String... arguments); + + /** + * Log an ERROR message based on a message key defined in a resource bundle + * with arguments. + * + * @param logCode - Log message identifier. + * @param fields - Map containing values for any log fields which the + * client wants to populate. + * @param arguments - Arguments to populate the log message template with. + */ + public void error(Enum logCode, LogFields fields, String... arguments); + + /** + * Log an ERROR message based on a message key defined in a resource bundle + * with arguments and a throwable exception. + * + * @param logCode - Log message identifier. + * @param ex - The exception to be logged. + * @param arguments - Arguments to populate the log message template with. + */ + public void error(Enum logCode, Throwable ex, String... arguments); + + /** + * Log an ERROR message based on a message key defined in a resource bundle + * with arguments and a throwable exception. + * + * @param logCode - Log message identifier. + * @param fields - Map containing values for any log fields which the + * client wants to populate. + * @param ex - The exception to be logged. + * @param arguments - Arguments to populate the log message template with. + */ + public void error(Enum logCode, LogFields fields, Throwable ex, String... arguments); + + /** + * Format the given log using the supplied arguments + * @param logCode - Log message identifier. + * @param arguments - Arguments to populate the log message template with. + */ + public String formatMsg(Enum logCode, String... arguments); + +} diff --git a/logging-api/src/main/java/org/onap/aai/cl/api/LoggerFactoryInterface.java b/logging-api/src/main/java/org/onap/aai/cl/api/LoggerFactoryInterface.java new file mode 100644 index 0000000..4fcf642 --- /dev/null +++ b/logging-api/src/main/java/org/onap/aai/cl/api/LoggerFactoryInterface.java @@ -0,0 +1,45 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * Copyright © 2017 Amdocs + * ================================================================================ + * 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.cl.api; + +/** + * Defines the common API that must be exposed by all LoggerFactory + * implementations. + */ +public interface LoggerFactoryInterface { + + /** + * Returns the logger associated with the name. + * + * @return Logger + */ + public Logger getLogger(String name); + + /** + * Returns the logger associated with the clazz. + * + * @return Logger + */ + public Logger getLogger(Class clazz); + +} diff --git a/logging-api/src/main/java/org/onap/aai/cl/mdc/MdcContext.java b/logging-api/src/main/java/org/onap/aai/cl/mdc/MdcContext.java new file mode 100644 index 0000000..11cacd9 --- /dev/null +++ b/logging-api/src/main/java/org/onap/aai/cl/mdc/MdcContext.java @@ -0,0 +1,80 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * Copyright © 2017 Amdocs + * ================================================================================ + * 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.cl.mdc; + +import org.slf4j.MDC; + +import java.net.InetAddress; +import java.text.SimpleDateFormat; +import java.util.Date; + +/** + * This class manages the MDC (mapped diagnostic context). Calling the init + * method when a new event is processed will save thread-specific context + * information which will be used when generating logs. + */ +public final class MdcContext { + public static String MDC_REQUEST_ID = "RequestId"; + public static String MDC_SERVER_FQDN = "ServerFQDN"; + public static String MDC_SERVICE_NAME = "ServiceName"; + public static String MDC_PARTNER_NAME = "PartnerName"; + public static String MDC_START_TIME = "StartTime"; + public static String MDC_REMOTE_HOST = "RemoteHost"; + public static String MDC_SERVICE_INSTANCE_ID = "ServiceInstanceId"; + public static String MDC_CLIENT_ADDRESS = "ClientAddress"; + + /** + * Initializes the fields of the Mapped Diagnostic Context. + * + * @param transId - Unique transaction identifier. + * @param serviceName - The name of the service generating the diagnostic. + * @param serviceInstance - Unique identifier of the specific instance + * generating the diagnostic. + * @param partnerName - Name of the entity initiating the transction to + * be logged + * @param clientAddress - IP address of the transaction client. + */ + public static void initialize(String transId, + String serviceName, + String serviceInstance, + String partnerName, + String clientAddress) { + MDC.clear(); + MDC.put(MDC_REQUEST_ID, transId); + MDC.put(MDC_SERVICE_NAME, serviceName); + MDC.put(MDC_SERVICE_INSTANCE_ID, serviceInstance); + MDC.put(MDC_PARTNER_NAME, partnerName); + MDC.put(MDC_CLIENT_ADDRESS, clientAddress); + MDC.put(MDC_START_TIME, + new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX").format(new Date())); + + try { + MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getCanonicalHostName()); + } catch (Exception e) { + // If, for some reason we are unable to get the canonical host name, we + // just want to leave the field unpopulated. There is not much value + // in doing anything else with an exception at this point. + } + + } +} diff --git a/logging-api/src/main/java/org/onap/aai/cl/mdc/MdcOverride.java b/logging-api/src/main/java/org/onap/aai/cl/mdc/MdcOverride.java new file mode 100644 index 0000000..1456217 --- /dev/null +++ b/logging-api/src/main/java/org/onap/aai/cl/mdc/MdcOverride.java @@ -0,0 +1,46 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * Copyright © 2017 Amdocs + * ================================================================================ + * 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.cl.mdc; + +import java.util.HashMap; +import java.util.Map; + +/** + * This class stores a map of MDC context attribute/values which can be used to + * override the actual MDC context. + */ +public class MdcOverride { + private Map overrides = new HashMap(); + + public void addAttribute(String attr, String val) { + overrides.put(attr, val); + } + + public String getAttributeValue(String attr) { + return overrides.get(attr); + } + + public boolean hasOverride(String attr) { + return overrides.containsKey(attr); + } +} diff --git a/logging-api/src/main/java/org/openecomp/cl/api/LogFields.java b/logging-api/src/main/java/org/openecomp/cl/api/LogFields.java deleted file mode 100644 index 677aa2c..0000000 --- a/logging-api/src/main/java/org/openecomp/cl/api/LogFields.java +++ /dev/null @@ -1,86 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * Copyright © 2017 Amdocs - * ================================================================================ - * 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========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - */ -package org.openecomp.cl.api; - -import java.util.HashMap; -import java.util.Map; - -public class LogFields { - - /** Map of field names to values. */ - private Map fields = new HashMap(); - - /** - * Retrieve the contents of the specified field entry. - * - * @param field - * - The field to retrieve the value for. - * - * @return - The value associated with the specified field, or null if there - * is no such entry. - */ - public String getField(Enum field) { - return fields.get(field.ordinal()); - } - - /** - * Assigns a value to a specific field. - * - * @param field - * - The field to assign a value to. - * @param value - * - The value to assign to the field. - * - * @return - The {@link LogFields} object (this is useful for parameter - * chaining. - */ - public LogFields setField(Enum field, String value) { - fields.put(field.ordinal(), value); - return this; - } - - /** - * Assigns a value to a specific field. - * - * @param field - The field to assign a value to. - * @param value - The value to assign to the field. - * - * @return - The {@link LogFields} object (this is useful for parameter - * chaining. - */ - public LogFields setField(Enum field, int value) { - fields.put(field.ordinal(), String.valueOf(value)); - return this; - } - - /** - * Determines whether or not a value has been assigned to a particular field. - * - * @param field - The field to be checked. - * - * @return - true if an entry exists for the specified field, false otherwise. - */ - public boolean fieldIsSet(Enum field) { - return fields.containsKey(field.ordinal()) && (fields.get(field.ordinal()) != null); - } -} diff --git a/logging-api/src/main/java/org/openecomp/cl/api/LogLine.java b/logging-api/src/main/java/org/openecomp/cl/api/LogLine.java deleted file mode 100644 index f63d421..0000000 --- a/logging-api/src/main/java/org/openecomp/cl/api/LogLine.java +++ /dev/null @@ -1,117 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * Copyright © 2017 Amdocs - * ================================================================================ - * 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========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - */ -package org.openecomp.cl.api; - -import org.openecomp.cl.mdc.MdcContext; -import org.openecomp.cl.mdc.MdcOverride; - -import org.slf4j.MDC; - -/** - * This class is used to help standardize how log lines are written and provide - * profiling info. - */ -public abstract class LogLine { - - public static enum LogLineType { - AUDIT, ERROR, METRICS - } - - /** - * Enumerates the predefined fields of the log line. Note that this - * enumeration only exposes those fields that the client may set via the - * {@link LogFields} object. Fields which are automatically populated by the - * logging service or sourced from the {@link MdcContext} do not appear here. - */ - public enum DefinedFields { - - STATUS_CODE, - RESPONSE_CODE, - RESPONSE_DESCRIPTION, - INSTANCE_UUID, - SEVERITY, - SERVER_IP, - CLIENT_IP, - CLASS_NAME, - PROCESS_KEY, - TARGET_SVC_NAME, - TARGET_ENTITY, - ERROR_CODE, - ERROR_DESCRIPTION, - CUSTOM_1, - CUSTOM_2, - CUSTOM_3, - CUSTOM_4; - } - - protected String component = ""; - protected String logCode = ""; - protected String level = ""; - protected String message = ""; - protected MdcOverride override = new MdcOverride(); - protected LogFields fields = new LogFields(); - - /** - * Sets common values that the log line will use for populating the log - * string. - * - * @param component - * - The entity invoking the log. - * @param logCode - * - String version of the log message code. - * @param level - * - Log level (DEBUG, TRACE, INFO, WARN, ERROR...) - * @param msg - * - The log message - * @param fields - * - A map of predefined log line fields to values. - * @param override - * - Structure which overrides selective fields in the - * {@link MdcContext} - */ - public void init(String component, String logCode, String level, String msg, LogFields fields, - MdcOverride override) { - - this.component = component; - this.logCode = logCode; - this.level = level; - this.message = msg; - this.override = override; - this.fields = fields; - } - - protected String getMdcValue(String attribute) { - if (override.hasOverride(attribute)) { - return override.getAttributeValue(attribute); - } - - String value = (String) MDC.get(attribute) == null ? "" : (String) MDC.get(attribute); - return value; - } - - public abstract String getFormattedLine(); - - protected String fieldValue(Enum field) { - return (fields.fieldIsSet(field) ? fields.getField(field) : ""); - } -} diff --git a/logging-api/src/main/java/org/openecomp/cl/api/Logger.java b/logging-api/src/main/java/org/openecomp/cl/api/Logger.java deleted file mode 100644 index 50efe49..0000000 --- a/logging-api/src/main/java/org/openecomp/cl/api/Logger.java +++ /dev/null @@ -1,218 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * Copyright © 2017 Amdocs - * ================================================================================ - * 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========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - */ -package org.openecomp.cl.api; - -import org.openecomp.cl.mdc.MdcOverride; - -/** Defines the common API which all Logger implementations must expose. */ -public interface Logger { - - /** - * Indicate whether or not TRACE level logging is enabled. - * - * @return true if TRACE level logs are enabled, false otherwise - */ - public boolean isTraceEnabled(); - - /** - * Indicate whether or not INFO level logging is enabled. - * - * @return true if INFO level logs are enabled, false otherwise - */ - public boolean isInfoEnabled(); - - /** - * Indicate whether or not ERROR level logging is enabled. - * - * @return true if ERROR level logs are enabled, false otherwise - */ - public boolean isErrorEnabled(); - - /** - * Indicate whether or not WARNING level logging is enabled. - * - * @return true if WARNING level logs are enabled, false otherwise - */ - public boolean isWarnEnabled(); - - /** - * Indicate whether or not DEBUG level logging is enabled. - * - * @return true if DEBUG level logs are enabled, false otherwise - */ - public boolean isDebugEnabled(); - - /** - * Log an INFO message based on a message key defined in a resource bundle - * with arguments. - * - * @param logCode - * - Log message identifier. - * @param arguments - * - Arguments to populate the log message template with. - */ - public void info(Enum logCode, String... arguments); - - /** - * Log an INFO message based on a message key defined in a resource bundle - * with arguments. - * - * @param logCode - * - Log message identifier. - * @param fields - * - Map containing values for any log fields which the client wants - * to populate. - * @param arguments - * - Arguments to populate the log message template with. - */ - public void info(Enum logCode, LogFields fields, String... arguments); - - /** - * Log an INFO message based on a message key defined in a resource bundle - * with arguments. - * - * @param logCode - Log message identifier. - * @param fields - Map containing values for any log fields which the - * client wants to populate. - * @param override - A set of values to override values stored in the MDC context - * @param arguments - Arguments to populate the log message template with. - */ - public void info(Enum logCode, LogFields fields, MdcOverride override, String... arguments); - - /** - * Log a WARNING message based on a message key defined in a resource bundle - * with arguments. - * - * @param logCode - Log message identifier. - * @param arguments - Arguments to populate the log message template with. - */ - public void warn(Enum logCode, String... arguments); - - /** - * Log a WARNING message based on a message key defined in a resource bundle - * with arguments. - * - * @param logCode - Log message identifier. - * @param fields - Map containing values for any log fields which the - * client wants to populate. - * @param arguments - Arguments to populate the log message template with. - */ - public void warn(Enum logCode, LogFields fields, String... arguments); - - /** - * Log a TRACE message based on a message key defined in a resource bundle - * with arguments. - * - * @param logCode - Log message identifier. - * @param arguments - Arguments to populate the log message template with. - */ - public void trace(Enum logCode, String... arguments); - - /** - * Log a TRACE message based on a message key defined in a resource bundle - * with arguments. - * - * @param logCode - Log message identifier. - * @param fields - Map containing values for any log fields which the - * client wants to populate. - * @param arguments - Arguments to populate the log message template with. - */ - public void trace(Enum logCode, LogFields fields, String... arguments); - - /** - * Log a simple, non-templated DEBUG message. - * - * @param logMessage - The message to be logged. - */ - public void debug(String logMessage); - - /** - * Log a DEBUG message based on a message key defined in a resource bundle - * with arguments. - * - * @param logCode - Log message identifier. - * @param arguments - Arguments to populate the log message template with. - */ - public void debug(Enum logCode, String... arguments); - - /** - * Log a DEBUG message based on a message key defined in a resource bundle - * with arguments. - * - * @param logCode - Log message identifier. - * @param fields - Map containing values for any log fields which the - * client wants to populate. - * @param arguments - Arguments to populate the log message template with. - */ - public void debug(Enum logCode, LogFields fields, String... arguments); - - /** - * Log an ERROR message based on a message key defined in a resource bundle - * with arguments. - * - * @param logCode - Log message identifier. - * @param arguments - Arguments to populate the log message template with. - */ - public void error(Enum logCode, String... arguments); - - /** - * Log an ERROR message based on a message key defined in a resource bundle - * with arguments. - * - * @param logCode - Log message identifier. - * @param fields - Map containing values for any log fields which the - * client wants to populate. - * @param arguments - Arguments to populate the log message template with. - */ - public void error(Enum logCode, LogFields fields, String... arguments); - - /** - * Log an ERROR message based on a message key defined in a resource bundle - * with arguments and a throwable exception. - * - * @param logCode - Log message identifier. - * @param ex - The exception to be logged. - * @param arguments - Arguments to populate the log message template with. - */ - public void error(Enum logCode, Throwable ex, String... arguments); - - /** - * Log an ERROR message based on a message key defined in a resource bundle - * with arguments and a throwable exception. - * - * @param logCode - Log message identifier. - * @param fields - Map containing values for any log fields which the - * client wants to populate. - * @param ex - The exception to be logged. - * @param arguments - Arguments to populate the log message template with. - */ - public void error(Enum logCode, LogFields fields, Throwable ex, String... arguments); - - /** - * Format the given log using the supplied arguments - * @param logCode - Log message identifier. - * @param arguments - Arguments to populate the log message template with. - */ - public String formatMsg(Enum logCode, String... arguments); - -} diff --git a/logging-api/src/main/java/org/openecomp/cl/api/LoggerFactoryInterface.java b/logging-api/src/main/java/org/openecomp/cl/api/LoggerFactoryInterface.java deleted file mode 100644 index 502aa19..0000000 --- a/logging-api/src/main/java/org/openecomp/cl/api/LoggerFactoryInterface.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * Copyright © 2017 Amdocs - * ================================================================================ - * 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========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - */ -package org.openecomp.cl.api; - -/** - * Defines the common API that must be exposed by all LoggerFactory - * implementations. - */ -public interface LoggerFactoryInterface { - - /** - * Returns the logger associated with the name. - * - * @return Logger - */ - public Logger getLogger(String name); - - /** - * Returns the logger associated with the clazz. - * - * @return Logger - */ - public Logger getLogger(Class clazz); - -} diff --git a/logging-api/src/main/java/org/openecomp/cl/mdc/MdcContext.java b/logging-api/src/main/java/org/openecomp/cl/mdc/MdcContext.java deleted file mode 100644 index 285ca9b..0000000 --- a/logging-api/src/main/java/org/openecomp/cl/mdc/MdcContext.java +++ /dev/null @@ -1,80 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * Copyright © 2017 Amdocs - * ================================================================================ - * 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========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - */ -package org.openecomp.cl.mdc; - -import org.slf4j.MDC; - -import java.net.InetAddress; -import java.text.SimpleDateFormat; -import java.util.Date; - -/** - * This class manages the MDC (mapped diagnostic context). Calling the init - * method when a new event is processed will save thread-specific context - * information which will be used when generating logs. - */ -public final class MdcContext { - public static String MDC_REQUEST_ID = "RequestId"; - public static String MDC_SERVER_FQDN = "ServerFQDN"; - public static String MDC_SERVICE_NAME = "ServiceName"; - public static String MDC_PARTNER_NAME = "PartnerName"; - public static String MDC_START_TIME = "StartTime"; - public static String MDC_REMOTE_HOST = "RemoteHost"; - public static String MDC_SERVICE_INSTANCE_ID = "ServiceInstanceId"; - public static String MDC_CLIENT_ADDRESS = "ClientAddress"; - - /** - * Initializes the fields of the Mapped Diagnostic Context. - * - * @param transId - Unique transaction identifier. - * @param serviceName - The name of the service generating the diagnostic. - * @param serviceInstance - Unique identifier of the specific instance - * generating the diagnostic. - * @param partnerName - Name of the entity initiating the transction to - * be logged - * @param clientAddress - IP address of the transaction client. - */ - public static void initialize(String transId, - String serviceName, - String serviceInstance, - String partnerName, - String clientAddress) { - MDC.clear(); - MDC.put(MDC_REQUEST_ID, transId); - MDC.put(MDC_SERVICE_NAME, serviceName); - MDC.put(MDC_SERVICE_INSTANCE_ID, serviceInstance); - MDC.put(MDC_PARTNER_NAME, partnerName); - MDC.put(MDC_CLIENT_ADDRESS, clientAddress); - MDC.put(MDC_START_TIME, - new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX").format(new Date())); - - try { - MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getCanonicalHostName()); - } catch (Exception e) { - // If, for some reason we are unable to get the canonical host name, we - // just want to leave the field unpopulated. There is not much value - // in doing anything else with an exception at this point. - } - - } -} diff --git a/logging-api/src/main/java/org/openecomp/cl/mdc/MdcOverride.java b/logging-api/src/main/java/org/openecomp/cl/mdc/MdcOverride.java deleted file mode 100644 index cc5e131..0000000 --- a/logging-api/src/main/java/org/openecomp/cl/mdc/MdcOverride.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * Copyright © 2017 Amdocs - * ================================================================================ - * 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========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - */ -package org.openecomp.cl.mdc; - -import java.util.HashMap; -import java.util.Map; - -/** - * This class stores a map of MDC context attribute/values which can be used to - * override the actual MDC context. - */ -public class MdcOverride { - private Map overrides = new HashMap(); - - public void addAttribute(String attr, String val) { - overrides.put(attr, val); - } - - public String getAttributeValue(String attr) { - return overrides.get(attr); - } - - public boolean hasOverride(String attr) { - return overrides.containsKey(attr); - } -} diff --git a/pom.xml b/pom.xml index 9d74a10..f2be59e 100644 --- a/pom.xml +++ b/pom.xml @@ -7,7 +7,7 @@ 1.0.0-SNAPSHOT - org.openecomp.aai.logging-service + org.onap.aai.logging-service logging-service pom 1.1.0-SNAPSHOT -- cgit 1.2.3-korg