From b40a52e5b2c8aaae975bed054408c39f4e3fd0db Mon Sep 17 00:00:00 2001 From: Steve Smokowski Date: Thu, 9 Feb 2017 15:59:56 -0500 Subject: Initial OpenEcomp A&AI Logging Service commit Change-Id: Ie67c5746c2aeafc0fa4318b5ba7ef8af1b3a2eda Signed-off-by: Steve Smokowski --- eelf-logging/pom.xml | 57 ++ .../org/openecomp/cl/eelf/AaiLoggerAdapter.java | 349 +++++++++ .../java/org/openecomp/cl/eelf/AuditLogLine.java | 81 ++ .../java/org/openecomp/cl/eelf/ErrorLogLine.java | 42 ++ .../java/org/openecomp/cl/eelf/LogMessageEnum.java | 31 + .../java/org/openecomp/cl/eelf/LoggerFactory.java | 177 +++++ .../java/org/openecomp/cl/eelf/MetricsLogLine.java | 83 +++ .../openecomp/cl/eelf/AAILoggerAdapterTest.java | 823 +++++++++++++++++++++ .../org/openecomp/cl/eelf/LoggerFactoryTest.java | 134 ++++ .../java/org/openecomp/cl/eelf/UnitTestMsgs.java | 44 ++ .../test/resources/logging/UnitTestMsgs.properties | 77 ++ 11 files changed, 1898 insertions(+) create mode 100644 eelf-logging/pom.xml create mode 100644 eelf-logging/src/main/java/org/openecomp/cl/eelf/AaiLoggerAdapter.java create mode 100644 eelf-logging/src/main/java/org/openecomp/cl/eelf/AuditLogLine.java create mode 100644 eelf-logging/src/main/java/org/openecomp/cl/eelf/ErrorLogLine.java create mode 100644 eelf-logging/src/main/java/org/openecomp/cl/eelf/LogMessageEnum.java create mode 100644 eelf-logging/src/main/java/org/openecomp/cl/eelf/LoggerFactory.java create mode 100644 eelf-logging/src/main/java/org/openecomp/cl/eelf/MetricsLogLine.java create mode 100644 eelf-logging/src/test/java/org/openecomp/cl/eelf/AAILoggerAdapterTest.java create mode 100644 eelf-logging/src/test/java/org/openecomp/cl/eelf/LoggerFactoryTest.java create mode 100644 eelf-logging/src/test/java/org/openecomp/cl/eelf/UnitTestMsgs.java create mode 100644 eelf-logging/src/test/resources/logging/UnitTestMsgs.properties (limited to 'eelf-logging') diff --git a/eelf-logging/pom.xml b/eelf-logging/pom.xml new file mode 100644 index 0000000..c9952d0 --- /dev/null +++ b/eelf-logging/pom.xml @@ -0,0 +1,57 @@ + + + + 4.0.0 + + + org.openecomp.aai.logging-service + logging-service + 1.0.0-SNAPSHOT + + + org.openecomp.aai + eelf-logging + EELF Logging Implementation + + + + + + org.openecomp.aai + logging-api + ${project.version} + + + + + com.att.eelf + eelf-core + 0.0.1 + + + + junit + junit + 4.11 + test + + + 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 new file mode 100644 index 0000000..0f05532 --- /dev/null +++ b/eelf-logging/src/main/java/org/openecomp/cl/eelf/AaiLoggerAdapter.java @@ -0,0 +1,349 @@ +/*- + * ============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 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 new file mode 100644 index 0000000..457da14 --- /dev/null +++ b/eelf-logging/src/main/java/org/openecomp/cl/eelf/AuditLogLine.java @@ -0,0 +1,81 @@ +/*- + * ============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.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 new file mode 100644 index 0000000..25c2fa3 --- /dev/null +++ b/eelf-logging/src/main/java/org/openecomp/cl/eelf/ErrorLogLine.java @@ -0,0 +1,42 @@ +/*- + * ============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.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 new file mode 100644 index 0000000..dc83763 --- /dev/null +++ b/eelf-logging/src/main/java/org/openecomp/cl/eelf/LogMessageEnum.java @@ -0,0 +1,31 @@ +/*- + * ============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 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 new file mode 100644 index 0000000..c0ff5b0 --- /dev/null +++ b/eelf-logging/src/main/java/org/openecomp/cl/eelf/LoggerFactory.java @@ -0,0 +1,177 @@ +/*- + * ============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 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 new file mode 100644 index 0000000..fb5e213 --- /dev/null +++ b/eelf-logging/src/main/java/org/openecomp/cl/eelf/MetricsLogLine.java @@ -0,0 +1,83 @@ +/*- + * ============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.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/openecomp/cl/eelf/AAILoggerAdapterTest.java b/eelf-logging/src/test/java/org/openecomp/cl/eelf/AAILoggerAdapterTest.java new file mode 100644 index 0000000..24dab76 --- /dev/null +++ b/eelf-logging/src/test/java/org/openecomp/cl/eelf/AAILoggerAdapterTest.java @@ -0,0 +1,823 @@ +/*- + * ============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 new file mode 100644 index 0000000..5e475aa --- /dev/null +++ b/eelf-logging/src/test/java/org/openecomp/cl/eelf/LoggerFactoryTest.java @@ -0,0 +1,134 @@ +/*- + * ============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 new file mode 100644 index 0000000..0b4eb5e --- /dev/null +++ b/eelf-logging/src/test/java/org/openecomp/cl/eelf/UnitTestMsgs.java @@ -0,0 +1,44 @@ +/*- + * ============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/eelf-logging/src/test/resources/logging/UnitTestMsgs.properties b/eelf-logging/src/test/resources/logging/UnitTestMsgs.properties new file mode 100644 index 0000000..77f5261 --- /dev/null +++ b/eelf-logging/src/test/resources/logging/UnitTestMsgs.properties @@ -0,0 +1,77 @@ +### +# ============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========================================================= +### + +#Resource key=Error Code|Message text|Resolution text |Description text +####### +#Newlines can be utilized to add some clarity ensuring continuing line +#has atleast one leading space +#ResourceKey=\ +# ERR0000E\ +# Sample error msg txt\ +# Sample resolution msg\ +# Sample description txt +# +###### +#Error code classification category +#000 Info/Debug +#100 Permission errors +#200 Availability errors/Timeouts +#300 Data errors +#400 Schema Interface type/validation errors +#500 Business process errors +#900 Unknown errors +# +######################################################################## + +SIMPLE_INFO_LOG=\ + UT0001I|\ + This is a simple info log with no arguments. + +INFO_LOG_WITH_ARGS=\ + UT0002I|\ + This is an info log with some arguments {0} and {1} + +SIMPLE_ERROR_LOG=\ + UT0001E|\ + This is a simple error log with no arguments. + +ERROR_LOG_WITH_ARGS=\ + UT0002E|\ + This is an error log with some arguments {0} and {1} + +SIMPLE_WARN_LOG=\ + UT0001W|\ + This is a simple warning log with no arguments. + +WARN_LOG_WITH_ARGS=\ + UT0002W|\ + This is a warning log with some arguments {0} and {1} + +SIMPLE_TRACE_LOG=\ + UT0001T|\ + This is a simple trace log with no arguments. + +TRACE_LOG_WITH_ARGS=\ + UT0002T|\ + This is a trace log with some arguments {0} and {1} + +DEBUG_LOG_WITH_ARGS=\ + UT0001D|\ + This is a debug log with some arguments {0} and {1} -- cgit 1.2.3-korg