diff options
author | Carsten Lund <lund@research.att.com> | 2017-03-13 13:51:35 +0000 |
---|---|---|
committer | Carsten Lund <lund@research.att.com> | 2017-04-18 02:17:51 +0000 |
commit | 37181837935f5e94fd02b32da0df966b498dd968 (patch) | |
tree | 294c24cebed722684a5a1ce4291b55db18322e4c | |
parent | 12569365f092fe2993f8cd470c48331888a29a17 (diff) |
[DCAE-15] Changes related to version 1.1
See Jira for details
Change-Id: I225aa7a8952da4ddb0a93ac238aa79c8993f72b8
Signed-off-by: Carsten Lund <lund@research.att.com>
19 files changed, 1666 insertions, 468 deletions
diff --git a/operation-utils/.classpath b/operation-utils/.classpath index 1ab68f0..329c766 100644 --- a/operation-utils/.classpath +++ b/operation-utils/.classpath @@ -11,6 +11,8 @@ <attribute name="maven.pomderived" value="true"/> </attributes> </classpathentry> + <classpathentry kind="src" path="src/main/java-gen"/> + <classpathentry kind="src" path="src/main/resources-gen"/> <classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER"> <attributes> <attribute name="maven.pomderived" value="true"/> diff --git a/operation-utils/META-INF/MANIFEST.MF b/operation-utils/META-INF/MANIFEST.MF index 65b7caa..8dfed08 100644 --- a/operation-utils/META-INF/MANIFEST.MF +++ b/operation-utils/META-INF/MANIFEST.MF @@ -6,3 +6,4 @@ Bundle-Version: 0.1.0.qualifier Export-Package: org.openecomp.entity, org.openecomp.logger, org.openecomp.utils +Require-Bundle: javax.servlet diff --git a/operation-utils/operation-utils.iml b/operation-utils/operation-utils.iml new file mode 100644 index 0000000..e3b64a3 --- /dev/null +++ b/operation-utils/operation-utils.iml @@ -0,0 +1,30 @@ +<?xml version="1.0" encoding="UTF-8"?> +<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4"> + <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_7" inherit-compiler-output="false"> + <output url="file://$MODULE_DIR$/target/classes" /> + <output-test url="file://$MODULE_DIR$/target/test-classes" /> + <content url="file://$MODULE_DIR$"> + <sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" /> + <sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" /> + <excludeFolder url="file://$MODULE_DIR$/target" /> + </content> + <orderEntry type="inheritedJdk" /> + <orderEntry type="sourceFolder" forTests="false" /> + <orderEntry type="library" name="Maven: javax.servlet:javax.servlet-api:3.1.0" level="project" /> + <orderEntry type="library" name="Maven: com.att.eelf:eelf-core:1.0.0" level="project" /> + <orderEntry type="library" name="Maven: ch.qos.logback:logback-core:1.1.3" level="project" /> + <orderEntry type="library" name="Maven: ch.qos.logback:logback-classic:1.1.3" level="project" /> + <orderEntry type="library" name="Maven: org.slf4j:slf4j-api:1.7.6" level="project" /> + <orderEntry type="library" name="Maven: org.yaml:snakeyaml:1.15" level="project" /> + <orderEntry type="library" name="Maven: com.att.research.ncomp.utils:ncomp-utils-java:0.1.0-SNAPSHOT" level="project" /> + <orderEntry type="library" name="Maven: log4j:log4j:1.2.17" level="project" /> + <orderEntry type="library" name="Maven: junit:junit:4.11" level="project" /> + <orderEntry type="library" name="Maven: org.hamcrest:hamcrest-core:1.3" level="project" /> + <orderEntry type="library" name="Maven: org.apache.commons:commons-compress:1.9" level="project" /> + <orderEntry type="library" name="Maven: commons-cli:commons-cli:1.3" level="project" /> + <orderEntry type="library" name="Maven: org.eclipse.emf:org.eclipse.emf.ecore:2.11.0-v20150123-0347" level="project" /> + <orderEntry type="library" name="Maven: org.eclipse.emf:org.eclipse.emf.common:2.11.0-v20150123-0347" level="project" /> + <orderEntry type="library" name="Maven: org.eclipse.emf:org.eclipse.emf.ecore.xmi:2.11.0-v20150123-0347" level="project" /> + <orderEntry type="library" name="Maven: org.codehaus.groovy:groovy-all:2.4.3" level="project" /> + </component> +</module>
\ No newline at end of file diff --git a/operation-utils/pom.xml b/operation-utils/pom.xml index 8500896..ebc5aa2 100644 --- a/operation-utils/pom.xml +++ b/operation-utils/pom.xml @@ -3,7 +3,6 @@ <modelVersion>4.0.0</modelVersion> <groupId>org.openecomp.dcae.operation.utils</groupId> <artifactId>operation-utils</artifactId> - <version>1.1.0-SNAPSHOT</version> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> @@ -11,42 +10,21 @@ <maven.compiler.target>1.7</maven.compiler.target> <nexusproxy>https://nexus.onap.org</nexusproxy></properties> - -<build> + + <build> <plugins> - <!-- site maven plugin --> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-site-plugin</artifactId> - <version>3.6</version> - <dependencies> - <dependency> - <groupId>org.apache.maven.wagon</groupId> - <artifactId>wagon-webdav-jackrabbit</artifactId> - <version>2.10</version> - </dependency> - </dependencies> - </plugin> - - <!-- blackduck maven plugin --> + <!-- site maven plugin --> <plugin> - <groupId>com.blackducksoftware.integration</groupId> - <artifactId>hub-maven-plugin</artifactId> - <version>1.4.0</version> - <inherited>false</inherited> - <configuration> - <hubProjectName>${project.name}</hubProjectName> - <outputDirectory>${project.basedir}</outputDirectory> - </configuration> - <executions> - <execution> - <id>create-bdio-file</id> - <phase>package</phase> - <goals> - <goal>createHubOutput</goal> - </goals> - </execution> - </executions> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-site-plugin</artifactId> + <version>3.6</version> + <dependencies> + <dependency> + <groupId>org.apache.maven.wagon</groupId> + <artifactId>wagon-webdav-jackrabbit</artifactId> + <version>2.10</version> + </dependency> + </dependencies> </plugin> <plugin> @@ -61,30 +39,69 @@ </dependency> </dependencies> </plugin> + + <plugin> + <groupId>org.codehaus.mojo</groupId> + <artifactId>build-helper-maven-plugin</artifactId> + <version>1.10</version> + <executions> + <execution> + <id>add-source</id> + <phase>generate-sources</phase> + <goals> + <goal>add-source</goal> + </goals> + <configuration> + <sources> + <source>src/main/java</source> + <source>src/main/java-gen</source> + </sources> + </configuration> + </execution> + <execution> + <id>add-resource</id> + <phase>generate-resources</phase> + <goals> + <goal>add-resource</goal> + </goals> + <configuration> + <resources> + <resource> + <directory>src/main/resources</directory> + </resource> + <resource> + <directory>src/main/resources-gen</directory> + </resource> + </resources> + </configuration> + </execution> + </executions> + + </plugin> </plugins> </build> <dependencies> <dependency> + <groupId>javax.servlet</groupId> + <artifactId>javax.servlet-api</artifactId> + <version>3.1.0</version> + </dependency> + <dependency> <groupId>com.att.eelf</groupId> <artifactId>eelf-core</artifactId> - <version>0.0.1</version> + <version>1.0.0</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.6</version> </dependency> - - <dependency> <groupId>org.yaml</groupId> <artifactId>snakeyaml</artifactId> <version>1.15</version> </dependency> - - - <dependency> <groupId>org.openecomp.ncomp.utils</groupId> <artifactId>ncomp-utils-java</artifactId> @@ -97,10 +114,10 @@ </dependency> </dependencies> - <parent> - <groupId>org.openecomp.ncomp.maven</groupId> - <artifactId>ncomp-maven-base</artifactId> - <version>1.1.0-SNAPSHOT</version> - <relativePath>../../dcae-org.openecomp.ncomp.maven/ncomp-maven-base</relativePath> - </parent> + <parent> + <groupId>org.openecomp.ncomp.maven</groupId> + <artifactId>ncomp-maven-base</artifactId> + <version>1.1.0-SNAPSHOT</version> + <relativePath>../../dcae-org.openecomp.ncomp.maven/ncomp-maven-base</relativePath> + </parent> </project> diff --git a/operation-utils/src/main/java-gen/org/openecomp/logger/GenericMessagesMessageEnum.java b/operation-utils/src/main/java-gen/org/openecomp/logger/GenericMessagesMessageEnum.java new file mode 100644 index 0000000..060a196 --- /dev/null +++ b/operation-utils/src/main/java-gen/org/openecomp/logger/GenericMessagesMessageEnum.java @@ -0,0 +1,25 @@ + +package org.openecomp.logger; + +import com.att.eelf.i18n.EELFResourceManager; +import org.openecomp.logger.EcompMessageEnum; + +public enum GenericMessagesMessageEnum implements EcompMessageEnum { + + ECOMP_GENERAL_EXCEPTION, + ECOMP_GENERAL_ERROR, + ECOMP_GENERAL_INFO, + ECOMP_GENERAL_WARNING, + ECOMP_REMOTE_CALL_OK, + ECOMP_REQUEST_OK, + ECOMP_REMOTE_CALL_ERROR, + ECOMP_REQUEST_ERROR, + ECOMP_MISSING_REQUESTID, + ECOMP_LOGGER_NON_EMPTY_STACK, + ECOMP_LOGGER_POP_ON_EMPTY_STACK, + ECOMP_LOGGER_TOP_ON_EMPTY_STACK; + + static { + EELFResourceManager.loadMessageBundle("org/openecomp/logger/GenericMessages"); + } +} diff --git a/operation-utils/src/main/java/org/openecomp/entity/EcompSubComponentInstance.java b/operation-utils/src/main/java/org/openecomp/entity/EcompSubComponentInstance.java index 9b54bdd..2654dea 100644 --- a/operation-utils/src/main/java/org/openecomp/entity/EcompSubComponentInstance.java +++ b/operation-utils/src/main/java/org/openecomp/entity/EcompSubComponentInstance.java @@ -47,7 +47,8 @@ public class EcompSubComponentInstance { return uuid; } - public static void initialize() { + public static void initialize(String instanceID) { + uuid = instanceID; if (serverIP == null || serverName == null || ("").equals(serverIP) || ("").equals(serverName)) { try { InetAddress server = InetAddress.getLocalHost(); @@ -60,4 +61,8 @@ public class EcompSubComponentInstance { } } } + + public static void initialize() { + initialize(UUID.randomUUID().toString()); + } } diff --git a/operation-utils/src/main/java/org/openecomp/logger/EcompException.java b/operation-utils/src/main/java/org/openecomp/logger/EcompException.java new file mode 100644 index 0000000..712c1ed --- /dev/null +++ b/operation-utils/src/main/java/org/openecomp/logger/EcompException.java @@ -0,0 +1,53 @@ + +/*- + * ============LICENSE_START========================================== + * OPENECOMP - DCAE + * =================================================================== + * 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.logger; + +import com.att.eelf.i18n.EELFResourceManager; + +public class EcompException extends RuntimeException { + public EcompMessageEnum msgEnum; + public String[] args; + static final long serialVersionUID = -4904961953794640177L; + + protected EcompException(EcompMessageEnum msgEnum, String message) { + super(message); + this.msgEnum = msgEnum; + } + + protected EcompException(EcompMessageEnum msgEnum, String message, Throwable t) { + super(message, t); + this.msgEnum = msgEnum; + } + + public static EcompException create(EcompMessageEnum msgEnum, String... args) { + EcompException e = new EcompException(msgEnum, EELFResourceManager.format(msgEnum, args)); + e.args = args; + return e; + } + + public static EcompException create(EcompMessageEnum msgEnum, Throwable t, String... args) { + EcompException e = new EcompException(msgEnum, EELFResourceManager.format(msgEnum, args), t); + e.args = args; + return e; + } + +} diff --git a/operation-utils/src/main/java/org/openecomp/logger/EcompLogger.java b/operation-utils/src/main/java/org/openecomp/logger/EcompLogger.java index 254b06e..476c0c3 100644 --- a/operation-utils/src/main/java/org/openecomp/logger/EcompLogger.java +++ b/operation-utils/src/main/java/org/openecomp/logger/EcompLogger.java @@ -19,16 +19,16 @@ * ============LICENSE_END============================================ */ - package org.openecomp.logger; - - import java.io.PrintWriter; import java.io.StringWriter; import java.util.Date; import java.util.UUID; -import java.util.logging.Logger; + +import javax.servlet.http.HttpServletRequest; + +import com.att.eelf.i18n.EELFResourceManager; import org.slf4j.MDC; @@ -36,20 +36,10 @@ import org.openecomp.entity.EcompOperation; import org.openecomp.entity.EcompOperationEnum; import org.openecomp.entity.EcompSubComponentInstance; import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; import com.att.eelf.configuration.SLF4jWrapper; -/** - * Simple wrapper around the EELF Logger class for MSO usage. - * This class supports all of the normal logging functions (debug, info, etc.), - * prepending a string of format "[<requestId>|<serviceId]" to each message. - * - * MSO code should initialize with these IDs when available, so that individual - * requests and/or services can be tracked throughout the various MSO component - * logs (API Handler, BPEL, and Adapters). - * - */ public class EcompLogger { + // MDC parameters public static final String REQUEST_ID = "RequestId"; public static final String SERVICE_INSTANCE_ID = "ServiceInstanceId"; @@ -62,345 +52,631 @@ public class EcompLogger { public static final String TIMER = "Timer"; public static final String USER = "User"; public static final String CATALOG = "Catalog"; - public static final String DUMMY_REQUEST_VALUE = "?"; - public static final String DUMMY_SERVICE_INSTANCE_VALUE = "??"; - - private static final String FATAL_LEVEL = "FATAL"; - private static final String ERROR_LEVEL = "ERROR"; - private static final String WARN_LEVEL = "WARN"; - private static final String INFO_LEVEL = "INFO"; - private static final String DEBUG_LEVEL = "DEBUG"; - - private EELFLogger errorLogger, auditLogger, metricsLogger, debugLogger; - + public static final String DUMMY_REQUEST_VALUE = "?"; + public static final String DUMMY_SERVICE_INSTANCE_VALUE = "??"; + + public static final String THREAD_ID = "thread"; + public static final String PARTNER_NAME = "PartnerName"; + public static final String TARGET_ENTITY = "TargetEntity"; + public static final String TARGET_SERVICE_NAME = "TargetServiceName"; + public static final String STATUS_CODE = "StatusCode"; + public static final String RESPONSE_CODE = "ResponseCode"; + public static final String RESPONSE_DESCRIPTION = "ResponseDescription"; + public static final String CLASS_NAME = "ClassName"; + + private static final String FATAL_LEVEL = "FATAL"; + private static final String ERROR_LEVEL = "ERROR"; + private static final String WARN_LEVEL = "WARN"; + private static final String INFO_LEVEL = "INFO"; + private static final String DEBUG_LEVEL = "DEBUG"; + + private static final String CustomField1 = "CustomField1"; + private static final String CustomField2 = "CustomField2"; + private static final String CustomField3 = "CustomField3"; + private static final String CustomField4 = "CustomField4"; + + private EELFLogger errorLogger, auditLogger, metricsLogger, debugLogger; - // For internal logging of the initialization of MSO logs - private static final Logger LOGGER = Logger.getLogger (EcompLogger.class.getName ()); private static final String ERROR_LOGGER_NAME = "org.openecomp.error"; private static final String AUDIT_LOGGER_NAME = "org.openecomp.audit"; private static final String METRICS_LOGGER_NAME = "org.openecomp.metrics"; private static final String DEBUG_LOGGER_NAME = "org.openecomp.debug"; + protected EcompLogger() { + this.errorLogger = new SLF4jWrapper(ERROR_LOGGER_NAME); + this.auditLogger = new SLF4jWrapper(AUDIT_LOGGER_NAME); + this.metricsLogger = new SLF4jWrapper(METRICS_LOGGER_NAME); + this.debugLogger = new SLF4jWrapper(DEBUG_LOGGER_NAME); + } + + public static synchronized EcompLogger getEcompLogger() { + return new EcompLogger(); + } + + // region Error Logging region + + private void clearMetricFields() { + MDC.remove(RESPONSE_CODE); + MDC.remove(RESPONSE_DESCRIPTION); + MDC.remove(TARGET_ENTITY); + MDC.remove(TARGET_SERVICE_NAME); + MDC.remove(STATUS_CODE); + MDC.remove(CLASS_NAME); + MDC.remove(CustomField1); + MDC.remove(CustomField2); + MDC.remove(CustomField3); + MDC.remove(CustomField4); + } + + private void clearAuditFields() { + clearMetricFields(); + MDC.remove(SERVICE_NAME); + MDC.remove(PARTNER_NAME); + MDC.remove(REMOTE_HOST); + MDC.remove(INSTANCE_UUID); + MDC.remove(SERVICE_INSTANCE_ID); + MDC.remove(SERVICE_NAME); + MDC.remove(SERVICE_NAME); + } + + private void prepareMsgEELFv1(String threadID, String partnerName, String targetEntity, String targetServiceName, + StatusCodeEnum statusCode, String[] customFields) { + if (!isNullOrEmpty(threadID)) + MDC.put(THREAD_ID, threadID); + if (!isNullOrEmpty(partnerName)) + MDC.put(PARTNER_NAME, partnerName); + if (!isNullOrEmpty(targetEntity)) + MDC.put(TARGET_ENTITY, targetEntity); + if (!isNullOrEmpty(targetServiceName)) + MDC.put(TARGET_SERVICE_NAME, targetServiceName); + if (statusCode != null) + MDC.put(STATUS_CODE, statusCode.toString()); + + // Backfill unknown values + if (isNullOrEmpty(MDC.get(THREAD_ID))) + MDC.put(THREAD_ID, "UNKNOWN"); + if (isNullOrEmpty(MDC.get(PARTNER_NAME))) + MDC.put(PARTNER_NAME, "UNKNOWN"); + if (isNullOrEmpty(MDC.get(TARGET_ENTITY))) + MDC.put(TARGET_ENTITY, "UNKNOWN"); + if (isNullOrEmpty(MDC.get(TARGET_SERVICE_NAME))) + MDC.put(TARGET_SERVICE_NAME, "UNKNOWN"); + if (isNullOrEmpty(MDC.get(STATUS_CODE))) + MDC.put(STATUS_CODE, "UNKNOWN"); + + if (customFields != null) { + for (int i = 0; i < customFields.length; i++) { + MDC.put("CustomField" + Integer.toString(i + 1), customFields[i]); + if (i == 3) + break; + } + } + } + + // region Error Logging region - private EcompLogger () { - this.errorLogger = new SLF4jWrapper(ERROR_LOGGER_NAME); - this.auditLogger = new SLF4jWrapper(AUDIT_LOGGER_NAME);; - this.metricsLogger = new SLF4jWrapper(METRICS_LOGGER_NAME); - this.debugLogger = new SLF4jWrapper(DEBUG_LOGGER_NAME); - } - - - public static synchronized EcompLogger getEcompLogger () { - return new EcompLogger (); - } - - /** - * Record the Audit start event - * - */ - public void recordAuditEventStart (EcompMessageEnum msg, String... args) { - prepareMsg (INFO_LEVEL); - setStart(); - auditLogger.info (msg, args); - } - /** - * Record the Audit start event - * - */ - public void recordAuditEventStart () { - recordAuditEventStart(GenericMessageEnum.AUDIT_BEGIN); - } - - /** - * Record the Audit end event with log message to put - * - * @param arg0 The log message to put - */ - public void recordAuditEventEnd (EcompMessageEnum msg, String... args) { - setTimer(); - prepareMsg (INFO_LEVEL); - auditLogger.info (msg, normalizeArray(args)); - } - - /** - * Record the Audit end event with log message to put - * - * @param arg0 The log message to put - */ - public void recordAuditEventEnd () { - auditLogger.info (GenericMessageEnum.AUDIT_END); - } - /** - * Record the Metric start event without log message - * - */ - public void recordMetricEventStart (EcompMessageEnum msg, String... args) { - prepareMsg (INFO_LEVEL); - setStart(); - metricsLogger.info (msg, args); - } - - /** - * Record the Metric end event with log message to put - * - * @param arg0 The log message to put - */ - public void recordMetricEventEnd (EcompMessageEnum msg, String... args) { - prepareMsg (INFO_LEVEL); - setTimer(); - metricsLogger.info (msg, normalizeArray(args)); - } - /** - * Record the Metric start event without log message - * - */ - public void recordMetricEventStart () { - recordMetricEventStart(GenericMessageEnum.METRICS_BEGIN); - } - - /** - * Record the Metric end event with log message to put - * - * @param arg0 The log message to put - */ - public void recordMetricEventEnd () { - recordMetricEventEnd (GenericMessageEnum.METRICS_END); - } - - // Debug methods - /** - * Record the Debug event - * - * @param msg The log message to put - */ - public void debug (String msg) { - prepareMsg (DEBUG_LEVEL); - errorLogger.debug (msg); - } - - /** - * Record the Debug event - * - * @param msg The log message to put - * @param t The exception to put - */ - public void debug (String msg, Throwable t) { - prepareMsg (DEBUG_LEVEL); - errorLogger.debug (msg); - } - - // Info methods - /** - * Record the Info event - * - * @param msg The log message to put - */ - public void info (EcompMessageEnum msg, String... args) { - prepareMsg (INFO_LEVEL); - errorLogger.info (msg,normalizeArray(args)); - } + public void error(String threadID, String partnerName, LogCategoryEnum logCategoryEnum, String[] customFields, + EcompMessageEnum msg, String... args) { + prepareMsg(logCategoryEnum, msg); + prepareMsgEELFv1(threadID, partnerName, null, null, null, customFields); + errorLogger.error(msg, normalizeArray(args)); + clearMetricFields(); + } + + public void error(LogCategoryEnum logCategoryEnum, EcompMessageEnum msg, String... args) { + setClassName(); + prepareMsg(logCategoryEnum, msg); + errorLogger.error(msg, normalizeArray(args)); + } /** - * Record the Info event - * - * @param msg The log message to put - * @param t The exception info - */ - public void info (EcompMessageEnum msg, Throwable t, String... args) { - prepareMsg (WARN_LEVEL); - errorLogger.info (msg,normalizeArray(args)); - errorLogger.info ("Exception raised: " + getNormalizedStackTrace (t)); - errorLogger.debug ("Exception raised", t); - } - - // Warning methods - /** - * Record the Warning event - * - * @param msg The log message to put - */ - public void warn (EcompMessageEnum msg, String... args) { - prepareMsg (WARN_LEVEL); - errorLogger.warn (msg,normalizeArray(args)); - } + * Record the Error event + * + * @param msg + * The log message to put + */ + public void error(EcompMessageEnum msg, String... args) { + setClassName(); + prepareMsg(ERROR_LEVEL, msg); + errorLogger.error(msg, normalizeArray(args)); + } + /** + * Record the Error event + * + * @param msg + * The log message to put + * @param t + * The exception info + */ + public void error(EcompMessageEnum msg, Throwable t, String... args) { + setClassName(); + prepareMsg(ERROR_LEVEL, msg); + errorLogger.error(msg, normalizeArray(args)); + errorLogger.error(msg, getNormalizedStackTrace(t)); + errorLogger.debug("Exception raised", t); + } + /** + * Record the Info event + * + * @param msg + * The log message to put + */ + public void info(EcompMessageEnum msg, String... args) { + setClassName(); + prepareMsg(INFO_LEVEL, msg); + debugLogger.info(msg, normalizeArray(args)); + } /** - * Record the Warning event - * - * @param msg The log message to put - * @param t The exception info - */ - public void warn (EcompMessageEnum msg, Throwable t, String... args) { - prepareMsg (WARN_LEVEL); - errorLogger.warn (msg,normalizeArray(args)); - errorLogger.warn ("Exception raised: " + getNormalizedStackTrace (t)); - errorLogger.debug ("Exception raised", t); - } - - // Error methods - /** - * Record the Error event - * - * @param msg The log message to put - */ - public void error (EcompMessageEnum msg, String... args) { - prepareMsg (ERROR_LEVEL); - errorLogger.error (msg, normalizeArray(args)); - } - - /** - * Record the Error event - * - * @param msg The log message to put - * @param t The exception info - */ - public void error (EcompMessageEnum msg, Throwable t, String... args) { - prepareMsg (ERROR_LEVEL); - errorLogger.error (msg, normalizeArray(args)); - errorLogger.error (GenericMessageEnum.GENERAL_EXCEPTION, getNormalizedStackTrace (t)); - errorLogger.debug ("Exception raised", t); - } - - public boolean isDebugEnabled () { - return errorLogger.isDebugEnabled(); - } - - private void setStart() { - MDC.put("startTime", Long.toString(new Date().getTime())); + * Record the Info event + * + * @param msg + * The log message to put + * @param t + * The exception info + */ + public void info(EcompMessageEnum msg, Throwable t, String... args) { + setClassName(); + prepareMsg(WARN_LEVEL, msg); + debugLogger.info(msg, normalizeArray(args)); + debugLogger.info("Exception raised: " + getNormalizedStackTrace(t)); + debugLogger.debug("Exception raised", t); } + public void info(String msg) { + setClassName(); + prepareMsg(INFO_LEVEL); + debugLogger.debug(msg); + } - private void setTimer() { - Date d = new Date(Long.parseLong(MDC.get("startTime"))); - MDC.put(TIMER, Long.toString(new Date().getTime()-d.getTime())); - } - - - private void prepareMsg (String loggingLevel) { - prepareMsg (loggingLevel, null, null); - } - - private void prepareMsg (String loggingLevel, String serviceNamep, String timer) { - String reqId = MDC.get (REQUEST_ID); - String svcId = MDC.get (SERVICE_INSTANCE_ID); - - if (reqId == null || reqId.isEmpty()) { - MDC.put (REQUEST_ID, DUMMY_REQUEST_VALUE); - } - - if (svcId == null || svcId.isEmpty()) { - MDC.put (SERVICE_INSTANCE_ID, DUMMY_SERVICE_INSTANCE_VALUE); - } - - if (timer != null) { - MDC.put (TIMER, timer); - } else { - MDC.remove(TIMER); - } - - MDC.put (ALERT_SEVERITY, getSeverityLevel (loggingLevel)); -// MDC.put (INSTANCE_UUID, EcompSubComponentInstance.getUuid()); - MDC.put (SERVER_IP, EcompSubComponentInstance.getServerIP()); - MDC.put (FQDN, EcompSubComponentInstance.getServerName()); - } - - private String getSeverityLevel (String loggingLevel) { - String severity; - // According to the Nagios alerting: 0=OK; 1=WARNING; 2=UNKOWN; 3=CRITICAL - switch (loggingLevel) { - case ERROR_LEVEL: - severity = "2"; - break; - case FATAL_LEVEL: - severity = "3"; - break; - case WARN_LEVEL: - severity = "1"; - break; - default: - severity = "0"; - break; - } - return severity; - } - - - public static void setLogContext (String reqId, String svcId) { - MDC.put (REQUEST_ID, reqId); - MDC.put (SERVICE_INSTANCE_ID, svcId); - } - - public static void setLoggerParameters (String remoteIpp, String userp) { - MDC.put (REMOTE_HOST, remoteIpp); - MDC.put (USER, userp); - } - - public static void setServiceName (String serviceNamep) { - MDC.put (SERVICE_NAME, serviceNamep); - } - - public static void resetServiceName () { - MDC.remove (SERVICE_NAME); - } - - public static void setLogContext (EcompOperation operation) { - if (operation != null) { - MDC.put (REQUEST_ID, operation.getRequestId()); - MDC.put (SERVICE_INSTANCE_ID, operation.getServiceInstanceId()); - } - else { - MDC.put (REQUEST_ID, DUMMY_REQUEST_VALUE); - MDC.put (SERVICE_INSTANCE_ID, DUMMY_SERVICE_INSTANCE_VALUE); - } - } - - private String normalize (String input) { - if (input == null) { - return null; - } - String result = input.replace ('|', '!'); - result = result.replace ("\n", " - "); - return result; - } - - - private String[] normalizeArray(String[] args) { - for (int i = 0; i< args.length; i++) { - args[i] = normalize(args[i]); + /** + * Record the Warning event + * + * @param msg + * The log message to put + */ + public void warn(EcompMessageEnum msg, String... args) { + setClassName(); + prepareMsg(WARN_LEVEL, msg); + errorLogger.warn(msg, normalizeArray(args)); + } + + /** + * Record the Warning event + * + * @param msg + * The log message to put + * @param t + * The exception info + */ + public void warn(EcompMessageEnum msg, Throwable t, String... args) { + setClassName(); + prepareMsg(WARN_LEVEL, msg); + errorLogger.warn(msg, normalizeArray(args)); + errorLogger.warn("Exception raised: " + getNormalizedStackTrace(t)); + errorLogger.debug("Exception raised", t); + } + + /** + * Record the Debug event + * + * @param msg + * The log message to put + */ + public void debug(String msg) { + setClassName(); + prepareMsg(DEBUG_LEVEL); + debugLogger.debug(msg); + } + + /** + * Record the Debug event + * + * @param msg + * The log message to put + * @param t + * The exception to put + */ + public void debug(String msg, Throwable t) { + setClassName(); + prepareMsg(DEBUG_LEVEL); + debugLogger.debug(msg, t); + } + + public void debug(EcompMessageEnum msg, String... args) { + setClassName(); + prepareMsg(DEBUG_LEVEL, msg); + debugLogger.info(msg, normalizeArray(args)); + } + + public void debug(Throwable t, EcompMessageEnum msg, String... args) { + setClassName(); + prepareMsg(DEBUG_LEVEL, msg); + debugLogger.info(msg, t, normalizeArray(args)); + } + + // endregion Error Logging region + + // region Audit Logging section + + /** + * Record the Audit start event + */ + public void recordAuditEventStart() { + Stopwatch.clearAndStart(); + // recordAuditEventStart(GenericMessageEnum.AUDIT_BEGIN); + } + + public void recordAuditEventStart(String targetEntity, String targetServiceName) { + Stopwatch.clearAndStart(); + if (!isNullOrEmpty(targetEntity)) + MDC.put(TARGET_ENTITY, targetEntity); + if (!isNullOrEmpty(targetServiceName)) + MDC.put(TARGET_SERVICE_NAME, targetServiceName); + } + + /** + * Record the Audit start event + */ + public void recordAuditEventStart(EcompMessageEnum msg, String... args) { + Stopwatch.clearAndStart(); + /* + * prepareMsg (INFO_LEVEL); setStart(); auditLogger.info (msg, args); + */ + } + + protected void recordAuditEventEnd(StatusCodeEnum statusCode, LogCategoryEnum logCategoryEnum, + String[] customFields, EcompMessageEnum msg, String... args) { + Stopwatch.stopAndPop(); + if (!Stopwatch.emptyStack()) { + warn(GenericMessagesMessageEnum.ECOMP_LOGGER_NON_EMPTY_STACK); } - return args; + setClassName(); + prepareMsg(logCategoryEnum, msg); + prepareMsgEELFv1(null, null, null, null, statusCode, customFields); + auditLogger.info(msg, normalizeArray(args)); + clearAuditFields(); + } + + public void setClassName() { + StackTraceElement[] l = Thread.currentThread().getStackTrace(); + for (StackTraceElement x : l) { + if (x.getClassName().equals("java.lang.Thread")) + continue; + if (x.getClassName().equals("org.openecomp.logger.EcompLogger")) + continue; + if (x.getClassName().equals("org.openecomp.logger.Stopwatch")) + continue; + MDC.put(CLASS_NAME, x.getClassName() + "@" + x.getMethodName() + ":" + x.getLineNumber()); + return; + } + } + + /** + * Record the Audit end event with log message to put + */ + public void recordAuditEventEnd() { + recordAuditEventEnd(StatusCodeEnum.COMPLETE, LogCategoryEnum.INFO, null, + GenericMessagesMessageEnum.ECOMP_REQUEST_OK); + } + + public void recordAuditEventEnd(StatusCodeEnum code) { + if (code == StatusCodeEnum.COMPLETE) { + EcompMessageEnum msg = GenericMessagesMessageEnum.ECOMP_REQUEST_OK; + recordAuditEventEnd(code, msg2cat(msg), null, msg); + } else { + EcompMessageEnum msg = GenericMessagesMessageEnum.ECOMP_REQUEST_ERROR; + recordAuditEventEnd(code, msg2cat(msg), null, msg, "unknown error"); + } + } + + /** + * Record the Audit end event with log message to put + */ + public void recordAuditEventEnd(EcompMessageEnum msg, String... args) { + recordAuditEventEnd(StatusCodeEnum.COMPLETE, LogCategoryEnum.INFO, null, msg, args); + } + + // endregion + + // region Metrics Logging region + + public void recordAuditEventEnd(StatusCodeEnum code, EcompMessageEnum msg, String... args) { + recordAuditEventEnd(code, msg2cat(msg), null, msg, args); + } + + /** + * Record the Metric start event without log message + */ + public void recordMetricEventStart() { + Stopwatch.pushAndStart(null, null); + // recordMetricEventStart(GenericMessageEnum.METRICS_BEGIN); + } + + public void recordMetricEventStart(String targetEntity, String targetServiceName) { + Stopwatch.pushAndStart(targetEntity, targetServiceName); + } + + /** + * Record the Metric start event without log message + */ + public void recordMetricEventStart(EcompMessageEnum msg, String... args) { + Stopwatch.pushAndStart(msg.toString(), null); + } + + public void recordMetricEventStart(EcompOperationEnum op, String target) { + Stopwatch.pushAndStart(op.toString(), target); + } + + protected void recordMetricEventEnd(StatusCodeEnum statusCode, LogCategoryEnum logCategoryEnum, + String[] customFields, EcompMessageEnum msg, String... args) { + Stopwatch.stopAndPop(); + setClassName(); + prepareMsg(logCategoryEnum, msg); + prepareMsgEELFv1(null, null, null, null, statusCode, customFields); + metricsLogger.info(msg, normalizeArray(args)); + clearMetricFields(); + } + + /** + * Record the Metric end event with log message to put + */ + public void recordMetricEventEnd(EcompMessageEnum msg, String... args) { + recordMetricEventEnd(StatusCodeEnum.COMPLETE, msg2cat(msg), null, msg, args); + } + + /** + * Record the Metric end event with log message to put + */ + public void recordMetricEventEnd() { + recordMetricEventEnd(GenericMessagesMessageEnum.ECOMP_REMOTE_CALL_OK); + } + + public void recordMetricEventEnd(StatusCodeEnum code) { + if (code == StatusCodeEnum.COMPLETE) { + EcompMessageEnum msg = GenericMessagesMessageEnum.ECOMP_REMOTE_CALL_OK; + recordMetricEventEnd(code, msg2cat(msg), null, msg); + } else { + EcompMessageEnum msg = GenericMessagesMessageEnum.ECOMP_REMOTE_CALL_ERROR; + recordMetricEventEnd(code, msg2cat(msg), null, msg, "unknown error"); + } + } + + public void recordMetricEventEnd(StatusCodeEnum code, EcompMessageEnum msg, String... args) { + recordMetricEventEnd(code, msg2cat(msg), null, msg, args); + } + + // endregion + + // region Setters Public + + public static void setLogContext(String reqId, String svcId) { + MDC.put(REQUEST_ID, reqId); + MDC.put(SERVICE_INSTANCE_ID, svcId); + } + + public static void setLogContext(EcompOperationEnum op, String serviceInstanceId, String requestId, + String partnerName) { + MDC.put(SERVICE_NAME, op.toString()); + MDC.put(SERVICE_INSTANCE_ID, serviceInstanceId); + MDC.put(REQUEST_ID, requestId); + MDC.put(THREAD_ID, Long.toString(Thread.currentThread().getId())); + MDC.put(PARTNER_NAME, partnerName); + } + + public static void setLoggerParameters(String remoteIpp, String userp) { + MDC.put(REMOTE_HOST, remoteIpp); + MDC.put(USER, userp); + } + + public static void setServiceName(String serviceNamep) { + MDC.put(SERVICE_NAME, serviceNamep); } - private String getNormalizedStackTrace (Throwable t) { - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); - t.printStackTrace(pw); - return sw.toString().replace ('|', '!').replace ("\n", " - "); - } + public void setPartnerName(String name) { + MDC.put(PARTNER_NAME, name); + } + public static void setLogContext(EcompOperation operation) { + if (operation != null) { + MDC.put(REQUEST_ID, operation.getRequestId()); + MDC.put(SERVICE_INSTANCE_ID, operation.getServiceInstanceId()); + } else { + MDC.put(REQUEST_ID, DUMMY_REQUEST_VALUE); + MDC.put(SERVICE_INSTANCE_ID, DUMMY_SERVICE_INSTANCE_VALUE); + } + } public void setOperation(EcompOperationEnum op) { - MDC.put (SERVICE_NAME, op.toString()); + MDC.put(SERVICE_NAME, op.toString()); + } + + public void setRequestId(String requestId) { + MDC.put(REQUEST_ID, requestId); + } + + // endregion + + // region Setters Private + + private LogCategoryEnum msg2cat(EcompMessageEnum msg) { + String s = EELFResourceManager.getIdentifier(msg); + char c = 'W'; + if (s != null && s.length() > 0) + c = s.toUpperCase().charAt(0); + switch (c) { + case 'I': + return LogCategoryEnum.INFO; + case 'W': + return LogCategoryEnum.WARN; + case 'E': + return LogCategoryEnum.ERROR; + case 'F': + return LogCategoryEnum.FATAL; + } + return LogCategoryEnum.WARN; + } + + @SuppressWarnings("unused") + private void setStart() { + MDC.put("startTime", Long.toString(new Date().getTime())); + } + + @SuppressWarnings("unused") + private void setTimer() { + Date d = new Date(Long.parseLong(MDC.get("startTime"))); + MDC.put(TIMER, Long.toString(new Date().getTime() - d.getTime())); + } + + // endregion + + // region Helpers + + private void prepareMsg(LogCategoryEnum logCategoryEnum, EcompMessageEnum msg) { + prepareMsg(getSeverityLevel(logCategoryEnum), null, null, msg); + } + + private void prepareMsg(String loggingLevel, EcompMessageEnum msg) { + prepareMsg(loggingLevel, null, null, msg); + } + + private void prepareMsg(String loggingLevel, String serviceNamep, String timer, EcompMessageEnum msg) { + String reqId = MDC.get(REQUEST_ID); + String svcId = MDC.get(SERVICE_INSTANCE_ID); + + if (reqId == null || reqId.isEmpty()) { + MDC.put(REQUEST_ID, UUID.randomUUID().toString()); + } + + if (svcId == null || svcId.isEmpty()) { + MDC.put(SERVICE_INSTANCE_ID, DUMMY_SERVICE_INSTANCE_VALUE); + } + + if (timer != null) { + MDC.put(TIMER, timer); + } else { + MDC.remove(TIMER); + } + + String instance = MDC.get(INSTANCE_UUID); + if (instance == null || instance.isEmpty()) { + MDC.put(INSTANCE_UUID, EcompSubComponentInstance.getUuid()); + } + + MDC.put(ALERT_SEVERITY, getSeverityLevel(loggingLevel)); + MDC.put(SERVER_IP, EcompSubComponentInstance.getServerIP()); + MDC.put(FQDN, EcompSubComponentInstance.getServerName()); + + if (null != msg) { + MDC.put(RESPONSE_CODE, EELFResourceManager.getIdentifier(msg)); + MDC.put(RESPONSE_DESCRIPTION, EELFResourceManager.getDescription(msg)); + } + } + + private void prepareMsg(String loggingLevel) { + prepareMsg(loggingLevel, null, null, null); + } + + private String getSeverityLevel(String loggingLevel) { + String severity; + // According to the Nagios alerting: 0=OK; 1=WARNING; 2=UNKOWN; + // 3=CRITICAL + switch (loggingLevel) { + case ERROR_LEVEL: + severity = "2"; + break; + case FATAL_LEVEL: + severity = "3"; + break; + case WARN_LEVEL: + severity = "1"; + break; + default: + severity = "0"; + break; + } + return severity; + } + + private String getSeverityLevel(LogCategoryEnum logCategoryEnum) { + String severity; + // According to the Nagios alerting: 0=OK; 1=WARNING; 2=UNKOWN; + // 3=CRITICAL + switch (logCategoryEnum) { + case FATAL: + severity = "2"; + break; + case ERROR: + severity = "3"; + break; + case WARN: + severity = "1"; + break; + default: + severity = "0"; + break; + } + return severity; + } + + private String normalize(String input) { + if (input == null) { + return null; + } + String result = input.replace('|', '!'); + result = result.replace("\n", " - "); + return result; + } + + private String[] normalizeArray(String[] args) { + for (int i = 0; i < args.length; i++) { + args[i] = normalize(args[i]); + } + return args; } + private String getNormalizedStackTrace(Throwable t) { + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + t.printStackTrace(pw); + return sw.toString().replace('|', '!').replace("\n", " - "); + } + + // endregion + public void newRequestId() { String uuid = UUID.randomUUID().toString(); - MDC.put (REQUEST_ID, uuid); + MDC.put(REQUEST_ID, uuid); } - - public void setRequestId(String requestId) { - MDC.put (REQUEST_ID, requestId); + public boolean isDebugEnabled() { + return errorLogger.isDebugEnabled(); } - + public void setRemoteHost(String remote) { - MDC.put (REMOTE_HOST, remote); + MDC.put(REMOTE_HOST, remote); } - + public void setInstanceId(String instance) { - MDC.put (INSTANCE_UUID, instance); + MDC.put(INSTANCE_UUID, instance); + } + + static boolean isNullOrEmpty(String value) { + return (value == null || value.isEmpty()) ? true : false; } + public void missingRequestId(HttpServletRequest request) { + warn(GenericMessagesMessageEnum.ECOMP_MISSING_REQUESTID, request.getRemoteHost()); + } + + public String getRequestId() { + return MDC.get(REQUEST_ID); + } + + @Override + public String toString() { + return MDC.getCopyOfContextMap().toString(); + } } diff --git a/operation-utils/src/main/java/org/openecomp/logger/GenericMessageEnum.java b/operation-utils/src/main/java/org/openecomp/logger/LogCategoryEnum.java index deed808..dcc69e0 100644 --- a/operation-utils/src/main/java/org/openecomp/logger/GenericMessageEnum.java +++ b/operation-utils/src/main/java/org/openecomp/logger/LogCategoryEnum.java @@ -21,18 +21,10 @@ package org.openecomp.logger; -import com.att.eelf.i18n.EELFResourceManager; - -public enum GenericMessageEnum implements EcompMessageEnum { - GENERAL_INFO, - GENERAL_WARNING, - GENERAL_ERROR, - GENERAL_EXCEPTION, - AUDIT_BEGIN, - AUDIT_END, - METRICS_BEGIN, - METRICS_END; - static { - EELFResourceManager.loadMessageBundle("GenericMessages"); - } +public enum LogCategoryEnum { + //0=INFO, 1=WARN, 2=ERROR, 3=FATAL + INFO, + WARN, + ERROR, + FATAL } diff --git a/operation-utils/src/main/java/org/openecomp/logger/StatusCodeEnum.java b/operation-utils/src/main/java/org/openecomp/logger/StatusCodeEnum.java new file mode 100644 index 0000000..53b549b --- /dev/null +++ b/operation-utils/src/main/java/org/openecomp/logger/StatusCodeEnum.java @@ -0,0 +1,27 @@ + +/*- + * ============LICENSE_START========================================== + * OPENECOMP - DCAE + * =================================================================== + * 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.logger; + +public enum StatusCodeEnum { + COMPLETE, + ERROR +} diff --git a/operation-utils/src/main/java/org/openecomp/logger/Stopwatch.java b/operation-utils/src/main/java/org/openecomp/logger/Stopwatch.java new file mode 100644 index 0000000..e86713d --- /dev/null +++ b/operation-utils/src/main/java/org/openecomp/logger/Stopwatch.java @@ -0,0 +1,253 @@ + +/*- + * ============LICENSE_START========================================== + * OPENECOMP - DCAE + * =================================================================== + * 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.logger; + +import static com.att.eelf.configuration.Configuration.MDC_BEGIN_TIMESTAMP; +import static com.att.eelf.configuration.Configuration.MDC_ELAPSED_TIME; +import static com.att.eelf.configuration.Configuration.MDC_END_TIMESTAMP; +import static com.att.eelf.configuration.Configuration.MDC_TARGET_ENTITY; +import static com.att.eelf.configuration.Configuration.MDC_TARGET_SERVICE_NAME; + +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.TimeZone; + +import org.slf4j.MDC; + + +/** + * This class is used to time events to determine their duration. The stop watch allows for the same types of operations + * as a real stop watch, that is, it allows the timing to be stopped, started, cleared, and read. The accumulated time + * is the total of all times between start and stop events. The watch can be repeatedly stopped and restarted, and will + * accumulate all durations between start/stop pairs. + */ +public class Stopwatch { + + public static String ISO_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; + public static final TimeZone utc = TimeZone.getTimeZone("UTC"); + public static final SimpleDateFormat isoFormatter = new SimpleDateFormat(ISO_FORMAT); + public static EcompLogger ecompLogger = EcompLogger.getEcompLogger(); + + /** + * This is the object that maintains our state on the thread local storage + */ + public static class StopwatchState { + /** + * The accumulated duration + */ + private long duration; + + /** + * Indicates that the watch is running + */ + private boolean running = false; + + /** + * The last recorded start time + */ + private long startTime; + + public String target; + + public String op; + + @Override + public String toString() { + return "StopwatchState [duration=" + duration + ", running=" + running + ", startTime=" + startTime + "]"; + } + + } + + public static class StopwatchStateStack { + private List<StopwatchState> l = new ArrayList<Stopwatch.StopwatchState>(); + + public StopwatchState top() { +// System.out.println("WWWWWW: " + Thread.currentThread().getName() + ": top 1 " + l); + if (l.size() == 0) { + ecompLogger.warn(GenericMessagesMessageEnum.ECOMP_LOGGER_TOP_ON_EMPTY_STACK); +// System.out.println("WWWWWW: " + Thread.currentThread().getName() + ": top empty"); + push(null,null); + } +// System.out.println("WWWWWW: " + Thread.currentThread().getName() + ": top 2 " + l); + return l.get(l.size()-1); + } + + public void push(String targetEntity, String target) { + l.add(new StopwatchState()); + top().op = targetEntity; + top().target = target; +// System.out.println("WWWWWW: " + Thread.currentThread().getName() + ": push 2 " + l); + } + + public void pop() { +// System.out.println("WWWWWW: " + Thread.currentThread().getName() + ": pop 1 " + l); + if (l.size() == 0) { + ecompLogger.warn(GenericMessagesMessageEnum.ECOMP_LOGGER_POP_ON_EMPTY_STACK); + return; + } + l.remove(l.size()-1); + } + + public void clear() { +// System.out.println("WWWWWW: " + Thread.currentThread().getName() + ": clear 1" + l); + l.clear(); + } + } + + /** + * Thread local storage wrapper + */ + private static ThreadLocal<StopwatchStateStack> tls = new ThreadLocal<>(); + + static { + isoFormatter.setTimeZone(utc); + } + + /** + * Looks up the Thread Local storage object containing the Stopwatch state, and creates it if it does not already + * exist. + * + * @return The state object + */ + private static StopwatchStateStack getState() { + StopwatchStateStack state = tls.get(); + if (state == null) { + state = new StopwatchStateStack(); + tls.set(state); + } + return state; + } + + /** + * Clears (and possibly stops) the watch. + */ + public static void clear() { + getState().clear(); + } + + /** + * The accumulated duration of the watch (in nano-seconds) + * + * @return The accumulated time + */ + public static long getDuration() { + StopwatchState state = getState().top(); + return state.duration; + } + + /** + * Determines if the stopwatch is currently running or not + * + * @return True if the watch is running + */ + public static boolean isRunning() { + StopwatchState state = getState().top(); + return state.running; + } + + /** + * Starts the watch if not already running. + */ + public static void start() { + StopwatchState state = getState().top(); + if (!state.running) { + state.running = true; + state.startTime = System.currentTimeMillis(); + MDC.put(MDC_BEGIN_TIMESTAMP, isoFormatter.format(new Date(state.startTime))); + } + } + + /** + * Stops the accumulation of time on the watch if running + */ + public static void stop() { + StopwatchState state = getState().top(); + if (state.running) { + long stopTime = System.currentTimeMillis(); + state.duration += (stopTime - state.startTime); + state.running = false; + MDC.put(MDC_END_TIMESTAMP,isoFormatter.format(new Date(stopTime))); + MDC.put(MDC_ELAPSED_TIME, String.valueOf(state.duration)); + } + if (!EcompLogger.isNullOrEmpty(state.target)) + MDC.put(MDC_TARGET_ENTITY, state.target); + if (state.op != null) + MDC.put(MDC_TARGET_SERVICE_NAME, state.op); + } + + /** + * Gets the amount of time since the stop watch was last started without stopping the watch or accumulating the + * previous time . + */ + public static double getCurrentDuration() { + StopwatchState state = getState().top(); + if (state.running) { + return (System.currentTimeMillis() - state.startTime); + } + return 0L; + } + + public static void pushNewWatch(String targetEntity, String target) { +// System.out.println("WWWWWW: " + Thread.currentThread().getName() + ": pushNewWatch 1" + getState().l); + getState().push(targetEntity,target); +// System.out.println("WWWWWW: " + Thread.currentThread().getName() + ": pushNewWatch 2" + getState().l); + } + + public static void popWatch() { + stop(); + getState().pop(); + } + + public static void clearAndStart() { +// System.out.println("WWWWWW: " + Thread.currentThread().getName() + " clearAndStart 1" + getState().l); + clear(); +// System.out.println("WWWWWW: " + Thread.currentThread().getName() + ": clearAndStart 2" + getState().l); + pushAndStart(null,null); +// System.out.println("WWWWWW: " + Thread.currentThread().getName() + ": clearAndStart 3" + getState().l); + } + + public static void stopAndPop() { +// System.out.println("WWWWWW: " + Thread.currentThread().getName() + ": stopAndPop 1" + getState().l); + stop(); +// System.out.println("WWWWWW: " + Thread.currentThread().getName() + ": stopAndPop 2" + getState().l); + popWatch(); +// System.out.println("WWWWWW: " + Thread.currentThread().getName() + ": stopAndPop 3" + getState().l); + } + + public static void pushAndStart(String targetEntity, String target) { +// System.out.println("WWWWWW: " + Thread.currentThread().getName() + ": pushAndStart 1" + getState().l); + pushNewWatch(targetEntity,target); +// System.out.println("WWWWWW: " + Thread.currentThread().getName() + ": pushAndStart 2" + getState().l); + start(); +// System.out.println("WWWWWW: " + Thread.currentThread().getName() + ": pushAndStart 3" + getState().l); + } + + public static boolean emptyStack() { + return getState().l.size() == 0; + } + + public static String getTopTarget() { + return getState().top().target; + } +} diff --git a/operation-utils/src/main/java/org/openecomp/utils/YamlToJava.java b/operation-utils/src/main/java/org/openecomp/utils/YamlToJava.java index 4577e06..fb3b1f4 100644 --- a/operation-utils/src/main/java/org/openecomp/utils/YamlToJava.java +++ b/operation-utils/src/main/java/org/openecomp/utils/YamlToJava.java @@ -42,51 +42,62 @@ import org.openecomp.ncomp.utils.PropertyUtil; import org.openecomp.ncomp.webservice.utils.FileUtils; public class YamlToJava { - -// package org.openecomp.operation.logging.usecases; -// -// import org.openecomp.logger.EcompMessageEnum; -// import com.att.eelf.i18n.EELFResourceManager; -// -// public enum MyMessageEnum implements EcompMessageEnum { -// // Api Handler Messages -// FOOBAR; -// -// static { -// EELFResourceManager.loadMessageBundle("foobar"); -// } -// } - + + // package org.openecomp.operation.logging.usecases; + // + // import org.openecomp.logger.EcompMessageEnum; + // import com.att.eelf.i18n.EELFResourceManager; + // + // public enum MyMessageEnum implements EcompMessageEnum { + // // Api Handler Messages + // FOOBAR; + // + // static { + // EELFResourceManager.loadMessageBundle("foobar"); + // } + // } + + static public void convert(String yamlFileName, String outputDir, String packageName) { + convert(yamlFileName, outputDir, outputDir, packageName); + } + @SuppressWarnings("unchecked") - static public void convert(String yamlFileName, String outputSourceRootDir, String packageName) { + static public void convert(String yamlFileName, String propertiesOutputDirectory, String enumOutputDirectory, + String packageName) { try { - if (! (new File(yamlFileName).exists())) { + System.out.println("Enterting YAML Convert)"); + if (!(new File(yamlFileName).exists())) { System.err.println(yamlFileName + " does not exists"); return; } DumperOptions options = new DumperOptions(); options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); Yaml y = new Yaml(options); - Map<String,Object> m = (Map<String, Object>) y.load(FileUtils.filename2stream(yamlFileName, null)); + Map<String, Object> m = (Map<String, Object>) y.load(FileUtils.filename2stream(yamlFileName, null)); File f = new File(yamlFileName); String name = f.getName().replace(".yaml", ""); m.put("name", name); m.put("packageName", packageName); - String ofile1 = outputSourceRootDir + "/" + name + ".properties"; + String resourcePath = packageName.replace('.', '/'); + m.put("resourcePath", resourcePath); + String ofile1 = propertiesOutputDirectory + "/" + name + ".properties"; + System.out.println("Properties file path => " + ofile1); OutputStreamWriter w; SimpleTemplateEngine engine = new SimpleTemplateEngine(); if (m.containsKey("messages")) { w = FileUtils.filename2writer(ofile1); w.append(engine.createTemplate(getTemplate("properties_template")).make(m).toString()); w.close(); - String ofile2 = outputSourceRootDir + "/" + name + "MessageEnum.java"; + String ofile2 = enumOutputDirectory + "/" + name + "MessageEnum.java"; + System.out.println("Message Enum file path => " + ofile2); w = FileUtils.filename2writer(ofile2); w.append(engine.createTemplate(getTemplate("messageEnum.java_template")).make(m).toString()); w.close(); } if (m.containsKey("operations")) { - String ofile3 = outputSourceRootDir + "/" + name + "OperationEnum.java"; + String ofile3 = enumOutputDirectory + "/" + name + "OperationEnum.java"; w = FileUtils.filename2writer(ofile3); + System.out.println("Operation Enum file path => " + ofile3); w.append(engine.createTemplate(getTemplate("operationEnum.java_template")).make(m).toString()); w.close(); } @@ -104,31 +115,63 @@ public class YamlToJava { ByteArrayOutputStream o = new ByteArrayOutputStream(); FileUtils.copyStream(in, o); return o.toString(); -} + } public static void main(String[] args) throws IOException { - Properties props = new Properties(); - String pname = "GenericMessages.properties"; - String fname = "src/main/resources/GenericMessages.yaml"; - props.load(YamlToJava.class.getClassLoader().getResourceAsStream(pname)); + for (int i = 0; i < args.length; i++) { + System.out.println(" Argument " + Integer.toString(i) + " ==> " + args[i]); + } + + switch (args.length) { + case 1: + String baseDir = findBaseDir(args[0]); + Map<String, Object> m = file2yaml(args[0]); + String javaDest = (String) (m.containsKey("java-root") ? m.get("java-root") : "src/main/java-gen"); + String resourcesDest = (String) (m.containsKey("resources-root") ? m.get("resources-root") + : "src/main/resources-gen"); + if (! javaDest.startsWith("/")) javaDest = baseDir + "/" + javaDest; + if (! resourcesDest.startsWith("/")) resourcesDest = baseDir + "/" + resourcesDest; + String packageName = (String) m.get("package-name"); + if (packageName == null) { + System.err.println("No package-name attribute in: " + args[0]); + System.exit(2); + } + String packageDir = "/" + packageName.replace(".", "/"); + convert(args[0], resourcesDest + packageDir, javaDest + packageDir, packageName); + break; + case 4: + convert(args[0], args[1], args[2], args[3]); + break; + case 5: + convert(args[1], args[2], args[3], args[4]); + break; + default: + System.err.println("Invalid arguments, expected --> yamlFileName"); + System.exit(2); + } + } + + private static String findBaseDir(String filename) { + File f = new File(filename); + f = f.getParentFile(); + while (f != null) { + File pom = new File(f,"pom.xml"); + if (pom.exists()) return f.getAbsolutePath(); + f = f.getParentFile(); + } + return "."; + } + + @SuppressWarnings("unchecked") + private static Map<String, Object> file2yaml(String yamlFileName) { + if (!(new File(yamlFileName).exists())) { + System.err.println(yamlFileName + " does not exists"); + System.exit(2); + } DumperOptions options = new DumperOptions(); options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); Yaml y = new Yaml(options); - JSONObject j = new JSONObject(); - for (Object k : props.keySet()) { - String a[] = props.getProperty((String) k).split("\\|"); - JSONObject j1 = new JSONObject(); - j.put((String) k, j1); - j1.put("errorCode", a[0]); - j1.put("messageFormat", a[1]); - j1.put("resolution", a[2]); - j1.put("description", a[3].trim()); - } - - Object data = y.load(j.toString()); - OutputStreamWriter w = FileUtils.filename2writer(fname); - w.append(y.dump(data) + "\n"); - w.close(); + return (Map<String, Object>) y.load(FileUtils.filename2stream(yamlFileName, null)); } } diff --git a/operation-utils/src/main/resources-gen/org/openecomp/logger/GenericMessages.properties b/operation-utils/src/main/resources-gen/org/openecomp/logger/GenericMessages.properties new file mode 100644 index 0000000..ae5ee3d --- /dev/null +++ b/operation-utils/src/main/resources-gen/org/openecomp/logger/GenericMessages.properties @@ -0,0 +1,72 @@ + +ECOMP_GENERAL_EXCEPTION=\ + ECOMP-GENERAL-EXCEPTION-5404W|\ + {0}|\ + Please check other logs for more detailed info|\ + General exception + +ECOMP_GENERAL_ERROR=\ + ECOMP-GENERAL-ERROR-5403E|\ + {0}|\ + Please check other logs for more detailed info|\ + General error + +ECOMP_GENERAL_INFO=\ + ECOMP-GENERAL-INFO-5401I|\ + {0}|\ + Please check other logs for more detailed info|\ + General info + +ECOMP_GENERAL_WARNING=\ + ECOMP-GENERAL-WARNING-5402W|\ + {0}|\ + Please check other logs for more detailed info|\ + General warning + +ECOMP_REMOTE_CALL_OK=\ + ECOMP-REMOTE-CALL-OK-2000I|\ + |\ + No resolution needed|\ + Remote Call Succeess + +ECOMP_REQUEST_OK=\ + ECOMP-REQUEST-OK-2000I|\ + |\ + No resolution needed|\ + Request Success + +ECOMP_REMOTE_CALL_ERROR=\ + ECOMP-REMOTE-CALL-ERROR-4000W|\ + {0}|\ + No resolution needed|\ + Remote Call Failed + +ECOMP_REQUEST_ERROR=\ + ECOMP-REQUEST-ERROR-4000I|\ + {0}|\ + No resolution needed|\ + Request Failed + +ECOMP_MISSING_REQUESTID=\ + ECOMP-MISSING-REQUESTID-3401W|\ + Missing request id from {0}|\ + Need to get north bound entity to provide request ID per ECOMP logging requirements|\ + Got a north bound request that was missing a request ID. + +ECOMP_LOGGER_NON_EMPTY_STACK=\ + ECOMP-LOGGER-NON-EMPTY-STACK-4401W|\ + |\ + Development bug.|\ + Component recorded an Audit End with an non empty stack + +ECOMP_LOGGER_POP_ON_EMPTY_STACK=\ + ECOMP-LOGGER-POP-ON-EMPTY-STACK-4402W|\ + |\ + Development bug.|\ + Component performed a Pop on empty stack + +ECOMP_LOGGER_TOP_ON_EMPTY_STACK=\ + ECOMP-LOGGER-TOP-ON-EMPTY-STACK-4403W|\ + |\ + Development bug.|\ + Component performed a Top on empty stack diff --git a/operation-utils/src/main/resources/GenericMessages.properties b/operation-utils/src/main/resources/GenericMessages.properties index b7322f8..d3dc81a 100644 --- a/operation-utils/src/main/resources/GenericMessages.properties +++ b/operation-utils/src/main/resources/GenericMessages.properties @@ -41,7 +41,12 @@ GENERAL_ERROR=\ ECOMP-GENERAL-ERROR-5403|\ {0}|\ Please check other logs for more detailed info|\ - General error + General error +GENERAL_EXCEPTION=\ + ECOMP-GENERAL-ERROR-5404|\ + {0}|\ + Please check other logs for more detailed info|\ + General exception AUDIT_BEGIN=\ ECOMP-GENERAL-5403|\ Entering method|\ @@ -62,4 +67,8 @@ METRICS_END=\ Exiting method|\ No resolution needed|\ Exiting method - +MISSING_REQUESTID=\ + ECOMP-MISSING_REQUESTID-5404|\ + from {0}|\ + No resolution needed|\ + missing request id diff --git a/operation-utils/src/main/resources/GenericMessages.yaml b/operation-utils/src/main/resources/GenericMessages.yaml index df592e2..71624d6 100644 --- a/operation-utils/src/main/resources/GenericMessages.yaml +++ b/operation-utils/src/main/resources/GenericMessages.yaml @@ -1,36 +1,65 @@ -GENERAL_ERROR: - errorCode: ECOMP-GENERAL-ERROR-5403 - messageFormat: '{0}' - resolution: Please check other logs for more detailed info - description: General error -GENERAL_INFO: - errorCode: ECOMP-GENERAL-INFO-5401 - messageFormat: '{0}' - resolution: Please check other logs for more detailed info - description: General info -GENERAL_WARNING: - errorCode: ECOMP-GENERAL-WARNING-5402 - messageFormat: '{0}' - resolution: Please check other logs for more detailed info - description: General warning -METRICS_END: - errorCode: ECOMP-GENERAL-5404 - messageFormat: Exiting method - resolution: No resolution needed - description: Exiting method -AUDIT_END: - errorCode: ECOMP-GENERAL-5404 - messageFormat: Exiting method - resolution: No resolution needed - description: Exiting method -AUDIT_BEGIN: - errorCode: ECOMP-GENERAL-5403 - messageFormat: Entering method - resolution: No resolution needed - description: Entering method -METRICS_BEGIN: - errorCode: ECOMP-GENERAL-5403 - messageFormat: Entering method - resolution: No resolution needed - description: Entering method +package-name: org.openecomp.logger +java-root: src/main/java-gen +resources-root: src/main/resources-gen +messages: + ECOMP-GENERAL-EXCEPTION: + errorCode: 5404W + messageFormat: "{0}" + resolution: Please check other logs for more detailed info + description: General exception + ECOMP-GENERAL-ERROR: + errorCode: 5403E + messageFormat: "{0}" + resolution: Please check other logs for more detailed info + description: General error + ECOMP-GENERAL-INFO: + errorCode: 5401I + messageFormat: "{0}" + resolution: Please check other logs for more detailed info + description: General info + ECOMP-GENERAL-WARNING: + errorCode: 5402W + messageFormat: "{0}" + resolution: Please check other logs for more detailed info + description: General warning + ECOMP-REMOTE-CALL-OK: + errorCode: 2000I + messageFormat: "" + resolution: No resolution needed + description: Remote Call Succeess + ECOMP-REQUEST-OK: + errorCode: 2000I + messageFormat: "" + resolution: No resolution needed + description: Request Success + ECOMP-REMOTE-CALL-ERROR: + errorCode: 4000W + messageFormat: "{0}" + resolution: No resolution needed + description: Remote Call Failed + ECOMP-REQUEST-ERROR: + errorCode: 4000I + messageFormat: "{0}" + resolution: No resolution needed + description: Request Failed + ECOMP-MISSING-REQUESTID: + errorCode: 3401W + messageFormat: Missing request id from {0} + resolution: Need to get north bound entity to provide request ID per ECOMP logging requirements + description: Got a north bound request that was missing a request ID. + ECOMP-LOGGER-NON-EMPTY-STACK: + errorCode: 4401W + messageFormat: "" + resolution: Development bug. + description: Component recorded an Audit End with an non empty stack + ECOMP-LOGGER-POP-ON-EMPTY-STACK: + errorCode: 4402W + messageFormat: "" + resolution: Development bug. + description: Component performed a Pop on empty stack + ECOMP-LOGGER-TOP-ON-EMPTY-STACK: + errorCode: 4403W + messageFormat: "" + resolution: Development bug. + description: Component performed a Top on empty stack
\ No newline at end of file diff --git a/operation-utils/src/main/resources/logback.xml b/operation-utils/src/main/resources/logback.xml new file mode 100644 index 0000000..5dde533 --- /dev/null +++ b/operation-utils/src/main/resources/logback.xml @@ -0,0 +1,351 @@ +<configuration scan="true" scanPeriod="3 seconds"> + <!--<jmxConfigurator /> --> + <!-- directory path for all other type logs --> + <property name="logDir" value="logs" /> + + <!-- directory path for debugging type logs --> + <property name="debugDir" value="debug-logs" /> + + <!-- specify the component name --> + <property name="componentName" value="EELF"></property> + + <!-- log file names --> + <property name="generalLogName" value="application" /> + <property name="securityLogName" value="security" /> + <property name="performanceLogName" value="performance" /> + <property name="serverLogName" value="server" /> + <property name="policyLogName" value="policy" /> + <property name="errorLogName" value="error" /> + <property name="metricsLogName" value="metrics" /> + <property name="auditLogName" value="audit" /> + <property name="debugLogName" value="debug" /> + + <property name="defaultPattern" value="%date{ISO8601,UTC}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{VirtualServerName}|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}|%X{Timer}| %msg%n" /> + + <property name="auditLoggerPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{VirtualServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}|%X{Unused}|%X{ProcessKey}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}| %msg%n" /> + <property name="metricsLoggerPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{VirtualServerName}|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}|%X{Unused}|%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}| %msg%n" /> + <property name="errorLoggerPattern" value="%date{ISO8601,UTC}|%X{RequestId}|%thread|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%.-5level|%X{ErrorCode}|%X{ErrorDescription}| %msg%n" /> + <property name="debugLoggerPattern" value="%date{ISO8601,UTC}|%X{RequestId}| %msg%n" /> + + <property name="logDirectory" value="${logDir}/${componentName}" /> + <property name="debugLogDirectory" value="${debugDir}/${componentName}" /> + + + <!-- Example evaluator filter applied against console appender --> + <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> + <encoder> + <pattern>${defaultPattern}</pattern> + </encoder> + </appender> + + <!-- ============================================================================ --> + <!-- EELF Appenders --> + <!-- ============================================================================ --> + + <!-- The EELFAppender is used to record events to the general application + log --> + + + <appender name="EELF" + class="ch.qos.logback.core.rolling.RollingFileAppender"> + <file>${logDirectory}/${generalLogName}.log</file> + <rollingPolicy + class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy"> + <fileNamePattern>${logDirectory}/${generalLogName}.%i.log.zip + </fileNamePattern> + <minIndex>1</minIndex> + <maxIndex>20</maxIndex> + </rollingPolicy> + <triggeringPolicy + class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> + <maxFileSize>2500KB</maxFileSize> + </triggeringPolicy> + <encoder> + <pattern>${defaultPattern}</pattern> + </encoder> + </appender> + + <appender name="asyncEELF" class="ch.qos.logback.classic.AsyncAppender"> + <queueSize>256</queueSize> + <appender-ref ref="EELF" /> + </appender> + + <!-- EELF Security Appender. This appender is used to record security events + to the security log file. Security events are separate from other loggers + in EELF so that security log records can be captured and managed in a secure + way separate from the other logs. This appender is set to never discard any + events. --> + <appender name="EELFSecurity" + class="ch.qos.logback.core.rolling.RollingFileAppender"> + <file>${logDirectory}/${securityLogName}.log</file> + <rollingPolicy + class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy"> + <fileNamePattern>${logDirectory}/${securityLogName}.%i.log.zip + </fileNamePattern> + <minIndex>1</minIndex> + <maxIndex>20</maxIndex> + </rollingPolicy> + <triggeringPolicy + class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> + <maxFileSize>2500KB</maxFileSize> + </triggeringPolicy> + <encoder> + <pattern>${defaultPattern}</pattern> + </encoder> + </appender> + + <appender name="asyncEELFSecurity" class="ch.qos.logback.classic.AsyncAppender"> + <queueSize>256</queueSize> + <discardingThreshold>0</discardingThreshold> + <appender-ref ref="EELFSecurity" /> + </appender> + + <!-- EELF Performance Appender. This appender is used to record performance + records. --> + <appender name="EELFPerformance" + class="ch.qos.logback.core.rolling.RollingFileAppender"> + <file>${logDirectory}/${performanceLogName}.log</file> + <rollingPolicy + class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy"> + <fileNamePattern>${logDirectory}/${performanceLogName}.%i.log.zip + </fileNamePattern> + <minIndex>1</minIndex> + <maxIndex>20</maxIndex> + </rollingPolicy> + <triggeringPolicy + class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> + <maxFileSize>2500KB</maxFileSize> + </triggeringPolicy> + <encoder> + <pattern>${defaultPattern}</pattern> + </encoder> + </appender> + <appender name="asyncEELFPerformance" class="ch.qos.logback.classic.AsyncAppender"> + <queueSize>256</queueSize> + <appender-ref ref="EELFPerformance" /> + </appender> + + <!-- EELF Server Appender. This appender is used to record Server related + logging events. The Server logger and appender are specializations of the + EELF application root logger and appender. This can be used to segregate Server + events from other components, or it can be eliminated to record these events + as part of the application root log. --> + <appender name="EELFServer" + class="ch.qos.logback.core.rolling.RollingFileAppender"> + <file>${logDirectory}/${serverLogName}.log</file> + <rollingPolicy + class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy"> + <fileNamePattern>${logDirectory}/${serverLogName}.%i.log.zip + </fileNamePattern> + <minIndex>1</minIndex> + <maxIndex>20</maxIndex> + </rollingPolicy> + <triggeringPolicy + class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> + <maxFileSize>2500KB</maxFileSize> + </triggeringPolicy> + <encoder> + <pattern>${defaultPattern}</pattern> + </encoder> + </appender> + <appender name="asyncEELFServer" class="ch.qos.logback.classic.AsyncAppender"> + <queueSize>256</queueSize> + <appender-ref ref="EELFServer" /> + </appender> + + + <!-- EELF Policy Appender. This appender is used to record Policy engine + related logging events. The Policy logger and appender are specializations + of the EELF application root logger and appender. This can be used to segregate + Policy engine events from other components, or it can be eliminated to record + these events as part of the application root log. --> + <appender name="EELFPolicy" + class="ch.qos.logback.core.rolling.RollingFileAppender"> + <file>${logDirectory}/${policyLogName}.log</file> + <rollingPolicy + class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy"> + <fileNamePattern>${logDirectory}/${policyLogName}.%i.log.zip + </fileNamePattern> + <minIndex>1</minIndex> + <maxIndex>20</maxIndex> + </rollingPolicy> + <triggeringPolicy + class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> + <maxFileSize>2500KB</maxFileSize> + </triggeringPolicy> + <encoder> + <pattern>${defaultPattern}</pattern> + </encoder> + </appender> + <appender name="asyncEELFPolicy" class="ch.qos.logback.classic.AsyncAppender"> + <queueSize>256</queueSize> + <appender-ref ref="EELFPolicy" /> + </appender> + + + <!-- EELF Audit Appender. This appender is used to record audit engine + related logging events. The audit logger and appender are specializations + of the EELF application root logger and appender. This can be used to segregate + Policy engine events from other components, or it can be eliminated to record + these events as part of the application root log. --> + + <appender name="EELFAudit" + class="ch.qos.logback.core.rolling.RollingFileAppender"> + <file>${logDirectory}/${auditLogName}.log</file> + <rollingPolicy + class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy"> + <fileNamePattern>${logDirectory}/${auditLogName}.%i.log.zip + </fileNamePattern> + <minIndex>1</minIndex> + <maxIndex>20</maxIndex> + </rollingPolicy> + <triggeringPolicy + class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> + <maxFileSize>2500KB</maxFileSize> + </triggeringPolicy> + <encoder> + <pattern>${auditLoggerPattern}</pattern> + </encoder> + </appender> + <appender name="asyncEELFAudit" class="ch.qos.logback.classic.AsyncAppender"> + <queueSize>256</queueSize> + <appender-ref ref="EELFAudit" /> + </appender> + + <appender name="EELFMetrics" + class="ch.qos.logback.core.rolling.RollingFileAppender"> + <file>${logDirectory}/${metricsLogName}.log</file> + <rollingPolicy + class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy"> + <fileNamePattern>${logDirectory}/${metricsLogName}.%i.log.zip + </fileNamePattern> + <minIndex>1</minIndex> + <maxIndex>20</maxIndex> + </rollingPolicy> + <triggeringPolicy + class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> + <maxFileSize>2500KB</maxFileSize> + </triggeringPolicy> + <encoder> + <!-- <pattern>"%d{HH:mm:ss.SSS} [%thread] %-5level %logger{1024} - + %msg%n"</pattern> --> + <pattern>${metricsLoggerPattern}</pattern> + </encoder> + </appender> + + + <appender name="asyncEELFMetrics" class="ch.qos.logback.classic.AsyncAppender"> + <queueSize>256</queueSize> + <appender-ref ref="EELFMetrics"/> + </appender> + + <appender name="EELFError" + class="ch.qos.logback.core.rolling.RollingFileAppender"> + <file>${logDirectory}/${errorLogName}.log</file> + <rollingPolicy + class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy"> + <fileNamePattern>${logDirectory}/${errorLogName}.%i.log.zip + </fileNamePattern> + <minIndex>1</minIndex> + <maxIndex>20</maxIndex> + </rollingPolicy> + <triggeringPolicy + class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> + <maxFileSize>2500KB</maxFileSize> + </triggeringPolicy> + <encoder> + <pattern>${errorLoggerPattern}</pattern> + </encoder> + </appender> + + <appender name="asyncEELFError" class="ch.qos.logback.classic.AsyncAppender"> + <queueSize>256</queueSize> + <appender-ref ref="EELFError"/> + </appender> + + <appender name="EELFDebug" + class="ch.qos.logback.core.rolling.RollingFileAppender"> + <file>${debugLogDirectory}/${debugLogName}.log</file> + <rollingPolicy + class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy"> + <fileNamePattern>${debugLogDirectory}/${debugLogName}.%i.log.zip + </fileNamePattern> + <minIndex>1</minIndex> + <maxIndex>20</maxIndex> + </rollingPolicy> + <triggeringPolicy + class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> + <maxFileSize>2500KB</maxFileSize> + </triggeringPolicy> + <encoder> + <pattern>${debugLoggerPattern}</pattern> + </encoder> + </appender> + + <appender name="asyncEELFDebug" class="ch.qos.logback.classic.AsyncAppender"> + <queueSize>256</queueSize> + <appender-ref ref="EELFDebug" /> + <includeCallerData>true</includeCallerData> + </appender> + + + <!-- ============================================================================ --> + <!-- EELF loggers --> + <!-- ============================================================================ --> + <logger name="com.att.eelf" level="info" additivity="false"> + <appender-ref ref="asyncEELF" /> + </logger> + <logger name="com.att.eelf.security" level="info" additivity="false"> + <appender-ref ref="asyncEELFSecurity" /> + </logger> + <logger name="com.att.eelf.perf" level="info" additivity="false"> + <appender-ref ref="asyncEELFPerformance" /> + </logger> + <logger name="com.att.eelf.server" level="info" additivity="false"> + <appender-ref ref="asyncEELFServer" /> + </logger> + <logger name="com.att.eelf.policy" level="info" additivity="false"> + <appender-ref ref="asyncEELFPolicy" /> + </logger> + + <logger name="com.att.eelf.audit" level="info" additivity="false"> + <appender-ref ref="asyncEELFAudit" /> + </logger> + + <logger name="com.att.eelf.metrics" level="info" additivity="false"> + <appender-ref ref="asyncEELFMetrics" /> + </logger> + + + <logger name="com.att.eelf.error" level="info" additivity="false"> + <appender-ref ref="asyncEELFError" /> + </logger> + + <logger name="com.att.eelf.debug" level="debug" additivity="false"> + <appender-ref ref="asyncEELFDebug" /> + </logger> + + + <logger name="com.att.ecomp.audit" level="info" additivity="false"> + <appender-ref ref="asyncEELFAudit" /> + </logger> + + <logger name="com.att.ecomp.metrics" level="info" additivity="false"> + <appender-ref ref="asyncEELFMetrics" /> + </logger> + + + <logger name="com.att.ecomp.error" level="info" additivity="false"> + <appender-ref ref="asyncEELFError" /> + </logger> + + + <logger name="com.att.ecomp.debug" level="debug" additivity="false"> + <appender-ref ref="asyncEELFDebug" /> + </logger> + + <root level="INFO"> + <appender-ref ref="asyncEELF" /> + </root> + +</configuration>
\ No newline at end of file diff --git a/operation-utils/src/main/resources/messageEnum.java_template b/operation-utils/src/main/resources/messageEnum.java_template index e0b3c12..d6c7884 100644 --- a/operation-utils/src/main/resources/messageEnum.java_template +++ b/operation-utils/src/main/resources/messageEnum.java_template @@ -9,10 +9,10 @@ public enum ${name}MessageEnum implements EcompMessageEnum { def last messages.each { n, v -> last = n } messages.each { n, v -> %> - $n${n==last ? ";" : ","}\ + ${n.replace('-','_')}${n==last ? ";" : ","}\ <% } %> static { - EELFResourceManager.loadMessageBundle("${packageName}.$name"); + EELFResourceManager.loadMessageBundle("${resourcePath}/$name"); } } diff --git a/operation-utils/src/main/resources/operationEnum.java_template b/operation-utils/src/main/resources/operationEnum.java_template index 9ec9d3d..4bf3ec0 100644 --- a/operation-utils/src/main/resources/operationEnum.java_template +++ b/operation-utils/src/main/resources/operationEnum.java_template @@ -8,6 +8,19 @@ public enum ${name}OperationEnum implements EcompOperationEnum { def last operations.each { n, v -> last = n } operations.each { n, v -> %> - $n${n==last ? ";" : ","}\ -<% } %> + ${n.replaceAll('[-&@#:]','_')}("$n")${n==last ? "" : ","}\ +<% } %> ; + + + private String n; + + private ${name}OperationEnum(String n) { + this.n = n; + } + + @Override + public String toString() { + return n; + } + } diff --git a/operation-utils/src/main/resources/properties_template b/operation-utils/src/main/resources/properties_template index 76b2b48..fa25ca5 100644 --- a/operation-utils/src/main/resources/properties_template +++ b/operation-utils/src/main/resources/properties_template @@ -1,8 +1,8 @@ <% messages.each { n, v -> %> -$n=\\ - $v.errorCode|\\ +${n.replace('-','_')}=\\ + $n-$v.errorCode|\\ $v.messageFormat|\\ $v.resolution|\\ $v.description |