diff options
Diffstat (limited to 'common-app-logging/src')
33 files changed, 4578 insertions, 0 deletions
diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/api/ILogFieldsHandler.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/api/ILogFieldsHandler.java new file mode 100644 index 0000000000..7d1783314f --- /dev/null +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/api/ILogFieldsHandler.java @@ -0,0 +1,181 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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.sdc.common.log.api; + +import org.openecomp.sdc.common.log.enums.Severity; + +public interface ILogFieldsHandler { + void startAuditTimer(); + + void startMetricTimer(); + + void stopAuditTimer(); + + void stopMetricTimer(); + + void setClassName(String className); + + void setServerFQDN(String serverFQDN); + + void setServerIPAddress(String serverIPAddress); + + // intended for setting this parameter in a given thread + void setServerFQDNInternally(); + + // intended for setting this parameter in a given thread + void setServerIPAddressInternally(); + + void setInstanceUUID(String instanceUUID); + + void setProcessKey(String processKey); + + void setAlertSeverity(Severity alertSeverity); + + void setOptCustomField1(String customField1); + + void setOutgoingInvocationId(String outgoingInvocationId); + + void setKeyRequestId(String keyRequestId); + + void setRemoteHost(String remoteHost); + + void setServiceName(String serviceName); + + void setStatusCode(String statusCode); + + void setPartnerName(String partnerName); + + void setResponseCode(int responseCode); + + void setResponseDesc(String responseDesc); + + void setServiceInstanceId(String serviceInstanceId); + + void setTargetEntity(String targetEntity); + + void setTargetServiceName(String targetServiceName); + + void setTargetVirtualEntity(String targetVirtualEntity); + + void setErrorCode(int errorCode); + + void setErrorCategory(String errorCategory); + + String getErrorCode(); + + String getServiceName(); + + String getTargetEntity(); + + String getTargetServiceName(); + + String getErrorCategory(); + + void clear(); + + boolean isMDCParamEmpty(String mdcKeyName); + + String getFqdn(); + + String getHostAddress(); + + String getKeyRequestId(); + + void removeStatusCode(); + + void removePartnerName(); + + void removeResponseCode(); + + void removeResponseDesc(); + + void removeServiceInstanceId(); + + void removeTargetEntity(); + + void removeTargetServiceName(); + + void removeTargetVirtualEntity(); + + void removeErrorCode(); + + void removeErrorCategory(); + + void removeErrorDescription(); + + void setAuditMessage(String message); + + String getAuditMessage(); + + //service supportability [US 496441] + + String getSupportablityAction(); + + String getSupportablityCsarUUID(); + + String getSupportablityCsarVersion(); + + String getSupportablityComponentName(); + + String getSupportablityComponentUUID(); + + String getSupportablityComponentVersion(); + + String getSupportablityStatusCode(); + + void setSupportablityAction(String action); + + void setSupportablityCsarUUID(String uuid); + + void setSupportablityCsarVersion(String version); + + void setSupportablityComponentName(String name); + + void setSupportablityComponentUUID(String UUID); + + void setSupportablityComponentVersion(String version); + + void setSupportablityStatusCode(String statusCode); + + void removeSupportablityAction(); + + void removeSupportablityComponentName(); + + void removeSupportablityComponentUUID(); + + void removeSupportablityComponentVersion(); + + void removeSupportablityCsarUUID(); + + void removeSupportablityCsarVersion(); + + void removeSupportablityStatusCode(); + + String getPartnerName(); + + String getRemoteHost(); + + String getServerIpAddress(); + + void setKeyInvocationId(String invocationId); + + CharSequence getKeyInvocationId(); +} diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/api/ILogger.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/api/ILogger.java new file mode 100644 index 0000000000..866498cefd --- /dev/null +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/api/ILogger.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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.sdc.common.log.api; + +import org.openecomp.sdc.common.log.enums.LogLevel; +import org.slf4j.Marker; + +import java.util.List; + +public interface ILogger { + void log(LogLevel logLevel, String message); + void log(Marker marker, LogLevel logLevel, String message); + void log(LogLevel logLevel, String message, Object... params); + void log(Marker marker, LogLevel logLevel, String message, Object... params); + void log(LogLevel logLevel, String message, Throwable throwable); + List<String> getMandatoryFields(); + ILogger clear(); + ILogger startTimer(); + ILogger setKeyRequestId(String keyRequestId); + + ILogger setKeyInvocationId(String keyInvocationId); +} diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/api/LogConfigurationConstants.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/api/LogConfigurationConstants.java new file mode 100644 index 0000000000..d1d5a3af7c --- /dev/null +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/api/LogConfigurationConstants.java @@ -0,0 +1,49 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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.sdc.common.log.api; + +public final class LogConfigurationConstants { + + public static final String MDC_SERVICE_INSTANCE_ID = "ServiceInstanceID"; + public static final String MDC_SERVER_IP_ADDRESS = "ServerIPAddress"; + public static final String MDC_REMOTE_HOST = "RemoteHost"; + public static final String MDC_AUDIT_MESSAGE = "AuditMessage"; + public static final String MDC_END_TIMESTAMP = "EndTimestamp"; + public static final String MDC_ELAPSED_TIME = "ElapsedTime"; + public static final String MDC_PROCESS_KEY = "ProcessKey"; + public static final String MDC_TARGET_VIRTUAL_ENTITY = "TargetVirtualEntity"; + public static final String MDC_ERROR_CATEGORY = "ErrorCategory"; + public static final String MDC_ERROR_CODE = "ErrorCode"; + public static final String MDC_ERROR_DESC = "ErrorDescription"; + public static final String MDC_CLASS_NAME = "ClassName"; + public static final String MDC_OPT_FIELD1 = "CustomField1"; + public static final String MDC_OPT_FIELD2 = "CustomField2"; + public static final String MDC_OPT_FIELD3 = "CustomField3"; + public static final String MDC_OPT_FIELD4 = "CustomField4"; + public static final String MDC_OUTGOING_INVOCATION_ID = "OutgoingInvocationId"; + public static final String MDC_SUPPORTABLITY_ACTION = "SupportablityAction"; + public static final String MDC_SUPPORTABLITY_CSAR_UUID = "SupportablityCsarUUID"; + public static final String MDC_SUPPORTABLITY_CSAR_VERSION = "SupportablityCsarVersion"; + public static final String MDC_SUPPORTABLITY_COMPONENT_NAME = "SupportablityComponentName"; + public static final String MDC_SUPPORTABLITY_COMPONENT_UUID = "SupportablityComponentUUID"; + public static final String MDC_SUPPORTABLITY_COMPONENT_VERSION = "SupportablityComponentVersion"; + public static final String MDC_SUPPORTABLITY_STATUS_CODE = "SupportablityStatus"; +}
\ No newline at end of file diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/ErrorLogOptionalData.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/ErrorLogOptionalData.java new file mode 100644 index 0000000000..d5279b1101 --- /dev/null +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/ErrorLogOptionalData.java @@ -0,0 +1,60 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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.sdc.common.log.elements; + +public class ErrorLogOptionalData { + private String targetEntity; + private String targetServiceName; + + String getTargetEntity() { + return targetEntity; + } + + String getTargetServiceName() { + return targetServiceName; + } + + public static Builder newBuilder() { + return new Builder(); + } + + public static class Builder { + private final ErrorLogOptionalData instance; + + private Builder() { + instance = new ErrorLogOptionalData(); + } + + public Builder targetEntity(String targetEntity) { + instance.targetEntity = targetEntity; + return this; + } + + public Builder targetServiceName(String targetServiceName) { + instance.targetServiceName = targetServiceName; + return this; + } + + public ErrorLogOptionalData build() { + return instance; + } + } +} diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LogFieldsMdcHandler.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LogFieldsMdcHandler.java new file mode 100644 index 0000000000..361c255009 --- /dev/null +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LogFieldsMdcHandler.java @@ -0,0 +1,504 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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.sdc.common.log.elements; + +import org.apache.commons.lang3.StringUtils; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.openecomp.sdc.common.log.api.LogConfigurationConstants; +import org.openecomp.sdc.common.log.enums.ConstantsLogging; +import org.openecomp.sdc.common.log.api.ILogFieldsHandler; +import org.openecomp.sdc.common.log.enums.Severity; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import javax.servlet.http.HttpServletRequest; +import java.net.InetAddress; +import java.time.Duration; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; + +public class LogFieldsMdcHandler implements ILogFieldsHandler { + + private static LogFieldsMdcHandler instanceMdcWrapper = new LogFieldsMdcHandler(); + + public static LogFieldsMdcHandler getInstance() { + return instanceMdcWrapper; + } + + private final static String dateFormatPattern = "yyyy-MM-dd HH:mm:ss.SSSz"; + private final DateTimeFormatter dateTimeFormatter = DateTimeFormatter + .ofPattern(dateFormatPattern); + protected static Logger log = LoggerFactory.getLogger(LogFieldsMdcHandler.class.getName()); + protected static String hostAddress; + private static String fqdn; + + static { + try { + hostAddress = InetAddress.getLocalHost().getHostAddress(); + fqdn = InetAddress.getByName(hostAddress).getCanonicalHostName(); + } catch (Exception ex) { + log.error("failed to get machine parameters", ex); + } + } + + @Override + public void startAuditTimer() { + if (StringUtils.isEmpty(MDC.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP))) { + MDC.put(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP, generatedTimeNow()); + } + } + + @Override + public void startMetricTimer() { + if (StringUtils.isEmpty(MDC.get(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP))) { + MDC.put(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP, generatedTimeNow()); + } + } + + @Override + public void stopAuditTimer() { + //set start time if it is not set yet + startAuditTimer(); + MDC.put(LogConfigurationConstants.MDC_END_TIMESTAMP, generatedTimeNow()); + setElapsedTime(MDC.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP)); + } + + @Override + public void stopMetricTimer() { + //set start time if it is not set yet + startMetricTimer(); + MDC.put(LogConfigurationConstants.MDC_END_TIMESTAMP, generatedTimeNow()); + setElapsedTime(MDC.get(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP)); + } + + @Override + public void setClassName(String className) { + MDC.put(LogConfigurationConstants.MDC_CLASS_NAME, className); + } + + @Override + public void setServerFQDN(String serverFQDN) { + MDC.put(ONAPLogConstants.MDCs.SERVER_FQDN, serverFQDN); + } + + @Override + public void setServerIPAddress(String serverIPAddress) { + MDC.put(LogConfigurationConstants.MDC_SERVER_IP_ADDRESS, serverIPAddress); + } + + @Override + public void setServerFQDNInternally() { + setServerFQDN(fqdn); + } + + @Override + public void setServerIPAddressInternally() { + setServerIPAddress(hostAddress); + } + + @Override + public void setInstanceUUID(String instanceUUID) { + MDC.put(ONAPLogConstants.MDCs.INSTANCE_UUID, instanceUUID); + } + + @Override + public void setProcessKey(String processKey) { + MDC.put(LogConfigurationConstants.MDC_PROCESS_KEY, processKey); + } + + @Override + public void setAlertSeverity(Severity alertSeverity) { + MDC.put(ONAPLogConstants.MDCs.RESPONSE_SEVERITY, String.valueOf(alertSeverity.getSeverityType())); + } + + @Override + public void setOptCustomField1(String customField1) { + MDC.put(LogConfigurationConstants.MDC_OPT_FIELD1, customField1); + } + + @Override + public void setOutgoingInvocationId(String outgoingInvocationId) { + MDC.put(LogConfigurationConstants.MDC_OUTGOING_INVOCATION_ID, outgoingInvocationId); + } + + @Override + public void setKeyRequestId(String keyRequestId) { + MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, + keyRequestId); // eg. servletRequest.getSession().getId() + } + + @Override + public void setKeyInvocationId(String invocationId ) { + MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, + invocationId); + } + + @Override + public void setRemoteHost(String remoteHost) { + MDC.put(LogConfigurationConstants.MDC_REMOTE_HOST, remoteHost); + } + + @Override + public void setServiceName(String serviceName) { + MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, serviceName); + } + + @Override + public void setStatusCode(String statusCode) { + MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, statusCode); + } + + @Override + public void setPartnerName(String partnerName) { + MDC.put(ONAPLogConstants.MDCs.PARTNER_NAME, partnerName); + } + + @Override + public void setResponseCode(int responseCode) { + MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE, Integer.toString(responseCode)); + } + + @Override + public void setResponseDesc(String responseDesc) { + MDC.put(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION, responseDesc); + } + + @Override + public void setServiceInstanceId(String serviceInstanceId) { + MDC.put(LogConfigurationConstants.MDC_SERVICE_INSTANCE_ID, serviceInstanceId); + } + + @Override + public void setTargetEntity(String targetEntity) { + MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY, targetEntity); + } + + @Override + public void setTargetServiceName(String targetServiceName) { + MDC.put(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME, targetServiceName); + } + + @Override + public void setTargetVirtualEntity(String targetVirtualEntity) { + MDC.put(LogConfigurationConstants.MDC_TARGET_VIRTUAL_ENTITY, targetVirtualEntity); + } + + @Override + public void setErrorCode(int errorCode) { + MDC.put(LogConfigurationConstants.MDC_ERROR_CODE, Integer.toString(errorCode)); + } + + @Override + public void setErrorCategory(String errorCategory) { + MDC.put(LogConfigurationConstants.MDC_ERROR_CATEGORY, errorCategory); + } + + @Override + public String getErrorCode() { + return MDC.get(LogConfigurationConstants.MDC_ERROR_CODE); + } + + @Override + public String getServiceName() { + return MDC.get(ONAPLogConstants.MDCs.SERVICE_NAME); + } + + @Override + public String getErrorCategory() { + return MDC.get(LogConfigurationConstants.MDC_ERROR_CATEGORY); + } + + @Override + public void clear() { + MDC.clear(); + } + + @Override + public boolean isMDCParamEmpty(String mdcKeyName) { + return StringUtils.isEmpty(MDC.get(mdcKeyName)); + } + + @Override + public String getFqdn() { + return fqdn; + } + + @Override + public String getHostAddress() { + return hostAddress; + } + + @Override + public String getKeyRequestId() { + return MDC.get(ONAPLogConstants.MDCs.REQUEST_ID); + } + + @Override + public String getTargetEntity() { + return MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY); + } + + @Override + public String getTargetServiceName() { + return MDC.get(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME); + } + + @Override + public void removeStatusCode() { + MDC.remove(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE); + } + + @Override + public void removePartnerName() { + MDC.remove(ONAPLogConstants.MDCs.PARTNER_NAME); + } + + @Override + public void removeResponseCode() { + MDC.remove(ONAPLogConstants.MDCs.RESPONSE_CODE); + } + + @Override + public void removeResponseDesc() { + MDC.remove(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION); + } + + @Override + public void removeServiceInstanceId() { + MDC.remove(LogConfigurationConstants.MDC_SERVICE_INSTANCE_ID); + } + + @Override + public void removeTargetEntity() { + MDC.remove(ONAPLogConstants.MDCs.TARGET_ENTITY); + } + + @Override + public void removeTargetServiceName() { + MDC.remove(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME); + } + + @Override + public void removeTargetVirtualEntity() { + MDC.remove(LogConfigurationConstants.MDC_TARGET_VIRTUAL_ENTITY); + } + + @Override + public void removeErrorCode() { + MDC.remove(LogConfigurationConstants.MDC_ERROR_CODE); + } + + @Override + public void removeErrorCategory() { + MDC.remove(LogConfigurationConstants.MDC_ERROR_CATEGORY); + } + + @Override + public void removeErrorDescription() { + MDC.remove(LogConfigurationConstants.MDC_ERROR_DESC); + } + + @Override + public void setAuditMessage(String message) { + MDC.put(LogConfigurationConstants.MDC_AUDIT_MESSAGE, message); + } + + @Override + public String getAuditMessage() { + return MDC.get(LogConfigurationConstants.MDC_AUDIT_MESSAGE); + } + + @Override + public String getSupportablityStatusCode() { + return MDC.get(LogConfigurationConstants.MDC_SUPPORTABLITY_STATUS_CODE); + } + + @Override + public String getSupportablityAction() { + return MDC.get(LogConfigurationConstants.MDC_SUPPORTABLITY_ACTION); + + } + + + @Override + public String getRemoteHost() { + return MDC.get(LogConfigurationConstants.MDC_REMOTE_HOST); + } + + @Override + public String getServerIpAddress() { + return MDC.get(LogConfigurationConstants.MDC_SERVER_IP_ADDRESS); + } + + @Override + public String getSupportablityCsarUUID() { + return MDC.get(LogConfigurationConstants.MDC_SUPPORTABLITY_CSAR_UUID); + } + + @Override + public String getSupportablityCsarVersion() { + return MDC.get(LogConfigurationConstants.MDC_SUPPORTABLITY_CSAR_VERSION); + + } + + @Override + public String getSupportablityComponentName() { + return MDC.get(LogConfigurationConstants.MDC_SUPPORTABLITY_COMPONENT_NAME); + } + + @Override + public String getSupportablityComponentUUID() { + return MDC.get(LogConfigurationConstants.MDC_SUPPORTABLITY_COMPONENT_UUID); + + } + + @Override + public String getSupportablityComponentVersion() { + return MDC.get(LogConfigurationConstants.MDC_SUPPORTABLITY_COMPONENT_VERSION); + } + + @Override + public String getKeyInvocationId() { + return MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID); + } + + @Override + public void setSupportablityStatusCode(String statusCode) { + MDC.put(LogConfigurationConstants.MDC_SUPPORTABLITY_STATUS_CODE, statusCode); + } + + @Override + public void setSupportablityAction(String action) { + MDC.put(LogConfigurationConstants.MDC_SUPPORTABLITY_ACTION, action); + } + + @Override + public void setSupportablityCsarUUID(String uuid) { + MDC.put(LogConfigurationConstants.MDC_SUPPORTABLITY_CSAR_UUID, uuid); + } + + @Override + public void setSupportablityCsarVersion(String version) { + MDC.put(LogConfigurationConstants.MDC_SUPPORTABLITY_CSAR_VERSION, version); + } + + @Override + public void setSupportablityComponentName(String name) { + MDC.put(LogConfigurationConstants.MDC_SUPPORTABLITY_COMPONENT_NAME, name); + } + + @Override + public void setSupportablityComponentUUID(String uuid) { + MDC.put(LogConfigurationConstants.MDC_SUPPORTABLITY_COMPONENT_UUID, uuid); + } + + @Override + public void setSupportablityComponentVersion(String version) { + MDC.put(LogConfigurationConstants.MDC_SUPPORTABLITY_COMPONENT_VERSION, version); + } + + @Override + public void removeSupportablityAction() { + MDC.remove(LogConfigurationConstants.MDC_SUPPORTABLITY_ACTION); + } + + @Override + public void removeSupportablityComponentName() { + MDC.remove(LogConfigurationConstants.MDC_SUPPORTABLITY_COMPONENT_NAME); + } + + @Override + public void removeSupportablityComponentUUID() { + MDC.remove(LogConfigurationConstants.MDC_SUPPORTABLITY_COMPONENT_UUID); + } + + @Override + public void removeSupportablityComponentVersion() { + MDC.remove(LogConfigurationConstants.MDC_SUPPORTABLITY_COMPONENT_VERSION); + } + + @Override + public void removeSupportablityCsarUUID() { + MDC.remove(LogConfigurationConstants.MDC_SUPPORTABLITY_CSAR_UUID); + } + + @Override + public void removeSupportablityCsarVersion() { + MDC.remove(LogConfigurationConstants.MDC_SUPPORTABLITY_CSAR_VERSION); + } + + @Override + public void removeSupportablityStatusCode() { + MDC.remove(LogConfigurationConstants.MDC_SUPPORTABLITY_STATUS_CODE); + } + + @Override + public String getPartnerName() { + return MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME); + } + + private void setElapsedTime(String beginTimestamp) { + try { + final LocalDateTime startTime = LocalDateTime.parse(beginTimestamp, dateTimeFormatter); + final LocalDateTime endTime = LocalDateTime + .parse(MDC.get(LogConfigurationConstants.MDC_END_TIMESTAMP), dateTimeFormatter); + final Duration timeDifference = Duration.between(startTime, endTime); + + MDC.put(LogConfigurationConstants.MDC_ELAPSED_TIME, String.valueOf(timeDifference.toMillis())); + + } catch (Exception ex) { + log.error("failed to calculate elapsed time", ex); + } + } + + private String generatedTimeNow() { + return dateTimeFormatter + .withZone(ZoneOffset.UTC) + .format(Instant.now()); + } + + public void collectRequestInfoForErrorAndDebugLogging(HttpServletRequest httpRequest) { + LogFieldsMdcHandler.getInstance().clear(); + String partnerName = LoggerBase.getPartnerName(httpRequest); + LogFieldsMdcHandler.getInstance().setPartnerName(partnerName); + + String serviceInstanceID = httpRequest.getHeader(ConstantsLogging.X_ECOMP_SERVICE_ID_HEADER); + LogFieldsMdcHandler.getInstance().setServiceInstanceId(serviceInstanceID); + + LogFieldsMdcHandler.getInstance().setRemoteHost(httpRequest.getRemoteHost()); + LogFieldsMdcHandler.getInstance().setServerIPAddress(httpRequest.getLocalAddr()); + + String requestId = LoggerBase.getRequestId(httpRequest); + LogFieldsMdcHandler.getInstance().setKeyRequestId(requestId); + + LogFieldsMdcHandler.getInstance().setServiceName(httpRequest.getRequestURI()); + } + + public void addInfoForErrorAndDebugLogging(String partnerName){ + LogFieldsMdcHandler.getInstance().clear(); + LogFieldsMdcHandler.getInstance().setPartnerName(partnerName); + + String requestId = LoggerBase.generateKeyRequestId(); + LogFieldsMdcHandler.getInstance().setKeyRequestId(requestId); + } +}
\ No newline at end of file diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerAudit.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerAudit.java new file mode 100644 index 0000000000..502b7a6871 --- /dev/null +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerAudit.java @@ -0,0 +1,173 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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.sdc.common.log.elements; + +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.openecomp.sdc.common.log.api.LogConfigurationConstants; +import org.openecomp.sdc.common.log.api.ILogFieldsHandler; +import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; +import org.openecomp.sdc.common.log.enums.Severity; +import org.slf4j.Logger; +import org.slf4j.MDC; +import org.slf4j.MarkerFactory; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +public class LoggerAudit extends LoggerBase { + private static List<String> mandatoryFields = new ArrayList<>(Arrays.asList( + ONAPLogConstants.MDCs.ENTRY_TIMESTAMP, + LogConfigurationConstants.MDC_END_TIMESTAMP, + ONAPLogConstants.MDCs.REQUEST_ID, + ONAPLogConstants.MDCs.SERVICE_NAME, + ONAPLogConstants.MDCs.PARTNER_NAME, + ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, + ONAPLogConstants.MDCs.RESPONSE_CODE, + LogConfigurationConstants.MDC_SERVICE_INSTANCE_ID, + ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION, + LogConfigurationConstants.MDC_ELAPSED_TIME, + LogConfigurationConstants.MDC_SERVER_IP_ADDRESS, + ONAPLogConstants.MDCs.SERVER_FQDN)); + + private static List<String> optionalFields = new ArrayList<>(Arrays.asList( + ONAPLogConstants.MDCs.INSTANCE_UUID, + ONAPLogConstants.MDCs.RESPONSE_SEVERITY, + LogConfigurationConstants.MDC_REMOTE_HOST, + LogConfigurationConstants.MDC_CLASS_NAME, + LogConfigurationConstants.MDC_PROCESS_KEY, + LogConfigurationConstants.MDC_OPT_FIELD1, + LogConfigurationConstants.MDC_OPT_FIELD2, + LogConfigurationConstants.MDC_OPT_FIELD3, + LogConfigurationConstants.MDC_OPT_FIELD4)); + + LoggerAudit(ILogFieldsHandler ecompMdcWrapper, Logger logger) { + //TODO Andrey, set default marker + super (ecompMdcWrapper, MarkerFactory.getMarker(ONAPLogConstants.Markers.ENTRY.getName()), logger); + //put the remote host and FQDN values from another thread if they are set + ecompMdcWrapper.setServerIPAddressInternally(); + ecompMdcWrapper.setServerFQDNInternally(); + } + + @Override + public LoggerAudit startTimer() { + ecompLogFieldsHandler.startAuditTimer(); + return this; + } + + public LoggerAudit stopTimer() { + ecompLogFieldsHandler.stopAuditTimer(); + return this; + } + + public LoggerAudit setInstanceUUID(String instanceUUID) { + ecompLogFieldsHandler.setInstanceUUID(instanceUUID); + return this; + } + + public LoggerAudit setOptClassName(String className) { + MDC.put(LogConfigurationConstants.MDC_CLASS_NAME, className); + return this; + } + + public LoggerAudit setOptProcessKey(String processKey) { + ecompLogFieldsHandler.setProcessKey(processKey); + return this; + } + + public LoggerAudit setOptAlertSeverity(Severity alertSeverity) { + ecompLogFieldsHandler.setAlertSeverity(alertSeverity); + return this; + } + + @Override + public LoggerAudit setKeyRequestId(String keyRequestId) { + return (LoggerAudit) super.setKeyRequestId(keyRequestId); + } + + @Override + public LoggerAudit setKeyInvocationId(String keyInvocationId) { + ecompLogFieldsHandler.setKeyInvocationId(keyInvocationId); + return this; + } + + public LoggerAudit setRemoteHost(String remoteHost) { + ecompLogFieldsHandler.setRemoteHost(remoteHost); + return this; + } + + public LoggerAudit setServiceName(String serviceName) { + ecompLogFieldsHandler.setServiceName(serviceName); + return this; + } + + public LoggerAudit setStatusCodeByResponseCode(String responseCode) { + String respStatus = Integer.parseInt(responseCode) / 100 == 2 ? ONAPLogConstants.ResponseStatus.COMPLETE.name() : ONAPLogConstants.ResponseStatus.ERROR.name(); + ecompLogFieldsHandler.setStatusCode(respStatus); + return this; + } + + public LoggerAudit setStatusCode(String statusCode) { + ecompLogFieldsHandler.setStatusCode(statusCode); + return this; + } + + + public LoggerAudit setPartnerName(String partnerName) { + ecompLogFieldsHandler.setPartnerName(partnerName); + return this; + } + + public LoggerAudit setResponseCode(EcompLoggerErrorCode responseCode) { + ecompLogFieldsHandler.setResponseCode(responseCode.getErrorCode()); + return this; + } + + public LoggerAudit setResponseDesc(String responseDesc) { + ecompLogFieldsHandler.setResponseDesc(responseDesc); + return this; + } + + public LoggerAudit setOptServiceInstanceId(String serviceInstanceId) { + ecompLogFieldsHandler.setServiceInstanceId(serviceInstanceId); + return this; + } + + public String getAuditMessage() { + return ecompLogFieldsHandler.getAuditMessage(); + } + + + @Override + public List<String> getMandatoryFields() { + return Collections.unmodifiableList(mandatoryFields); + } + + @Override + public LoggerAudit clear() { + super.clear(); + ecompLogFieldsHandler.setServerFQDNInternally(); + ecompLogFieldsHandler.setServerIPAddressInternally(); + return this; + } + +} diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerBase.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerBase.java new file mode 100644 index 0000000000..5b2bfad5b9 --- /dev/null +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerBase.java @@ -0,0 +1,224 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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.sdc.common.log.elements; + +import com.google.common.annotations.VisibleForTesting; +import org.apache.commons.lang3.StringUtils; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.openecomp.sdc.common.log.api.ILogFieldsHandler; +import org.openecomp.sdc.common.log.api.ILogger; +import org.openecomp.sdc.common.log.enums.ConstantsLogging; +import org.openecomp.sdc.common.log.enums.LogLevel; +import org.openecomp.sdc.common.log.enums.LogMarkers; +import org.openecomp.sdc.common.log.utils.LoggingThreadLocalsHolder; +import org.slf4j.Logger; +import org.slf4j.Marker; +import org.slf4j.MarkerFactory; + +import javax.servlet.http.HttpServletRequest; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; + +public abstract class LoggerBase implements ILogger { + private final Logger myLogger; + private final Marker myMarker; + protected final ILogFieldsHandler ecompLogFieldsHandler; + private final static String missingLogFieldsMsg = "mandatory parameters for ECOMP logging, missing fields: %s, original message: %s"; + + LoggerBase(ILogFieldsHandler ecompLogFieldsHandler, Marker marker, Logger logger) { + this.ecompLogFieldsHandler = ecompLogFieldsHandler; + this.myMarker = marker; + this.myLogger = logger; + setKeyRequestIdIfNotSetYet(); + } + + public static String generateKeyRequestId() { + return UUID.randomUUID().toString(); + } + + public static String getRequestId(HttpServletRequest httpRequest) { + String onapRequestId = httpRequest.getHeader(ONAPLogConstants.Headers.REQUEST_ID); + String requestId = httpRequest.getHeader(ConstantsLogging.X_REQUEST_ID); + String transactionReId = httpRequest.getHeader(ConstantsLogging.X_TRANSACTION_ID_HEADER); + String ecompRequestId = httpRequest.getHeader(ConstantsLogging.X_ECOMP_REQUEST_ID_HEADER); + return Arrays.asList(onapRequestId, requestId, transactionReId, ecompRequestId).stream() + .filter(id -> !StringUtils.isEmpty(id)).findFirst().orElse(generateKeyRequestId()); + } + + public static String getPartnerName(HttpServletRequest httpRequest) { + String userId = httpRequest.getHeader(ConstantsLogging.USER_ID_HEADER); + String onapPartnerName = httpRequest.getHeader(ONAPLogConstants.Headers.PARTNER_NAME); + String reqUri = httpRequest.getHeader(ConstantsLogging.USER_AGENT_HEADER); + return Arrays.asList(userId, onapPartnerName, reqUri).stream() + .filter(pn-> !StringUtils.isEmpty(pn)).findFirst().orElse(ConstantsLogging.PartnerName_Unknown); + } + + protected void setKeyRequestIdIfNotSetYet() { + if (StringUtils.isEmpty(ecompLogFieldsHandler.getKeyRequestId())) { + setKeyRequestId(LoggingThreadLocalsHolder.getUuid()); + } + } + + private void validateMandatoryFields(String originMsg) { + // this method only checks if the mandatory fields have been initialized + String filedNameThatHasNotBeenInitialized = checkMandatoryFieldsExistInMDC(); + + if (myLogger.isDebugEnabled() && !"".equalsIgnoreCase(filedNameThatHasNotBeenInitialized)) { + myLogger.debug(MarkerFactory.getMarker(LogMarkers.DEBUG_MARKER.text()), + String.format(missingLogFieldsMsg, filedNameThatHasNotBeenInitialized, originMsg)); + } + } + + @VisibleForTesting + String checkMandatoryFieldsExistInMDC() { + // this method returns a String of uninitialised fields + StringBuilder missingFields = new StringBuilder(); + getMandatoryFields().forEach(field -> { + if (ecompLogFieldsHandler.isMDCParamEmpty(field)) { + missingFields.append(field).append(" "); + } + }); + return missingFields.toString(); + } + + public abstract List<String> getMandatoryFields(); + + protected String convertExceptionStackToString(Exception ex) { + StringBuilder stackTrack = new StringBuilder(); + Arrays.asList(ex.getStackTrace()).forEach(item -> stackTrack.append(item.toString()).append("\n")); + return stackTrack.toString(); + } + + @Override + public void log(LogLevel logLevel, String message) { + log(logLevel, message, (Object) null); + } + + @Override + public void log(Marker marker, LogLevel logLevel, String message) { + log(marker, logLevel, message, (Object) null); + } + + @Override + public void log(LogLevel logLevel, String message, Object...params) { + validateMandatoryFields(message); + + switch(logLevel) { + case ERROR: + case FATAL: //TODO check how to log "FATAL" word + myLogger.error(myMarker, message, params); + break; + case WARN: + myLogger.warn(myMarker, message, params); + break; + case INFO: + myLogger.info(myMarker, message, params); + break; + case DEBUG: + myLogger.debug(myMarker, message, params); + break; + case TRACE: + myLogger.trace(myMarker, message, params); + break; + default: + break; + } + } + + @Override + public void log(LogLevel logLevel, String message, Throwable throwable) { + validateMandatoryFields(message); + + switch(logLevel) { + case ERROR: + case FATAL: //TODO check how to log "FATAL" word + myLogger.error(myMarker, createErrorMessage(message, throwable)); + break; + case WARN: + myLogger.warn(myMarker, createErrorMessage(message, throwable)); + break; + case INFO: + myLogger.info(myMarker, createErrorMessage(message, throwable)); + break; + case DEBUG: + myLogger.debug(myMarker, message, throwable); + break; + case TRACE: + myLogger.trace(myMarker, message, throwable); + break; + default: + break; + } + } + + @Override + public void log(Marker marker, LogLevel logLevel, String message, Object...params) { + validateMandatoryFields(message); + + switch(logLevel) { + case ERROR: + case FATAL: //TODO check how to log "FATAL" word + myLogger.error(marker, message, params); + break; + case WARN: + myLogger.warn(marker, message, params); + break; + case INFO: + myLogger.info(marker, message, params); + break; + case DEBUG: + myLogger.debug(marker, message, params); + break; + case TRACE: + myLogger.trace(marker, message, params); + break; + default: + break; + } + } + + protected String createErrorMessage(String message, Throwable throwable) { + return String.format("%s: %s", message, throwable.getLocalizedMessage()); + } + + + @Override + public ILogger clear() { + ecompLogFieldsHandler.clear(); + return this; + } + + @Override + public ILogger setKeyRequestId(String keyRequestId) { + ecompLogFieldsHandler.setKeyRequestId(keyRequestId); + return this; + } + + + @Override + public ILogger setKeyInvocationId(String keyInvocationId) { + ecompLogFieldsHandler.setKeyInvocationId(keyInvocationId); + return this; + } + + +} diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerDebug.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerDebug.java new file mode 100644 index 0000000000..dc8c4b4c16 --- /dev/null +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerDebug.java @@ -0,0 +1,75 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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.sdc.common.log.elements; + +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.openecomp.sdc.common.log.api.ILogFieldsHandler; +import org.openecomp.sdc.common.log.enums.LogLevel; +import org.openecomp.sdc.common.log.enums.LogMarkers; +import org.slf4j.Logger; +import org.slf4j.MarkerFactory; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class LoggerDebug extends LoggerBase { + + private static List<String> mandatoryFields = new ArrayList<>(Arrays.asList(ONAPLogConstants.MDCs.REQUEST_ID)); + + LoggerDebug(ILogFieldsHandler ecompMdcWrapper, Logger logger) { + super(ecompMdcWrapper, MarkerFactory.getMarker(LogMarkers.DEBUG_MARKER.text()), logger); + } + + @Override + public LoggerDebug clear() { + //nothing to clean up + return this; + } + + @Override + public void log(LogLevel logLevel, String message, Object...params){ + setKeyRequestIdIfNotSetYet(); + super.log(logLevel, message, params); + } + + @Override + public void log(LogLevel logLevel, String message, Throwable throwable){ + setKeyRequestIdIfNotSetYet(); + super.log(logLevel, message, throwable); + } + + @Override + public void log(LogLevel logLevel, String message){ + setKeyRequestIdIfNotSetYet(); + super.log(logLevel, message); + } + + @Override + public LoggerDebug startTimer() { + return this; + } + + @Override + public List<String> getMandatoryFields() { + return mandatoryFields; + } +} diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerError.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerError.java new file mode 100644 index 0000000000..a38f16df98 --- /dev/null +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerError.java @@ -0,0 +1,163 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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.sdc.common.log.elements; + +import org.apache.commons.lang3.StringUtils; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.openecomp.sdc.common.log.api.LogConfigurationConstants; +import org.openecomp.sdc.common.log.api.ILogFieldsHandler; +import org.openecomp.sdc.common.log.enums.EcompErrorSeverity; +import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; +import org.openecomp.sdc.common.log.enums.LogLevel; +import org.openecomp.sdc.common.log.enums.LogMarkers; +import org.slf4j.Logger; +import org.slf4j.MarkerFactory; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +public class LoggerError extends LoggerBase { + private static ArrayList<String> mandatoryFields = new ArrayList<>(Arrays.asList( + ONAPLogConstants.MDCs.REQUEST_ID, + ONAPLogConstants.MDCs.SERVICE_NAME, + LogConfigurationConstants.MDC_ERROR_CATEGORY, + LogConfigurationConstants.MDC_ERROR_CODE)); + + public static final String defaultServiceName = "SDC catalog"; + + LoggerError(ILogFieldsHandler ecompMdcWrapper, Logger logger) { + super(ecompMdcWrapper, MarkerFactory.getMarker(LogMarkers.ERROR_MARKER.text()), logger); + } + + @Override + public List<String> getMandatoryFields() { + return Collections.unmodifiableList(mandatoryFields); + } + + @Override + public LoggerError setKeyRequestId(String keyRequestId) { + return (LoggerError) super.setKeyRequestId(keyRequestId); + } + + @Override + public LoggerError startTimer() { + return this; + } + + @Override + public LoggerError clear() { + ecompLogFieldsHandler.removeErrorCategory(); + ecompLogFieldsHandler.removeErrorDescription(); + ecompLogFieldsHandler.removeErrorCode(); + return this; + } + + public void log(LogLevel logLevel, + EcompLoggerErrorCode errorCodeEnum, + String serviceName, + String targetEntity, + String message, Object...params) { + fillFieldsBeforeLogging(logLevel, errorCodeEnum, serviceName, targetEntity, null); + super.log(logLevel, message, params); + } + + public void log(LogLevel logLevel, + EcompLoggerErrorCode errorCodeEnum, + String serviceName, + ErrorLogOptionalData errorLogOptionalData, + String description, + Object...params) { + fillFieldsBeforeLogging(logLevel, errorCodeEnum, serviceName, + errorLogOptionalData.getTargetEntity(), errorLogOptionalData.getTargetServiceName()); + super.log(logLevel, description, params); + } + + private void fillFieldsBeforeLogging(LogLevel logLevel, EcompLoggerErrorCode errorCodeEnum, String serviceName, String targetEntity, String targetServiceName) { + clear(); + ecompLogFieldsHandler.setErrorCode(errorCodeEnum.getErrorCode()); + ecompLogFieldsHandler.setErrorCategory(logLevel.name()); + + ecompLogFieldsHandler.setTargetEntity(targetEntity); + ecompLogFieldsHandler.setTargetServiceName(targetServiceName); + + if (StringUtils.isEmpty(ecompLogFieldsHandler.getServiceName())) { + ecompLogFieldsHandler.setServiceName(serviceName); + } + + setKeyRequestIdIfNotSetYet(); + } + + public void log(EcompErrorSeverity errorSeverity, + EcompLoggerErrorCode errorCodeEnum, + String serviceName, + String targetEntity, + String message, Object... params) { + log(convertFromSeverityErrorLevel(errorSeverity), errorCodeEnum, serviceName, targetEntity, message, params); + } + + public void log(LogLevel logLevel, + EcompLoggerErrorCode errorCodeEnum, + String serviceName, + String message, Object...params) { + log(logLevel, errorCodeEnum, serviceName, (String)null, message, params); + } + + public void log(LogLevel logLevel, + EcompLoggerErrorCode errorCodeEnum, + String serviceName, + String message) { + log(logLevel, errorCodeEnum, serviceName, message); + } + + @Override + public void log(LogLevel logLevel, String message, Object...params) { + log(logLevel, EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, defaultServiceName, (String)null, message, params); + } + + public void log(LogLevel logLevel, String message, Throwable throwable) { + log(logLevel, createErrorMessage(message, throwable)); + } + + public void log(LogLevel logLevel, String message) { + log(logLevel, EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, defaultServiceName, (String)null, message); + } + + public void logInfo(LogLevel logLevel, String message, Object... params) { + log(logLevel, EcompLoggerErrorCode.SUCCESS, defaultServiceName, (String)null, message, params); + } + + private LogLevel convertFromSeverityErrorLevel(EcompErrorSeverity severityLevel) { + switch(severityLevel) { + case INFO: + return LogLevel.INFO; + case FATAL: + return LogLevel.FATAL; + case ERROR: + return LogLevel.ERROR; + case WARN: + return LogLevel.WARN; + } + return LogLevel.ERROR; + } + +} diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerFactory.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerFactory.java new file mode 100644 index 0000000000..59e2777966 --- /dev/null +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerFactory.java @@ -0,0 +1,82 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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.sdc.common.log.elements; + +import org.slf4j.Logger; + +/** + * Created by dd4296 on 12/26/2017. + * this factory helps decouple the classes for Stopwatch and LogFieldsMdcHandler from + * the EcompLogger classes + */ +public class LoggerFactory { + + private LoggerFactory() { + } + + @SuppressWarnings("unchecked") + public static <T, V> V getLogger(Class<T> type, Logger logger) { + + if (type.getName().equals(LoggerAudit.class.getName())) { + return (V) new LoggerAudit(new LogFieldsMdcHandler(), logger); + } + + if (type.getName().equals(LoggerDebug.class.getName())) { + return (V) new LoggerDebug(new LogFieldsMdcHandler(), logger); + } + + if (type.getName().equals(LoggerMetric.class.getName())) { + return (V) new LoggerMetric(new LogFieldsMdcHandler(), logger); + } + + if (type.getName().equals(LoggerError.class.getName())) { + return (V) new LoggerError(new LogFieldsMdcHandler(), logger); + } + + return null; + } + + @SuppressWarnings("unchecked") + public static <T, V> V getMdcLogger(Class<T> type, Logger logger) { + + if (type.getName().equals(LoggerAudit.class.getName())) { + return (V) new LoggerAudit(LogFieldsMdcHandler.getInstance(), logger); + } + + if (type.getName().equals(LoggerDebug.class.getName())) { + return (V) new LoggerDebug(LogFieldsMdcHandler.getInstance(), logger); + } + + if (type.getName().equals(LoggerMetric.class.getName())) { + return (V) new LoggerMetric(LogFieldsMdcHandler.getInstance(), logger); + } + + if (type.getName().equals(LoggerError.class.getName())) { + return (V) new LoggerError(LogFieldsMdcHandler.getInstance(), logger); + } + + if (type.getName().equals(LoggerSupportability.class.getName())) { + return (V) new LoggerSupportability(LogFieldsMdcHandler.getInstance(), logger); + } + + return null; + } +} diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerMetric.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerMetric.java new file mode 100644 index 0000000000..3dbcf1dde3 --- /dev/null +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerMetric.java @@ -0,0 +1,193 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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.sdc.common.log.elements; + +import org.openecomp.sdc.common.log.api.ILogFieldsHandler; +import org.openecomp.sdc.common.log.enums.LogLevel; +import org.openecomp.sdc.common.log.enums.LogMarkers; +import org.openecomp.sdc.common.log.enums.Severity; +import org.slf4j.Logger; +import org.slf4j.MarkerFactory; + +import javax.ws.rs.core.Response; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.*; +import static org.openecomp.sdc.common.log.api.LogConfigurationConstants.*; + + +public class LoggerMetric extends LoggerBase { + private static List<String> mandatoryFields = new ArrayList<>(Arrays.asList( + INVOKE_TIMESTAMP, + MDC_END_TIMESTAMP, + REQUEST_ID, + SERVICE_NAME, + PARTNER_NAME, + RESPONSE_CODE, + MDC_SERVICE_INSTANCE_ID, + RESPONSE_DESCRIPTION, + MDC_ELAPSED_TIME, + TARGET_ENTITY, + MDC_SERVER_IP_ADDRESS, + SERVER_FQDN)); + + private static List<String> optionalFields = new ArrayList<>(Arrays.asList( + MDC_TARGET_VIRTUAL_ENTITY, + TARGET_ENTITY, + TARGET_SERVICE_NAME, + RESPONSE_STATUS_CODE, + INSTANCE_UUID, + RESPONSE_SEVERITY, + MDC_REMOTE_HOST, + CLIENT_IP_ADDRESS, + MDC_CLASS_NAME, + MDC_PROCESS_KEY, + MDC_OPT_FIELD1, + MDC_OPT_FIELD2, + MDC_OPT_FIELD3, + MDC_OPT_FIELD4)); + + LoggerMetric(ILogFieldsHandler ecompMdcWrapper, Logger logger) { + super(ecompMdcWrapper, MarkerFactory.getMarker(LogMarkers.METRIC_MARKER.text()), logger); + //put the remote host and FQDN values from another thread if they are set + ecompMdcWrapper.setServerIPAddressInternally(); + ecompMdcWrapper.setServerFQDNInternally(); + } + + public void log(Response.StatusType statusInfo, + String className, + LogLevel logLevel, + Severity securityLevel, + String message) { + log(statusInfo,className, logLevel, securityLevel, message); + } + + @Override + public void log(LogLevel logLevel, String message) { + setKeyRequestIdIfNotSetYet(); + log(logLevel, message, (Object) null); + } + + @Override + public LoggerMetric startTimer() { + clear(); + ecompLogFieldsHandler.startMetricTimer(); + return this; + } + + public LoggerMetric stopTimer() { + ecompLogFieldsHandler.stopMetricTimer(); + return this; + } + + @Override + public LoggerMetric setKeyRequestId(String keyRequestId) { + return (LoggerMetric) super.setKeyRequestId(keyRequestId); + } + + @Override + public List<String> getMandatoryFields() { + return mandatoryFields; + } + + @Override + public LoggerMetric clear() { + ecompLogFieldsHandler.removeTargetEntity(); + ecompLogFieldsHandler.removeTargetServiceName(); + ecompLogFieldsHandler.removeResponseCode(); + ecompLogFieldsHandler.removeResponseDesc(); + ecompLogFieldsHandler.removeStatusCode(); + return this; + } + + + public LoggerMetric setInstanceUUID(String instanceUUID) { + ecompLogFieldsHandler.setInstanceUUID(instanceUUID); + return this; + } + + + public LoggerMetric setOutgoingInvocationId(String out_invocationId) { + ecompLogFieldsHandler.setOutgoingInvocationId(out_invocationId); + return this; + } + + public LoggerMetric setRemoteHost(String remoteHost) { + ecompLogFieldsHandler.setRemoteHost(remoteHost); + return this; + } + + public LoggerMetric setServiceName(String serviceName) { + ecompLogFieldsHandler.setServiceName(serviceName); + return this; + } + + public LoggerMetric setStatusCode(String statusCode) { + ecompLogFieldsHandler.setStatusCode(statusCode); + return this; + } + + public LoggerMetric setPartnerName(String partnerName) { + ecompLogFieldsHandler.setPartnerName(partnerName); + return this; + } + + public LoggerMetric setResponseCode(int responseCode) { + ecompLogFieldsHandler.setResponseCode(responseCode); + return this; + } + + public LoggerMetric setResponseDesc(String responseDesc) { + ecompLogFieldsHandler.setResponseDesc(responseDesc); + return this; + } + + public LoggerMetric setOptServiceInstanceId(String serviceInstanceId) { + ecompLogFieldsHandler.setServiceInstanceId(serviceInstanceId); + return this; + } + + public LoggerMetric setOptClassName(String className) { + ecompLogFieldsHandler.setClassName(className); + return this; + } + + public LoggerMetric setTargetEntity(String targetEntity) { + ecompLogFieldsHandler.setTargetEntity(targetEntity); + return this; + } + + public LoggerMetric setTargetServiceName(String targetServiceName) { + ecompLogFieldsHandler.setTargetServiceName(targetServiceName); + return this; + } + + public LoggerMetric setTargetVirtualEntity(String targetVirtualEntity) { + ecompLogFieldsHandler.setTargetVirtualEntity(targetVirtualEntity); + return this; + } + + + + +} diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerSupportability.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerSupportability.java new file mode 100644 index 0000000000..849add3625 --- /dev/null +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerSupportability.java @@ -0,0 +1,101 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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.sdc.common.log.elements; + +import org.openecomp.sdc.common.log.api.LogConfigurationConstants; +import org.openecomp.sdc.common.log.api.ILogFieldsHandler; +import org.openecomp.sdc.common.log.enums.LogLevel; +import org.openecomp.sdc.common.log.enums.LogMarkers; +import org.openecomp.sdc.common.log.enums.LoggerSupportabilityActions; +import org.openecomp.sdc.common.log.enums.StatusCode; +import org.slf4j.Logger; +import org.slf4j.MarkerFactory; + +import java.util.*; + +public class LoggerSupportability extends LoggerBase { + + public LoggerSupportability(ILogFieldsHandler ecompLogFieldsHandler, Logger logger) { + super(ecompLogFieldsHandler, MarkerFactory.getMarker(LogMarkers.SUPPORTABILITY_MARKER.text()), + logger); + } + + public static LoggerSupportability getLogger(String className) { + return LoggerFactory.getMdcLogger(LoggerSupportability.class, + org.slf4j.LoggerFactory.getLogger(className)); + } + + + public void log(LoggerSupportabilityActions action, Map<String,String> componentMetaData,StatusCode statusCode, String message, Object...params) { + fillFieldsBeforeLogging(action,componentMetaData,statusCode); + super.log(LogLevel.INFO,message, params); + } + + public void log(LoggerSupportabilityActions action, StatusCode statusCode, String message, Object...params) { + log(action, null, statusCode, message, params); + } + + private static List<String> mandatoryFields = new ArrayList<>(Arrays.asList( + LogConfigurationConstants.MDC_SUPPORTABLITY_ACTION, + LogConfigurationConstants.MDC_SUPPORTABLITY_CSAR_UUID, + LogConfigurationConstants.MDC_SUPPORTABLITY_CSAR_VERSION, + LogConfigurationConstants.MDC_SUPPORTABLITY_COMPONENT_NAME, + LogConfigurationConstants.MDC_SUPPORTABLITY_COMPONENT_UUID, + LogConfigurationConstants.MDC_SUPPORTABLITY_COMPONENT_VERSION, + LogConfigurationConstants.MDC_SUPPORTABLITY_STATUS_CODE)); + + private void fillFieldsBeforeLogging(LoggerSupportabilityActions action, Map<String,String> componentMetaData,StatusCode statusCode) { + clear(); + if (componentMetaData!=null){ + ecompLogFieldsHandler.setSupportablityCsarUUID(componentMetaData.get(LogConfigurationConstants.MDC_SUPPORTABLITY_CSAR_UUID)); + ecompLogFieldsHandler.setSupportablityCsarVersion(componentMetaData.get(LogConfigurationConstants.MDC_SUPPORTABLITY_CSAR_VERSION)); + ecompLogFieldsHandler.setSupportablityComponentName(componentMetaData.get(LogConfigurationConstants.MDC_SUPPORTABLITY_COMPONENT_NAME)); + ecompLogFieldsHandler.setSupportablityComponentUUID(componentMetaData.get(LogConfigurationConstants.MDC_SUPPORTABLITY_COMPONENT_UUID)); + ecompLogFieldsHandler.setSupportablityComponentVersion(componentMetaData.get(LogConfigurationConstants.MDC_SUPPORTABLITY_COMPONENT_VERSION)); + } + ecompLogFieldsHandler.setSupportablityAction(action.getName()); + ecompLogFieldsHandler.setSupportablityStatusCode(statusCode.getStatusCodeEnum()); + } + + @Override + public LoggerSupportability clear(){ + LogFieldsMdcHandler.getInstance().removeSupportablityAction(); + LogFieldsMdcHandler.getInstance().removeSupportablityCsarUUID(); + LogFieldsMdcHandler.getInstance().removeSupportablityCsarVersion(); + LogFieldsMdcHandler.getInstance().removeSupportablityComponentName(); + LogFieldsMdcHandler.getInstance().removeSupportablityComponentUUID(); + LogFieldsMdcHandler.getInstance().removeSupportablityComponentVersion(); + LogFieldsMdcHandler.getInstance().removeSupportablityStatusCode(); + return this; + } + + + @Override + public List<String> getMandatoryFields() { + return Collections.unmodifiableList(mandatoryFields); + } + + @Override + public LoggerSupportability startTimer() { + return this; + } + +} diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/ConstantsLogging.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/ConstantsLogging.java new file mode 100644 index 0000000000..34606dcebd --- /dev/null +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/ConstantsLogging.java @@ -0,0 +1,33 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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.sdc.common.log.enums; + +public final class ConstantsLogging { + public static final String USER_ID_HEADER = "USER_ID"; + public static final String USER_AGENT_HEADER = "User-Agent"; + public static final String PartnerName_Unknown = "UNKNOWN"; + public static final String X_ECOMP_REQUEST_ID_HEADER = "X-ECOMP-RequestID"; + public static final String X_TRANSACTION_ID_HEADER = "X-TransactionId"; + public static final String X_REQUEST_ID = "X-RequestID"; + public static final String X_ECOMP_INSTANCE_ID_HEADER = "X-ECOMP-InstanceID"; + public static final String X_ECOMP_SERVICE_ID_HEADER = "X-ECOMP-ServiceID"; + +} diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/EcompErrorSeverity.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/EcompErrorSeverity.java new file mode 100644 index 0000000000..4d21d8c8c6 --- /dev/null +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/EcompErrorSeverity.java @@ -0,0 +1,25 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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.sdc.common.log.enums; + +public enum EcompErrorSeverity { + INFO, WARN, ERROR, FATAL; +} diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/EcompLoggerErrorCode.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/EcompLoggerErrorCode.java new file mode 100644 index 0000000000..db174b4096 --- /dev/null +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/EcompLoggerErrorCode.java @@ -0,0 +1,67 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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.sdc.common.log.enums; + +import java.util.Arrays; +import java.util.Optional; + +/** + * Created by dd4296 on 12/26/2017. + */ +public enum EcompLoggerErrorCode { + SUCCESS(0), + PERMISSION_ERROR(100), + AVAILABILITY_TIMEOUTS_ERROR(200), + DATA_ERROR(300), + SCHEMA_ERROR(400), + BUSINESS_PROCESS_ERROR(500), + UNKNOWN_ERROR(900); + + private int errorCode; + + EcompLoggerErrorCode(int errorCode) { + this.errorCode = errorCode; + } + + public int getErrorCode() { + return errorCode; + } + + public static EcompLoggerErrorCode getByValue(String ecompErrorCode) { + String errorPrefix = parseCode(ecompErrorCode); + Optional<EcompLoggerErrorCode> optionalCode = Arrays.stream(values()).filter(v->isCode(v, errorPrefix)).findFirst(); + return optionalCode.orElse(UNKNOWN_ERROR); + } + + private static boolean isCode(EcompLoggerErrorCode ecompLoggerErrorCode, String errorPrefix) { + return String.valueOf(ecompLoggerErrorCode.getErrorCode()).contains(errorPrefix); + } + + private static String parseCode(String errorCode) { + try { + return errorCode.substring("E_".length(), 3); + } catch (StringIndexOutOfBoundsException ex) { + return UNKNOWN_ERROR.name(); + } + } + + +} diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/LogLevel.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/LogLevel.java new file mode 100644 index 0000000000..aaee7512bd --- /dev/null +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/LogLevel.java @@ -0,0 +1,30 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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.sdc.common.log.enums; + +public enum LogLevel { + INFO, + WARN, + DEBUG, + TRACE, + ERROR, + FATAL +} + diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/LogMarkers.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/LogMarkers.java new file mode 100644 index 0000000000..7b12ded745 --- /dev/null +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/LogMarkers.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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.sdc.common.log.enums; + +public enum LogMarkers { + DEBUG_MARKER("DEBUG_MARKER"), + ERROR_MARKER("ERROR_MARKER"), + METRIC_MARKER("METRICS"), + SUPPORTABILITY_MARKER("SUPPORTABILITY_MARKER"); + + private String text; + + LogMarkers (String text){ + this.text = text; + } + + public String text(){ + return text; + } + +} diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/LoggerSupportabilityActions.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/LoggerSupportabilityActions.java new file mode 100644 index 0000000000..d831700dec --- /dev/null +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/LoggerSupportabilityActions.java @@ -0,0 +1,85 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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.sdc.common.log.enums; + +public enum LoggerSupportabilityActions { + IMPORT_CSAR("CREATE RESOURCE FROM CSAR"), + CREATE_RESOURCE_FROM_YAML("CREATE RESOURCE FROM YAML"), + CREATE_RI_AND_RELATIONS("CREATE RI AND RELATIONS"), + CREATE_NODES_AND_CVFCS("ADD NODES AND CVFCS"), + CREATE_ARTIFACTS("ADD ARTIFACTS"), + CREATE_SERVICE("CREATE SERVICE"), + CREATE_RESOURCE("CREATE RESOURCE"), + CREATE_PROPERTIES("ADD PROPERTIES"), + CREATE_INPUTS("ADD INPUTS"), + CREATE_POLICIES("ADD POLICIES"), + CREATE_RELATIONS("ADD RELATIONS"), + CREATE_CAPABILITY_REQUIREMENTS("CREATE CAPABILITY REQUIREMENTS"), + MERGE("MERGE"), + PROPERTY_ASSIGNMENT("PROPERTY ASSIGNMENT"), + CREATE_INSTANCE("CREATE INSTANCE"), + CREATE_RELATION("ADD RELATION"), + CREATE_GROUP_POLICY("ADD GROUP POLICY"), + CREATE_GROUPS("ADD GROUPS"), + UPDATE_PROPERTY_IN_GROUP_POLICY("UPDATE PROPERTY IN GROUP POLICY"), + UPDATE_CAPABILITY("UPDATE CAPABILITY"), + PROPERTY("ADD PROPERTY"), + UPLOAD_DOWNLOAD_ARTIFACT("UPLOAD/DOWNLOAD ARTIFACT"), + LIFECYCLE("LIFECYCLE"), + DISTRIBUTION("DISTRIBUTION"), + UPDATE_CATALOG("UPDATE CATALOG"), + ARCHIVE("ARCHIVE"), + TENANT_ISOLATION("TENANT ISOLATION"), + DOWNLOAD_ARTIFACTS("DOWNLOAD ARTIFACTS"), + UPDATE_HEAT("UPDATE HEAT"), + PARAMETERS("PARAMETERS"), + CHANGELIFECYCLESTATE("CHANGE LIFECYCLE STATE"), + VALIDATE_NAME("VALIDATE COMPONENT NAME"), + DELETE_COMPONENT_INSTANCE_ARTIFACT("DELETE COMPONENT INSTANCE ARTIFACT"), + DELETE_SERVICE("DELETE SERVICE"), + DELETE_RESOURCE("DELETE RESOURCE"), + UPDATE_RESOURCE("UPDATE RESOURCE"), + UPDATE_COMPONENT_INSTANCE("UPDATE COMPONENT INSTANCE"), + DELETE_COMPONENT_INSTANCE("DELETE COMPONENT INSTANCE"), + UPDATE_PROPERTIES("UPDATE PROPERTIES"), + RESTORE_FROM_ARCHIVE("RESTORE FROM ARCHIVE"), + UPDATE_INPUTS("UPDATE INPUTS"), + DELETE_INPUTS("DELETE INPUTS"), + ASSOCIATE_RI_TO_RI("ASSOCIATE RI TO RI"), + UN_ASSOCIATE_RI_TO_RI("UN ASSOCIATE RI TO RI"), + UPDATE_ARTIFACT("UPDATE ARTIFACT"), + GENERATE_CSAR("GENERATE CSAR"), + GENERATE_TOSCA("GENERATE TOSCA"), + UPDATE_GROUP_MEMBERS("UPDATE GROUP MEMBERS"), + UPDATE_INSTANCE_CAPABILITY_PROPERTY("UPDATE INSTANCE CAPABILITY PROPERTY"), + UPDATE_POLICY_TARGET("UPDATE POLICY TARGET"), + UPDATE_POLICIES_PROPERTIES("UPDATE POLICIES PROPERTIES"); + private String name; + + LoggerSupportabilityActions(String name) { + this.name = name; + } + + public String getName() { + return name; + } + +} diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/Severity.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/Severity.java new file mode 100644 index 0000000000..0e90d57c8e --- /dev/null +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/Severity.java @@ -0,0 +1,40 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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.sdc.common.log.enums; + +public enum Severity { + OK(0), + WARNING(1), + CRITICAL(2), + DOWN(3), + UNREACHABLE(4); + + int severityType; + + Severity(int serveryType) { + this.severityType = serveryType; + } + + public int getSeverityType() { + return severityType; + } +} + diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/StatusCode.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/StatusCode.java new file mode 100644 index 0000000000..4ed65df97b --- /dev/null +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/StatusCode.java @@ -0,0 +1,38 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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.sdc.common.log.enums; + +public enum StatusCode { + ERROR("ERROR"), + STARTED("STARTED"), + COMPLETE("COMPLETE"), + INPROGRESS("INPROGRESS"); + + String statusCode; + + StatusCode(String statusCode) { + this.statusCode = statusCode; + } + + public String getStatusCodeEnum() { + return statusCode; + } +} diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/utils/EcompLogErrorCode.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/utils/EcompLogErrorCode.java new file mode 100644 index 0000000000..9c90529d22 --- /dev/null +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/utils/EcompLogErrorCode.java @@ -0,0 +1,42 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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.sdc.common.log.utils; + +public enum EcompLogErrorCode { + E_399("Internal Invalid Object. Description: %s"), + E_210("Connection problem towards U-EB server. Reason: %s"); + + + String description; + + EcompLogErrorCode(String description) { + this.description = description; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + +} diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/utils/LoggingThreadLocalsHolder.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/utils/LoggingThreadLocalsHolder.java new file mode 100644 index 0000000000..3d7a16b846 --- /dev/null +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/utils/LoggingThreadLocalsHolder.java @@ -0,0 +1,45 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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.sdc.common.log.utils; + + +public class LoggingThreadLocalsHolder { + + private LoggingThreadLocalsHolder() { + } + + private static final ThreadLocal<String> uuidThreadLocal = new ThreadLocal<>(); + + public static void setUuid(String uuid) { + uuidThreadLocal.set(uuid); + } + + public static String getUuid() { + return uuidThreadLocal.get(); + } + + + + public static void cleanup() { + uuidThreadLocal.remove(); + } + +} diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/wrappers/Logger.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/wrappers/Logger.java new file mode 100644 index 0000000000..9c2bfec126 --- /dev/null +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/wrappers/Logger.java @@ -0,0 +1,656 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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.sdc.common.log.wrappers; + +import com.google.common.annotations.VisibleForTesting; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.openecomp.sdc.common.log.elements.*; +import org.openecomp.sdc.common.log.enums.EcompErrorSeverity; +import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; +import org.openecomp.sdc.common.log.enums.LogLevel; +import org.slf4j.Marker; + +import java.util.UUID; + + +/** + * This class wraps {@link org.slf4j.Logger} object and provides mandatory information required by Ecomp logging rules. + * Note: All deprecated methods are supported to be compatible to the legacy code + * and have not be used by the new code + */ +public class Logger implements org.slf4j.Logger { + private final LoggerDebug debug; + private final LoggerError error; + private final LoggerMetric metric; + private final org.slf4j.Logger logger; + + @VisibleForTesting + public Logger(org.slf4j.Logger logger) { + this.logger = logger; + this.debug = LoggerFactory.getMdcLogger(LoggerDebug.class, logger); + this.error = LoggerFactory.getMdcLogger(LoggerError.class, logger); + this.metric = LoggerFactory.getMdcLogger(LoggerMetric.class, logger); + + } + + private Logger(String className) { + this(org.slf4j.LoggerFactory.getLogger(className)); + } + + public static Logger getLogger(String className) { + return new Logger(className); + } + + public static Logger getLogger(Class<?> clazz) { + return new Logger(clazz.getName()); + } + + + public boolean isDebugEnabled() { + return logger.isDebugEnabled(); + } + + @Override + public String getName() { + return logger.getName(); + } + + public boolean isTraceEnabled() { + return logger.isTraceEnabled(); + } + + public boolean isErrorEnabled() { return logger.isErrorEnabled(); } + + public boolean isWarnEnabled() { return logger.isWarnEnabled(); } + + @Override + @Deprecated /** Please use method {@link #warn(EcompLoggerErrorCode, String, String)} **/ + public void warn(String msg) { + if (isWarnEnabled()) { + error.log(LogLevel.WARN, msg); + } + } + + @Override + @Deprecated /** Please use method {@link #warn(EcompLoggerErrorCode, String, String)} **/ + public void warn(String msg, Object o) { + + if (isWarnEnabled()) { + error.log(LogLevel.WARN, msg, o); + } + } + + public boolean isInfoEnabled() { return logger.isInfoEnabled(); } + + @Override + public void info(String msg) { + if (isInfoEnabled()) { + debug.log(LogLevel.INFO, msg); + } + } + + @Override + public void info(String msg, Object o) { + if (isInfoEnabled()) { + debug.log(LogLevel.INFO, msg, o); + } + } + + @Override + public void info(String msg, Object o, Object o1) { + if (isInfoEnabled()) { + debug.log(LogLevel.INFO, msg, o, o1); + } + } + + public void debug(String msg, Object... params) { + if (isDebugEnabled()) { + debug.log(LogLevel.DEBUG, msg, params); + } + } + + public void metric(String msg, Object... params) { + metric.log(LogLevel.INFO, msg, params); + } + + public void invoke(String remoteHost, String targetEntity, String targetServiceName, String serviceName, String msg, Object... params) { + + String invocationId = UUID.randomUUID().toString(); + String requestID = UUID.randomUUID().toString(); + + metric.startTimer() + .stopTimer() + .setRemoteHost(remoteHost) + .setOutgoingInvocationId(invocationId) + .setTargetServiceName(targetServiceName) + .setTargetEntity(targetEntity) + .setStatusCode(ONAPLogConstants.ResponseStatus.COMPLETE.name()) + .setKeyRequestId(requestID) + .setServiceName(serviceName); + metric.log(ONAPLogConstants.Markers.INVOKE, LogLevel.INFO, msg, params); + } + + public void invokeReturn(String msg, Object... params) { + try { + metric.startTimer() + .stopTimer(); + } catch (Exception e) { + e.printStackTrace(); + } + metric.log(ONAPLogConstants.Markers.INVOKE_RETURN, LogLevel.INFO, msg, params); + } + + public void invokeSynchronous(String msg, Object... params) { + metric.log(ONAPLogConstants.Markers.INVOKE_SYNCHRONOUS, LogLevel.INFO, msg, params); + } + + @Override + public void debug(String msg, Throwable throwable) { + if (isDebugEnabled()) { + debug.log(LogLevel.DEBUG, msg, throwable); + } + } + + @Override + public boolean isDebugEnabled(Marker marker) { + return false; + } + + @Override + public void debug(Marker marker, String msg) { + if (isDebugEnabled()) { + debug.log(LogLevel.DEBUG, msg); + } + } + + @Override + public void debug(Marker marker, String msg, Object o) { + if (isDebugEnabled()) { + debug.log(LogLevel.DEBUG, msg, o); + } + } + + @Override + public void debug(Marker marker, String msg, Object o, Object o1) { + if (isDebugEnabled()) { + debug.log(LogLevel.DEBUG, msg, o, o1); + } + } + + @Override + public void debug(Marker marker, String msg, Object... objects) { + if (isDebugEnabled()) { + debug.log(LogLevel.DEBUG, msg, objects); + } + } + + @Override + public void debug(Marker marker, String msg, Throwable throwable) { + if (isDebugEnabled()) { + debug.log(LogLevel.DEBUG, msg, throwable); + } + } + + public void debug(String message) { + if (isDebugEnabled()) { + debug.log(LogLevel.DEBUG, message); + } + } + + @Override + public void debug(String msg, Object o) { + if (isDebugEnabled()) { + debug.log(LogLevel.DEBUG, msg, o); + } + } + + @Override + public void debug(String msg, Object o, Object o1) { + if (isDebugEnabled()) { + debug.log(LogLevel.DEBUG, msg, o, o1); + } + } + + public void trace(String message, Object... params) { + if (isTraceEnabled()) { + debug.log(LogLevel.TRACE, message, params); + } + } + + @Override + public void trace(String msg, Throwable throwable) { + if (isTraceEnabled()) { + debug.log(LogLevel.TRACE, msg, throwable); + } + } + + @Override + public boolean isTraceEnabled(Marker marker) { + return false; + } + + @Override + public void trace(Marker marker, String msg) { + if (isTraceEnabled()) { + debug.log(LogLevel.TRACE, msg); + } + } + + @Override + public void trace(Marker marker, String msg, Object o) { + if (isTraceEnabled()) { + debug.log(LogLevel.TRACE, msg, o); + } + } + + @Override + public void trace(Marker marker, String msg, Object o, Object o1) { + if (isTraceEnabled()) { + debug.log(LogLevel.TRACE, msg, o, o1); + } + } + + @Override + public void trace(Marker marker, String msg, Object... objects) { + if (isTraceEnabled()) { + debug.log(LogLevel.TRACE, msg, objects); + } + } + + @Override + public void trace(Marker marker, String msg, Throwable throwable) { + if (isTraceEnabled()) { + debug.log(LogLevel.TRACE, msg, throwable); + } + } + + public void trace(String msg) { + if (isTraceEnabled()) { + debug.log(LogLevel.TRACE, msg); + } + } + + @Override + public void trace(String msg, Object o) { + if (isTraceEnabled()) { + debug.log(LogLevel.TRACE, msg, o); + } + } + + @Override + public void trace(String msg, Object o, Object o1) { + if (isTraceEnabled()) { + debug.log(LogLevel.TRACE, msg, o, o1); + } + } + + public void info(String msg, Object... params) { + if (isInfoEnabled()) { + debug.log(LogLevel.INFO, msg, params); + } + } + + @Override + public void info(String msg, Throwable throwable) { + if (isInfoEnabled()) { + debug.log(LogLevel.INFO, msg, throwable); + } + } + + @Override + public boolean isInfoEnabled(Marker marker) { + return false; + } + + @Override + public void info(Marker marker, String msg) { + if (isInfoEnabled()) { + debug.log(LogLevel.INFO, msg); + } + } + + @Override + public void info(Marker marker, String msg, Object o) { + if (isInfoEnabled()) { + debug.log(LogLevel.INFO, msg, o); + } + } + + @Override + public void info(Marker marker, String msg, Object o, Object o1) { + if (isInfoEnabled()) { + debug.log(LogLevel.INFO, msg, o, o1); + } + } + + @Override + public void info(Marker marker, String msg, Object... objects) { + if (isInfoEnabled()) { + debug.log(LogLevel.INFO, msg, objects); + } + } + + @Override + public void info(Marker marker, String msg, Throwable throwable) { + if (isInfoEnabled()) { + debug.log(LogLevel.INFO, msg, throwable); + } + } + + @Deprecated /** Please use method {@link #warn(EcompLoggerErrorCode, String, String)} **/ + public void warn(String msg, Object... params){ + if (isWarnEnabled()) { + error.log(LogLevel.WARN, msg, params); + } + } + + @Override + @Deprecated /** Please use method {@link #warn(EcompLoggerErrorCode, String, String)} **/ + public void warn(String msg, Object o, Object o1) { + if (isWarnEnabled()) { + error.log(LogLevel.WARN, msg, o, o1); + } + } + + @Override + @Deprecated /** Please use method {@link #warn(EcompLoggerErrorCode, String, String)} **/ + public void warn(String msg, Throwable throwable) { + if (isWarnEnabled()) { + error.log(LogLevel.WARN, msg, throwable); + } + } + + @Override + public boolean isWarnEnabled(Marker marker) { + return false; + } + + @Override + @Deprecated /** Please use method {@link #warn(EcompLoggerErrorCode, String, String)} **/ + public void warn(Marker marker, String msg) { + if (isWarnEnabled()) { + error.log(LogLevel.WARN, msg); + } + } + + @Override + @Deprecated /** Please use method {@link #warn(EcompLoggerErrorCode, String, String)} **/ + public void warn(Marker marker, String msg, Object o) { + if (isWarnEnabled()) { + error.log(LogLevel.WARN, msg, o); + } + } + + @Override + @Deprecated /** Please use method {@link #warn(EcompLoggerErrorCode, String, String)} **/ + public void warn(Marker marker, String msg, Object o, Object o1) { + if (isWarnEnabled()) { + error.log(LogLevel.WARN, msg, o, o1); + } + } + + @Override + @Deprecated /** Please use method {@link #warn(EcompLoggerErrorCode, String, String)} **/ + public void warn(Marker marker, String msg, Object... objects) { + if (isWarnEnabled()) { + error.log(LogLevel.WARN, msg, objects); + } + } + + @Override + @Deprecated /** Please use method {@link #warn(EcompLoggerErrorCode, String, String)} **/ + public void warn(Marker marker, String msg, Throwable throwable) { + if (isWarnEnabled()) { + error.log(LogLevel.WARN, msg, throwable); + } + } + + @Deprecated /** Please use method {@link #error(EcompLoggerErrorCode, String, String)} **/ + public void error(String msg, Object... params){ + if (isErrorEnabled()) { + error.log(LogLevel.ERROR, msg, params); + } + } + + @Override + @Deprecated /** Please use method {@link #error(EcompLoggerErrorCode, String, String)} **/ + public void error(String msg, Throwable throwable) { + if (isErrorEnabled()) { + error.log(LogLevel.ERROR, msg, throwable); + } + } + + @Override + public boolean isErrorEnabled(Marker marker) { + return false; + } + + @Override + @Deprecated /** Please use method {@link #error(EcompLoggerErrorCode, String, String)} **/ + public void error(Marker marker, String msg) { + if (isErrorEnabled()) { + error.log(LogLevel.ERROR, msg); + } + } + + @Override + @Deprecated /** Please use method {@link #error(EcompLoggerErrorCode, String, String)} **/ + public void error(Marker marker, String msg, Object o) { + if (isErrorEnabled()) { + error.log(LogLevel.ERROR, msg, o); + } + } + + @Override + @Deprecated /** Please use method {@link #error(EcompLoggerErrorCode, String, String)} **/ + public void error(Marker marker, String msg, Object o, Object o1) { + if (isErrorEnabled()) { + error.log(LogLevel.ERROR, msg, o, o1); + } + } + + @Override + @Deprecated /** Please use method {@link #error(EcompLoggerErrorCode, String, String)} **/ + public void error(Marker marker, String msg, Object... params) { + if (isErrorEnabled()) { + error.log(LogLevel.ERROR, msg, params); + } + } + + @Override + @Deprecated /** Please use method {@link #error(EcompLoggerErrorCode, String, String)} **/ + public void error(Marker marker, String msg, Throwable throwable) { + if (isErrorEnabled()) { + error.log(LogLevel.ERROR, msg, throwable); + } + } + + @Deprecated /** Please use method {@link #error(EcompLoggerErrorCode, String, String)} **/ + public void error(String msg){ + if (isErrorEnabled()) { + error.log(LogLevel.ERROR, msg); + } + } + + @Override + @Deprecated /** Please use method {@link #error(EcompLoggerErrorCode, String, String)} **/ + public void error(String msg, Object o) { + if (isErrorEnabled()) { + error.log(LogLevel.ERROR, msg, o); + } + } + + @Override + @Deprecated /** Please use method {@link #error(EcompLoggerErrorCode, String, String)} **/ + public void error(String msg, Object o, Object o1) { + if (isErrorEnabled()) { + error.log(LogLevel.ERROR, msg, o, o1); + } + } + + /** + * Writes out ERROR logging level message to the application error log + * @param errorLevel code representing the error severity level + * @param serviceName name of the API invoked at the logging component + * @param targetEntity name of the ECOMP component or sub-component, or external entity at which the error occurred or null + * @param errorDescription a human readable description of the error condition + * @param params optional parameters of a given error description + */ + public void error(EcompErrorSeverity errorLevel, + EcompLoggerErrorCode errorCodeEnum, + String serviceName, + String targetEntity, + String errorDescription, Object...params) { + if (isErrorEnabled()) { + error.log(errorLevel, errorCodeEnum, serviceName, targetEntity, errorDescription, params); + } + } + + /** + * Writes out ERROR logging level message to the application error log + * @param errorCodeEnum code representing the error condition + * @param serviceName name of the API invoked at the logging component + * @param targetEntity name of the ECOMP component or sub-component, or external entity at which the error occurred or null + * @param errorDescription a human readable description of the error condition + * @param params optional parameters of a given error description + */ + @Deprecated /** Please use method {@link #error(EcompLoggerErrorCode, String, ErrorLogOptionalData, String, Object...)} **/ + public void error(EcompLoggerErrorCode errorCodeEnum, + String serviceName, + String targetEntity, + String errorDescription, Object...params) { + if (isErrorEnabled()) { + error.log(LogLevel.ERROR, errorCodeEnum, serviceName, targetEntity, errorDescription, params); + } + } + + /* Writes out ERROR logging level message to the application error LOG + * @param errorCodeEnum code representing the error condition + * @param errorDescription a human readable description of the error condition + * @param params optional parameters of a given error description + */ + + public void error(EcompLoggerErrorCode errorCodeEnum, String serviceName, + String errorDescription, Object...params) { + error(errorCodeEnum, serviceName, (String)null, errorDescription, params); + } + + /** + * Writes out ERROR logging level message to the application error log + * @param errorCodeEnum code representing the error condition + * @param serviceName name of the API invoked at the logging component + * @param errorLogOptionalData elements that contans all relevant data of the error + * @param errorDescription a human readable description of the error condition + * @param params optional parameters of a given error description + */ + public void error(EcompLoggerErrorCode errorCodeEnum, + String serviceName, + ErrorLogOptionalData errorLogOptionalData, + String errorDescription, + Object...params) { + if (isErrorEnabled()) { + error.log(LogLevel.ERROR, errorCodeEnum, serviceName, errorLogOptionalData, errorDescription, params); + } + } + + /** + * Writes out WARN logging level message to the application error log + * @param errorCodeEnum code representing the error condition + * @param serviceName name of the API invoked at the logging component + * @param targetEntity name of the ECOMP component or sub-component, or external entity at which the error occurred or null + * @param errorDescription a human readable description of the error condition + * @param params optional parameters of a given error description + */ + public void warn(EcompLoggerErrorCode errorCodeEnum, + String serviceName, + String targetEntity, + String errorDescription, Object...params) { + if (isWarnEnabled()) { + error.log(LogLevel.WARN, errorCodeEnum, serviceName, targetEntity, errorDescription, params); + } + } + + /** + * Writes out WARN logging level message to the application error log + * @param errorCodeEnum code representing the error condition + * @param serviceName name of the API invoked at the logging component + * @param errorLogOptionalData elements that contans all relevant data of the error + * @param description a human readable description of the error condition + * @param params optional parameters of a given error description + */ + public void warn(EcompLoggerErrorCode errorCodeEnum, + String serviceName, + ErrorLogOptionalData errorLogOptionalData, + String description, Object...params) { + if (isWarnEnabled()) { + error.log(LogLevel.WARN, errorCodeEnum, serviceName, errorLogOptionalData, description, params); + } + } + + /** + * Writes out WARN logging level message to the application error log + * @param errorCodeEnum code representing the error condition + * @param serviceName name of the API invoked at the logging component + * @param errorDescription a human readable description of the error condition + * @param params optional parameters of a given error description + */ + public void warn(EcompLoggerErrorCode errorCodeEnum, + String serviceName, + String errorDescription, Object...params) { + if (isWarnEnabled()) { + error.log(LogLevel.WARN, errorCodeEnum, serviceName, (String)null, errorDescription, params); + } + } + + /** + * Writes out FATAL logging level message to the application error log + * @param errorCodeEnum code representing the error condition + * @param serviceName name of the API invoked at the logging component + * @param targetEntity name of the ECOMP component or sub-component, or external entity at which the error occurred or null + * @param errorDescription a human readable description of the error condition + * @param params optional parameters of a given error description + */ + public void fatal(EcompLoggerErrorCode errorCodeEnum, + String serviceName, + String targetEntity, + String errorDescription, Object...params) { + if (isErrorEnabled()) { + error.log(LogLevel.FATAL, errorCodeEnum, serviceName, targetEntity, errorDescription, params); + } + } + + /** + * Writes out FATAL logging level message to the application error log + * @param errorCodeEnum code representing the error condition + * @param serviceName name of the API invoked at the logging component + * @param errorLogOptionalData elements that contans all relevant data of the error + * @param description a human readable description of the error condition + * @param params optional parameters of a given error description + */ + public void fatal(EcompLoggerErrorCode errorCodeEnum, String serviceName, + ErrorLogOptionalData errorLogOptionalData, + String description, Object...params) { + if (isErrorEnabled()) { + error.log(LogLevel.FATAL, errorCodeEnum, serviceName, errorLogOptionalData, description, params); + } + } +} + diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/wrappers/LoggerSdcAudit.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/wrappers/LoggerSdcAudit.java new file mode 100644 index 0000000000..b2db66ed00 --- /dev/null +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/wrappers/LoggerSdcAudit.java @@ -0,0 +1,177 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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.sdc.common.log.wrappers; + +import org.apache.commons.lang3.StringUtils; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.openecomp.sdc.common.log.enums.ConstantsLogging; +import org.openecomp.sdc.common.log.elements.LoggerAudit; +import org.openecomp.sdc.common.log.elements.LoggerFactory; +import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; +import org.openecomp.sdc.common.log.enums.LogLevel; +import org.openecomp.sdc.common.log.enums.Severity; +import org.openecomp.sdc.common.log.utils.LoggingThreadLocalsHolder; +import org.slf4j.MDC; +import org.slf4j.Marker; + +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.core.Response; +import java.util.UUID; + + +/** + * Created by dd4296 on 12/19/2017. + * + * audit log for asdc using the log library + * this is adapted for filter classes + */ +public class LoggerSdcAudit extends LoggerSdcUtilBase { + + private static String AUDIT_ON = "auditOn"; + private String className; + private final LoggerAudit ecompLoggerAudit; + + public LoggerSdcAudit(Class<?> clazz) { + this.className = clazz.getName(); + ecompLoggerAudit = LoggerFactory.getMdcLogger(LoggerAudit.class, org.slf4j.LoggerFactory.getLogger(clazz)); + } + + public void startLog(ContainerRequestContext requestContext) { + ecompLoggerAudit.clear() + .startTimer() + .setPartnerName(getPartnerName( + requestContext.getHeaderString("user-agent"), + requestContext.getHeaderString("USER_ID"), + getUrl(requestContext), + requestContext.getHeaderString("X-ONAP-PartnerName"))) + .setServiceName(getServiceName(requestContext)) + .setKeyRequestId(LoggingThreadLocalsHolder.getUuid()) + .setKeyInvocationId(UUID.randomUUID().toString()); + MDC.put(AUDIT_ON, "true"); + } + + public void startAuditFetchLog(String partnerName, String serviceName) { + ecompLoggerAudit.clear() + .startTimer() + .setPartnerName(partnerName) + .setServiceName(serviceName) + .setOptClassName(serviceName); + MDC.put(AUDIT_ON, "true"); + } + + public static boolean isFlowBeingTakenCare() { + String auditOn = MDC.get(AUDIT_ON); + return !StringUtils.isEmpty(auditOn) && "true".equals(auditOn); + } + + //this function clears the MDC data that relevant for this class + public void clearMyData(){ + ecompLoggerAudit.clear(); + } + + public void logExit(String remoteAddress, + ContainerRequestContext requestContext, + Response.StatusType statusInfo, + LogLevel logLevel, + Severity securityLevel, + String message, + Marker marker) { + + try { + + String msg = ecompLoggerAudit.getAuditMessage() == null ? + message : ecompLoggerAudit.getAuditMessage(); + ecompLoggerAudit.stopTimer() + .setRemoteHost(remoteAddress) + .setResponseCode(convertHttpCodeToErrorCode(statusInfo.getStatusCode())) + .setStatusCodeByResponseCode(Integer.toString(statusInfo.getStatusCode())) + .setResponseDesc(statusInfo.getReasonPhrase()) + .setInstanceUUID(requestContext.getHeaderString(ConstantsLogging.X_ECOMP_INSTANCE_ID_HEADER)) + .setOptServiceInstanceId(requestContext.getHeaderString(ConstantsLogging.X_ECOMP_SERVICE_ID_HEADER)) + .setOptClassName(className) + .setOptAlertSeverity(securityLevel) + .log(marker, logLevel, msg); + } + catch (Exception e) { + log.warn("Failed to write to Audit Log. Original Message: {}", message, e); + } + finally { + MDC.put(AUDIT_ON,"false"); + } + } + + public void logEntry(String remoteAddress, + ContainerRequestContext requestContext, + LogLevel logLevel, + Severity securityLevel, + String message, + Marker marker) { + + try { + + String msg = ecompLoggerAudit.getAuditMessage() == null ? + message : ecompLoggerAudit.getAuditMessage(); + ecompLoggerAudit.stopTimer() + .setRemoteHost(remoteAddress) + .setResponseCode(EcompLoggerErrorCode.SUCCESS) + .setStatusCode(ONAPLogConstants.ResponseStatus.INPROGRESS.name()) + .setResponseDesc("") + .setInstanceUUID(requestContext.getHeaderString(ConstantsLogging.X_ECOMP_INSTANCE_ID_HEADER)) + .setOptServiceInstanceId(requestContext.getHeaderString(ConstantsLogging.X_ECOMP_SERVICE_ID_HEADER)) + .setOptClassName(className) + .setOptAlertSeverity(securityLevel) + .log(marker, logLevel, msg); + } + catch (Exception e) { + log.warn("Failed to write to Audit Log. Original Message: {}", message, e); + } + finally { + MDC.put(AUDIT_ON,"false"); + } + } + + public void logEntry(LogLevel logLevel, + Severity securityLevel, + String message, + Marker marker, + String requestId) { + + try { + + String msg = ecompLoggerAudit.getAuditMessage() == null ? + message : ecompLoggerAudit.getAuditMessage(); + ecompLoggerAudit.stopTimer() + .setKeyRequestId(requestId) + .setResponseCode(EcompLoggerErrorCode.SUCCESS) + .setStatusCode(ONAPLogConstants.ResponseStatus.COMPLETE.name()) + .setResponseDesc("") + .setOptAlertSeverity(securityLevel) + .log(marker, logLevel, msg); + } + catch (Exception e) { + log.warn("Failed to write to Audit Log. Original Message: {}", message, e); + } + finally { + MDC.put(AUDIT_ON,"false"); + } + } + +} diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/wrappers/LoggerSdcUtilBase.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/wrappers/LoggerSdcUtilBase.java new file mode 100644 index 0000000000..cec429a000 --- /dev/null +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/wrappers/LoggerSdcUtilBase.java @@ -0,0 +1,204 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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.sdc.common.log.wrappers; + +import org.apache.commons.lang3.StringUtils; +import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.ws.rs.container.ContainerRequestContext; +import java.util.List; +import java.util.StringTokenizer; + +import static java.net.HttpURLConnection.*; + +public class LoggerSdcUtilBase { + + protected static Logger log = LoggerFactory.getLogger(LoggerSdcUtilBase.class.getName()); + + String getRequestIDfromHeaders(List<Object> requestHeader) { + // this method gets list of type object. + // toString method returns the RequestId with brackets. + String requestHeaderString = requestHeader.toString(); + return requestHeaderString.replace("[","").replace("]",""); + } + + + + // this method translates http error code to ECOMP Logger Error code + // this is a naive translation and is not a result of any documented format ECOMP specification + protected EcompLoggerErrorCode convertHttpCodeToErrorCode(int httpResponseCode) { + if (isSuccessError(httpResponseCode)) { + return EcompLoggerErrorCode.SUCCESS; + } + + if (isSchemaError(httpResponseCode)) { + return EcompLoggerErrorCode.SCHEMA_ERROR; + } + if (isDataError(httpResponseCode)) { + return EcompLoggerErrorCode.DATA_ERROR; + } + if (isPermissionsError(httpResponseCode)) { + return EcompLoggerErrorCode.PERMISSION_ERROR; + } + if (isTimeoutOrAvailabilityError(httpResponseCode)) { + return EcompLoggerErrorCode.AVAILABILITY_TIMEOUTS_ERROR; + } + if (isBusinessProcessError(httpResponseCode)) { + return EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR; + } + return EcompLoggerErrorCode.UNKNOWN_ERROR; + } + + private boolean isTimeoutOrAvailabilityError(int httpResponseCode) { + + switch (httpResponseCode) { + case HTTP_BAD_REQUEST: + case HTTP_UNAUTHORIZED: + case HTTP_NOT_FOUND: + case HTTP_CLIENT_TIMEOUT: + case HTTP_GONE: + return true; + default: + return false; + } + + } + + private boolean isPermissionsError(int httpResponseCode) { + + switch (httpResponseCode) { + case HTTP_PAYMENT_REQUIRED: + case HTTP_FORBIDDEN: + case HTTP_BAD_METHOD: + case HTTP_PROXY_AUTH: + return true; + default: return false; + } + } + + private boolean isDataError(int httpResponseCode) { + + switch (httpResponseCode) { + case HTTP_NOT_ACCEPTABLE: + case HTTP_LENGTH_REQUIRED: + case HTTP_PRECON_FAILED: + case HTTP_REQ_TOO_LONG: + case HTTP_ENTITY_TOO_LARGE: + case HTTP_UNSUPPORTED_TYPE: + return true; + default: return false; + } + } + + private boolean isSchemaError(int httpResponseCode) { + return HTTP_CONFLICT == httpResponseCode; + } + + private boolean isSuccessError(int httpResponseCode) { + return httpResponseCode < 399; + } + + private boolean isBusinessProcessError(int httpResponseCode) { + return httpResponseCode > 499; + } + + protected String getPartnerName(String userAgent, String userId, String url, String xOnapPartnerName) { + + //On called side (receiver) If the API call is authenticated, then log the userid/mechid (fully qualified if that is what was provided) + if (isFound(userId)) { + return userId; + } + + String urlUser = getUserIdFromUrl(url); + if (isFound(urlUser)) { + return urlUser; + } + + //Otherwise, if X-ONAP-PartnerName was provided, then log that + if (isFound(xOnapPartnerName)){ + return xOnapPartnerName; + } + + //Otherwise, for an HTTP API call, log the part of the URI specifying the agent that the caller used to make the call + String userAgentName = getUserIdFromUserAgent(userAgent); + if (isFound(userAgentName)) { + return userAgentName; + } + + return "UNKNOWN"; + } + + private String getUserIdFromUserAgent(String userAgent) { + if (userAgent != null && userAgent.length() > 0) { + if (userAgent.toLowerCase().contains("firefox")) { + return "fireFox_FE"; + } + + if (userAgent.toLowerCase().contains("msie")) { + return "explorer_FE"; + } + + if (userAgent.toLowerCase().contains("chrome")) { + return "chrome_FE"; + } + + return userAgent; + } + return null; + } + + private String getUserIdFromUrl(String url) { + if (url != null && url.toLowerCase().contains("user")) { + StringTokenizer st = new StringTokenizer(url, "/"); + while (st.hasMoreElements()) { + if ("user".equalsIgnoreCase(st.nextToken())) { + return st.nextToken(); + } + } + } + return null; + } + + protected String getUrl(ContainerRequestContext requestContext) { + String url = ""; + + try { + if (requestContext.getUriInfo() != null && requestContext.getUriInfo().getRequestUri() != null) { + url = requestContext.getUriInfo().getRequestUri().toURL().toString(); + } + } catch (Exception ex) { + log.error("failed to get url from request context ", ex); + } + + return url; + } + + protected String getServiceName(ContainerRequestContext requestContext) { + return (requestContext.getUriInfo().getRequestUri().toString()) + .replace(requestContext.getUriInfo().getBaseUri().toString(), "/"); + } + + private boolean isFound(String value) { + return (StringUtils.isNotEmpty(value)); + } +}
\ No newline at end of file diff --git a/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LogFieldsMdcHandlerTest.java b/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LogFieldsMdcHandlerTest.java new file mode 100644 index 0000000000..1634115b06 --- /dev/null +++ b/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LogFieldsMdcHandlerTest.java @@ -0,0 +1,100 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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.sdc.common.log.elements; + +import org.junit.Before; +import org.junit.Test; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.slf4j.MDC; + +import static org.junit.Assert.*; +import static org.openecomp.sdc.common.log.api.LogConfigurationConstants.*; + +public class LogFieldsMdcHandlerTest { + + private LogFieldsMdcHandler ecompMdcWrapper; + + @Before + public void init(){ + ecompMdcWrapper = new LogFieldsMdcHandler(); + ecompMdcWrapper.clear(); + MDC.clear(); + } + + @Test + public void isMDCParamEmpty_shouldReturnTrue_onNonNullValueInMDC(){ + MDC.put("Key","value1"); + assertFalse(ecompMdcWrapper.isMDCParamEmpty("Key")); + } + @Test + public void isMDCParamEmpty_shouldReturnFalse_onEmptyStringInMDC(){ + MDC.put("Key",""); + assertTrue(ecompMdcWrapper.isMDCParamEmpty("Key")); + } + + @Test + public void isMDCParamEmpty_shouldReturnFalse_onNullValueInMDC(){ + MDC.put("Key",null); + assertTrue(ecompMdcWrapper.isMDCParamEmpty("Key")); + } + + @Test + public void startTimer_shouldFilecompMdcWrappereginTimestampField(){ + ecompMdcWrapper.startMetricTimer(); + assertFalse(ecompMdcWrapper.isMDCParamEmpty(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP)); + } + + @Test + public void stopTimer_shouldFillEndTimestampField_ifStartTimerWasCalledPreviously(){ + ecompMdcWrapper.startAuditTimer(); + ecompMdcWrapper.stopAuditTimer(); + assertFalse(ecompMdcWrapper.isMDCParamEmpty(MDC_END_TIMESTAMP)); + } + + @Test + public void clear_shouldRemoveAllMandatoryAndOptionalFields_And_OnlyThem(){ + ecompMdcWrapper.setClassName("class1"); + ecompMdcWrapper.setPartnerName("partner1"); + ecompMdcWrapper.setOptCustomField1("of1"); + ecompMdcWrapper.clear(); + assertNull(MDC.get(MDC_CLASS_NAME)); + assertNull(MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME)); + assertNull(MDC.get(MDC_OPT_FIELD1)); + } + + @Test + public void clear_shouldNotThrowAnException_WhenNoFieldWasAssignedAsMandatoryOrOptional(){ + ecompMdcWrapper.setClassName("class1"); + ecompMdcWrapper.setPartnerName("partner1"); + ecompMdcWrapper.setOptCustomField1("of1"); + Exception exp = null; + try { + ecompMdcWrapper.clear(); + } + catch (Exception e) + { + exp =e; + } + assertNull(exp); + } + +} + diff --git a/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerAsdcUtilTest.java b/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerAsdcUtilTest.java new file mode 100644 index 0000000000..4b0533ae24 --- /dev/null +++ b/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerAsdcUtilTest.java @@ -0,0 +1,195 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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.sdc.common.log.elements; + + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; +import org.openecomp.sdc.common.log.enums.LogLevel; +import org.openecomp.sdc.common.log.enums.Severity; +import org.openecomp.sdc.common.log.wrappers.LoggerSdcAudit; +import org.openecomp.sdc.common.log.wrappers.LoggerSdcUtilBase; +import org.slf4j.MarkerFactory; + +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.core.UriInfo; +import java.net.URI; +import java.net.URISyntaxException; + +import static java.net.HttpURLConnection.*; +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class LoggerAsdcUtilTest { + + private static final String chromeUserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"; + private static final String firefoxUserAgent = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en-US; rv:1.8.1.13) Gecko/20080313 Firefox"; + private static final String explorerUserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows Phone OS 7.5; Trident/5.0; IEMobile/9.0)"; + + private static final String testUserId = "ml007"; + private static final String urlWithUserName = "/api/v1/user/" + testUserId; + private static final String xOnapPartnerName = "ml007"; + + class SdcEelfAuditTest extends LoggerSdcAudit { + + SdcEelfAuditTest(Class<?> clazz) { + super(clazz); + } + + public String getPartnerName(String userAgent, String userID, String url, String xOnapPartnerName) { + return super.getPartnerName(userAgent, userID, url, xOnapPartnerName); + } + } + + @Mock + private ContainerRequestContext requestContext; + @Mock + UriInfo uriInfo; + + private SdcEelfAuditTest asdcEelfAudit; + + @Before + public void Init () throws URISyntaxException { + asdcEelfAudit = new SdcEelfAuditTest(LoggerAsdcUtilTest.class); + when(requestContext.getHeaderString(anyString())).thenReturn("ab2222"); + when(requestContext.getUriInfo()).thenReturn(uriInfo); + URI uri = new URI("http:/abc.com/getId"); + when(uriInfo.getRequestUri()).thenReturn(uri); + when(uriInfo.getBaseUri()).thenReturn(uri); + + } + + @Test + public void extract_user_id_from_userAgentTest() { + + String userIdChrome = asdcEelfAudit.getPartnerName(chromeUserAgent, "", "", ""); + assertEquals(userIdChrome.toLowerCase(), "chrome_FE".toLowerCase()); + + String userIdFireFox = asdcEelfAudit.getPartnerName(firefoxUserAgent, "", "", ""); + assertEquals(userIdFireFox.toLowerCase(), "firefox_FE".toLowerCase()); + + String userIdIE = asdcEelfAudit.getPartnerName(explorerUserAgent, "", "", ""); + assertEquals(userIdIE.toLowerCase(), "explorer_FE".toLowerCase()); + } + + @Test + public void extract_user_id_from_urlTest() { + + String userId = asdcEelfAudit.getPartnerName("", "", urlWithUserName, ""); + assertEquals(testUserId, userId); + } + + @Test + public void extract_user_id_from_paramTest() { + + String userId = asdcEelfAudit.getPartnerName("", testUserId, "", ""); + assertEquals(userId, testUserId); + } + + @Test + public void extract_user_id_from_xOnapPartnerNameTest() { + + String userId = asdcEelfAudit.getPartnerName("", "", "", xOnapPartnerName); + assertEquals(userId, testUserId); + } + + @Test + public void extract_user_id_priorityTest() { + + String userId = asdcEelfAudit.getPartnerName(chromeUserAgent, testUserId, urlWithUserName, xOnapPartnerName); + assertEquals(userId, testUserId); + + String userIdUrl = asdcEelfAudit.getPartnerName(chromeUserAgent, "", urlWithUserName, ""); + assertEquals(userIdUrl, testUserId); + + String userIdUserAgent = asdcEelfAudit.getPartnerName(chromeUserAgent, "", "", ""); + assertEquals(userIdUserAgent.toLowerCase(), "chrome_FE".toLowerCase()); + } + + @Test + public void check_http_error_convert_to_eelf_code() { + class LoggerSdcUtilBaseTest extends LoggerSdcUtilBase { + public EcompLoggerErrorCode convertHttpCodeToErrorCode(int httpResponseCode) { + return super.convertHttpCodeToErrorCode(httpResponseCode); + } + } + + LoggerSdcUtilBaseTest utilBase = new LoggerSdcUtilBaseTest(); + + Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_BAD_REQUEST), EcompLoggerErrorCode.AVAILABILITY_TIMEOUTS_ERROR); + Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_UNAUTHORIZED), EcompLoggerErrorCode.AVAILABILITY_TIMEOUTS_ERROR); + Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_NOT_FOUND), EcompLoggerErrorCode.AVAILABILITY_TIMEOUTS_ERROR); + Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_CLIENT_TIMEOUT), EcompLoggerErrorCode.AVAILABILITY_TIMEOUTS_ERROR); + Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_GONE), EcompLoggerErrorCode.AVAILABILITY_TIMEOUTS_ERROR); + + Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_PAYMENT_REQUIRED), EcompLoggerErrorCode.PERMISSION_ERROR); + Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_FORBIDDEN), EcompLoggerErrorCode.PERMISSION_ERROR); + Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_BAD_METHOD), EcompLoggerErrorCode.PERMISSION_ERROR); + Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_PROXY_AUTH), EcompLoggerErrorCode.PERMISSION_ERROR); + + Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_NOT_ACCEPTABLE), EcompLoggerErrorCode.DATA_ERROR); + Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_LENGTH_REQUIRED), EcompLoggerErrorCode.DATA_ERROR); + Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_PRECON_FAILED), EcompLoggerErrorCode.DATA_ERROR); + Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_REQ_TOO_LONG), EcompLoggerErrorCode.DATA_ERROR); + Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_ENTITY_TOO_LARGE), EcompLoggerErrorCode.DATA_ERROR); + Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_UNSUPPORTED_TYPE), EcompLoggerErrorCode.DATA_ERROR); + + Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_CONFLICT), EcompLoggerErrorCode.SCHEMA_ERROR); + + Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_OK), EcompLoggerErrorCode.SUCCESS); + + Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_INTERNAL_ERROR), EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR); + Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_NOT_IMPLEMENTED), EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR); + Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_BAD_GATEWAY), EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR); + Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_UNAVAILABLE), EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR); + Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_GATEWAY_TIMEOUT), EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR); + Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_VERSION), EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR); + + } + + @Test + public void takenCareOf_shouldBeTrue_ifStartedLogWasCalled(){ + asdcEelfAudit.startLog(requestContext); + assertTrue(asdcEelfAudit.isFlowBeingTakenCare()); + } + + @Test + public void takenCareOf_shouldBeFalse_ifStartedLogWasNoCalled(){ + assertFalse(asdcEelfAudit.isFlowBeingTakenCare()); + } + + @Test + public void takenCareOf_shouldBeFalse_ifStartedLogWasCalleAndLogWasCalledToo(){ + asdcEelfAudit.startLog(requestContext); + + asdcEelfAudit.logExit(null,null,null, LogLevel.INFO, Severity.OK, + "message", MarkerFactory.getMarker(ONAPLogConstants.Markers.EXIT.getName())); + assertFalse(asdcEelfAudit.isFlowBeingTakenCare()); + } +} diff --git a/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerAuditTest.java b/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerAuditTest.java new file mode 100644 index 0000000000..7ca1cf16cc --- /dev/null +++ b/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerAuditTest.java @@ -0,0 +1,117 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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.sdc.common.log.elements; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.openecomp.sdc.common.log.enums.LogLevel; +import org.openecomp.sdc.common.log.enums.Severity; +import org.slf4j.Logger; +import org.slf4j.MDC; + +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.UUID; + +import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.*; +import static org.openecomp.sdc.common.log.api.LogConfigurationConstants.*; +import static org.openecomp.sdc.common.log.elements.LogFieldsMdcHandler.hostAddress; +import static org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode.DATA_ERROR; + +@RunWith(MockitoJUnitRunner.class) +public class LoggerAuditTest { + @Mock + private Logger logger; + + private LoggerAudit auditLog; + + @Before + public void init() { + auditLog = new LoggerAudit(LogFieldsMdcHandler.getInstance(), logger); + } + + @After + public void tearDown() { + MDC.clear(); + } + + @Test + public void whenNoAuditFieldsArePopulated_ShouldReturnAssertTrue_onMdcMap() { + auditLog.clear() + .log(LogLevel.INFO, "some error code"); + Assert.assertNotNull(MDC.get(SERVER_FQDN)); + Assert.assertNotNull(MDC.get(MDC_SERVER_IP_ADDRESS)); + } + + @Test + public void whenAllAuditFieldsArePopulated_ShouldReturnAssertTrue_onEachMACField() throws UnknownHostException { + + String uuid = UUID.randomUUID().toString(); + String hostName = InetAddress.getByName(hostAddress).getCanonicalHostName(); + String hostAddress = InetAddress.getLocalHost().getHostAddress(); + + auditLog.clear() + .startTimer() + .stopTimer() + .setKeyRequestId(uuid) + .setInstanceUUID(INSTANCE_UUID) + .setRemoteHost(MDC_REMOTE_HOST) + .setServiceName(SERVICE_NAME) + .setResponseCode(DATA_ERROR) + .setStatusCodeByResponseCode("201") + .setResponseDesc(RESPONSE_DESCRIPTION) + .setPartnerName(PARTNER_NAME) + + .setOptClassName(LoggerAuditTest.class.toString()) + .setOptAlertSeverity(Severity.CRITICAL) + .setOptProcessKey(MDC_PROCESS_KEY) + .setOptServiceInstanceId(MDC_SERVICE_INSTANCE_ID) + .log(LogLevel.DEBUG, ""); + + + Assert.assertFalse(LogFieldsMdcHandler.getInstance().isMDCParamEmpty(ENTRY_TIMESTAMP)); + Assert.assertFalse(LogFieldsMdcHandler.getInstance().isMDCParamEmpty(MDC_END_TIMESTAMP)); + Assert.assertFalse(LogFieldsMdcHandler.getInstance().isMDCParamEmpty(MDC_ELAPSED_TIME)); + + Assert.assertEquals(MDC.get(MDC_SERVER_IP_ADDRESS), hostAddress); + Assert.assertEquals(MDC.get(SERVER_FQDN), hostName); + Assert.assertEquals(MDC.get(MDC_REMOTE_HOST), MDC_REMOTE_HOST); + Assert.assertEquals(MDC.get(RESPONSE_STATUS_CODE), ONAPLogConstants.ResponseStatus.COMPLETE.name()); + + Assert.assertEquals(MDC.get(REQUEST_ID), uuid); + Assert.assertEquals(MDC.get(SERVICE_NAME), SERVICE_NAME); + Assert.assertEquals(MDC.get(PARTNER_NAME), PARTNER_NAME); + Assert.assertEquals(MDC.get(RESPONSE_CODE), String.valueOf(DATA_ERROR.getErrorCode())); + Assert.assertEquals(MDC.get(RESPONSE_DESCRIPTION), RESPONSE_DESCRIPTION); + Assert.assertEquals(MDC.get(INSTANCE_UUID), INSTANCE_UUID); + Assert.assertEquals(MDC.get(MDC_CLASS_NAME), LoggerAuditTest.class.toString()); + + Assert.assertEquals(MDC.get(RESPONSE_SEVERITY), String.valueOf(Severity.CRITICAL.getSeverityType())); + Assert.assertEquals(MDC.get(MDC_PROCESS_KEY), MDC_PROCESS_KEY); + Assert.assertEquals(MDC.get(MDC_SERVICE_INSTANCE_ID), MDC_SERVICE_INSTANCE_ID); + } +} diff --git a/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerBaseTest.java b/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerBaseTest.java new file mode 100644 index 0000000000..91e1aab267 --- /dev/null +++ b/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerBaseTest.java @@ -0,0 +1,142 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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.sdc.common.log.elements; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.openecomp.sdc.common.log.enums.ConstantsLogging; + +import javax.servlet.http.HttpServletRequest; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class LoggerBaseTest { + + @Mock + HttpServletRequest httpServletRequest; + + private static final String ONAP_REQ_ID_VALUE = "onapReqId"; + private static final String REQ_ID_VALUE = "reqId"; + private static final String TRANSACTION_RE_IQ_VALUE = "transactionReqId"; + private static final String ECOMP_REQ_ID_VALUE = "ecompReqId"; + private static final String USER_ID_VALUE = "userId"; + private static final String ONAP_PARTNER_NAME_VALUE = "partnerName"; + private static final String USER_UGENT = "userAgent"; + + @Test + public void testGetRequestIfFromOnapHeader() { + when(httpServletRequest.getHeader(ONAPLogConstants.Headers.REQUEST_ID)).thenReturn(ONAP_REQ_ID_VALUE); + when(httpServletRequest.getHeader(ConstantsLogging.X_REQUEST_ID)).thenReturn(REQ_ID_VALUE); + when(httpServletRequest.getHeader(ConstantsLogging.X_TRANSACTION_ID_HEADER)).thenReturn(TRANSACTION_RE_IQ_VALUE); + when(httpServletRequest.getHeader(ConstantsLogging.X_ECOMP_REQUEST_ID_HEADER)).thenReturn(ECOMP_REQ_ID_VALUE); + + String requestId = LoggerBase.getRequestId(httpServletRequest); + assertThat(requestId).isEqualTo(ONAP_REQ_ID_VALUE); + } + + @Test + public void testGetRequestIfFromReqIdHeader() { + when(httpServletRequest.getHeader(ONAPLogConstants.Headers.REQUEST_ID)).thenReturn(null); + when(httpServletRequest.getHeader(ConstantsLogging.X_REQUEST_ID)).thenReturn(REQ_ID_VALUE); + when(httpServletRequest.getHeader(ConstantsLogging.X_TRANSACTION_ID_HEADER)).thenReturn(TRANSACTION_RE_IQ_VALUE); + when(httpServletRequest.getHeader(ConstantsLogging.X_ECOMP_REQUEST_ID_HEADER)).thenReturn(ECOMP_REQ_ID_VALUE); + + String requestId = LoggerBase.getRequestId(httpServletRequest); + assertThat(requestId).isEqualTo(REQ_ID_VALUE); + } + + @Test + public void testGetRequestIfFromTransactionIdHeader() { + when(httpServletRequest.getHeader(ONAPLogConstants.Headers.REQUEST_ID)).thenReturn(null); + when(httpServletRequest.getHeader(ConstantsLogging.X_REQUEST_ID)).thenReturn(null); + when(httpServletRequest.getHeader(ConstantsLogging.X_TRANSACTION_ID_HEADER)).thenReturn(TRANSACTION_RE_IQ_VALUE); + when(httpServletRequest.getHeader(ConstantsLogging.X_ECOMP_REQUEST_ID_HEADER)).thenReturn(ECOMP_REQ_ID_VALUE); + + String requestId = LoggerBase.getRequestId(httpServletRequest); + assertThat(requestId).isEqualTo(TRANSACTION_RE_IQ_VALUE); + } + + @Test + public void testGetRequestIfFromEcompIdHeader() { + when(httpServletRequest.getHeader(ONAPLogConstants.Headers.REQUEST_ID)).thenReturn(null); + when(httpServletRequest.getHeader(ConstantsLogging.X_REQUEST_ID)).thenReturn(null); + when(httpServletRequest.getHeader(ConstantsLogging.X_TRANSACTION_ID_HEADER)).thenReturn(null); + when(httpServletRequest.getHeader(ConstantsLogging.X_ECOMP_REQUEST_ID_HEADER)).thenReturn(ECOMP_REQ_ID_VALUE); + + String requestId = LoggerBase.getRequestId(httpServletRequest); + assertThat(requestId).isEqualTo(ECOMP_REQ_ID_VALUE); + } + + @Test + public void testGetRequestIfFromRandonHeader() { + when(httpServletRequest.getHeader(ONAPLogConstants.Headers.REQUEST_ID)).thenReturn(null); + when(httpServletRequest.getHeader(ConstantsLogging.X_REQUEST_ID)).thenReturn(null); + when(httpServletRequest.getHeader(ConstantsLogging.X_TRANSACTION_ID_HEADER)).thenReturn(null); + when(httpServletRequest.getHeader(ConstantsLogging.X_ECOMP_REQUEST_ID_HEADER)).thenReturn(null); + + String requestId = LoggerBase.getRequestId(httpServletRequest); + assertThat(requestId).isNotEmpty(); + } + + @Test + public void testPartnerNameFromUserHeader() { + when(httpServletRequest.getHeader(ConstantsLogging.USER_ID_HEADER)).thenReturn(USER_ID_VALUE); + when(httpServletRequest.getHeader(ConstantsLogging.USER_AGENT_HEADER)).thenReturn(USER_UGENT); + when(httpServletRequest.getHeader(ONAPLogConstants.Headers.PARTNER_NAME)).thenReturn(ONAP_PARTNER_NAME_VALUE); + + String partnerName = LoggerBase.getPartnerName(httpServletRequest); + assertThat(partnerName).isEqualTo(USER_ID_VALUE); + } + + @Test + public void testPartnerNameFromOnapPartnerNameHeader() { + when(httpServletRequest.getHeader(ConstantsLogging.USER_ID_HEADER)).thenReturn(null); + when(httpServletRequest.getHeader(ONAPLogConstants.Headers.PARTNER_NAME)).thenReturn(ONAP_PARTNER_NAME_VALUE); + + String partnerName = LoggerBase.getPartnerName(httpServletRequest); + assertThat(partnerName).isEqualTo(ONAP_PARTNER_NAME_VALUE); + } + + @Test + public void testPartnerNameFromReqUriHeader() { + when(httpServletRequest.getHeader(ConstantsLogging.USER_ID_HEADER)).thenReturn(null); + when(httpServletRequest.getHeader(ONAPLogConstants.Headers.PARTNER_NAME)).thenReturn(null); + when(httpServletRequest.getHeader(ConstantsLogging.USER_AGENT_HEADER)).thenReturn(USER_UGENT); + + String partnerName = LoggerBase.getPartnerName(httpServletRequest); + assertThat(partnerName).isEqualTo(USER_UGENT); + } + + @Test + public void testPartnerNameUnknown() { + when(httpServletRequest.getHeader(ConstantsLogging.USER_ID_HEADER)).thenReturn(null); + when(httpServletRequest.getHeader(ONAPLogConstants.Headers.PARTNER_NAME)).thenReturn(null); + when(httpServletRequest.getHeader(ConstantsLogging.USER_AGENT_HEADER)).thenReturn(null); + + String partnerName = LoggerBase.getPartnerName(httpServletRequest); + assertThat(partnerName).isEqualTo(ConstantsLogging.PartnerName_Unknown); + } +} diff --git a/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerDebugTest.java b/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerDebugTest.java new file mode 100644 index 0000000000..020b55cba6 --- /dev/null +++ b/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerDebugTest.java @@ -0,0 +1,107 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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.sdc.common.log.elements; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.openecomp.sdc.common.log.enums.LogLevel; +import org.openecomp.sdc.common.log.utils.LoggingThreadLocalsHolder; +import org.slf4j.Logger; +import org.slf4j.MDC; + +import java.net.UnknownHostException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE; +import static org.openecomp.sdc.common.log.api.LogConfigurationConstants.*; + +@RunWith(MockitoJUnitRunner.class) +public class LoggerDebugTest { + + @Mock + private Logger logger; + + private LoggerDebug debugLog; + + @Before + public void init() { + debugLog = new LoggerDebug(LogFieldsMdcHandler.getInstance(), logger); + LoggingThreadLocalsHolder.setUuid(null); + MDC.clear(); + } + + @Test + public void whenNoFieldsIsPopulated_RequestedMdcFieldsAreEmpty() { + debugLog.clear() + .log(LogLevel.DEBUG, "some error code"); + assertNull(MDC.get(ONAPLogConstants.MDCs.REQUEST_ID)); + } + + @Test + public void debugLogCheckValidationValidFieldsTest() { + debugLog.clear() + .startTimer() + .setKeyRequestId("uuid") + .log(LogLevel.DEBUG, "some error code"); + + assertEquals(MDC.get(ONAPLogConstants.MDCs.REQUEST_ID), "uuid"); + } + + @Test + public void whenOnlyDebugUUIDFieldsIsPopulated_ShouldReturnAssertTrue_onUUIDFieldCheck() { + debugLog.clear() + .setKeyRequestId("uuid") + .log(LogLevel.DEBUG, "some error code"); + + assertEquals("uuid", MDC.get(ONAPLogConstants.MDCs.REQUEST_ID)); + } + + @Test + public void whenAllDebugFieldsArePopulated_ShouldReturnAssertTrue_onEachMACFieldCheck() throws UnknownHostException { + debugLog.clear() + .startTimer() + .setKeyRequestId(ONAPLogConstants.MDCs.REQUEST_ID) + .log(LogLevel.DEBUG, "some message"); + + Assert.assertTrue(LogFieldsMdcHandler.getInstance().isMDCParamEmpty(MDC_END_TIMESTAMP)); + Assert.assertTrue(LogFieldsMdcHandler.getInstance().isMDCParamEmpty(MDC_ELAPSED_TIME)); + Assert.assertTrue(LogFieldsMdcHandler.getInstance().isMDCParamEmpty(RESPONSE_STATUS_CODE)); + } + + + @Test + public void validateMandatoryFields(){ + assertEquals(ONAPLogConstants.MDCs.REQUEST_ID, debugLog.checkMandatoryFieldsExistInMDC().trim()); + } + + @Test + public void validateMandatoryFieldsWhenFieldIsSet(){ + debugLog.clear() + .setKeyRequestId("1234"); + assertEquals("", debugLog.checkMandatoryFieldsExistInMDC()); + } +} diff --git a/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerErrorTest.java b/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerErrorTest.java new file mode 100644 index 0000000000..06376ed48f --- /dev/null +++ b/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerErrorTest.java @@ -0,0 +1,92 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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.sdc.common.log.elements; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; +import org.openecomp.sdc.common.log.enums.LogLevel; +import org.openecomp.sdc.common.log.utils.EcompLogErrorCode; +import org.openecomp.sdc.common.log.utils.LoggingThreadLocalsHolder; +import org.slf4j.Logger; +import org.slf4j.MDC; + +import static org.junit.Assert.assertEquals; +import static org.openecomp.sdc.common.log.api.LogConfigurationConstants.MDC_ERROR_CODE; + +@RunWith(MockitoJUnitRunner.class) +public class LoggerErrorTest { + private LoggerError errorLog; + + @Mock + private Logger logger; + @Before + public void init() { + errorLog = LoggerFactory.getMdcLogger(LoggerError.class, logger); + MDC.clear(); + } + + @Test + public void allFieldsArePresentTest() { + LoggingThreadLocalsHolder.setUuid("uuid"); + errorLog.log(LogLevel.ERROR, EcompLoggerErrorCode.AVAILABILITY_TIMEOUTS_ERROR, "service", "entity", "server error"); + + assertEquals(MDC.get(MDC_ERROR_CODE), String.valueOf(EcompLoggerErrorCode.AVAILABILITY_TIMEOUTS_ERROR.getErrorCode())); + assertEquals("uuid", MDC.get(ONAPLogConstants.MDCs.REQUEST_ID)); + assertEquals("entity", MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); + assertEquals("service", MDC.get(ONAPLogConstants.MDCs.SERVICE_NAME)); + } + + @Test + public void missingFieldsTest() { + errorLog.clear() + .log(LogLevel.ERROR,"some message"); + } + + @Test + public void convertEcompErrorForLogging_correctName() { + assertEquals(EcompLoggerErrorCode.AVAILABILITY_TIMEOUTS_ERROR, EcompLoggerErrorCode.getByValue(EcompLogErrorCode.E_210.name())); + } + + @Test + public void convertEcompErrorForLogging_correctName_2() { + assertEquals(EcompLoggerErrorCode.DATA_ERROR, EcompLoggerErrorCode.getByValue(EcompLogErrorCode.E_399.name())); + } + + @Test + public void convertEcompErrorForLogging_NotConvertable() { + assertEquals(EcompLoggerErrorCode.UNKNOWN_ERROR, EcompLoggerErrorCode.getByValue("ABC")); + } + + @Test + public void convertEcompErrorForLogging_NotConvertable_2() { + assertEquals(EcompLoggerErrorCode.UNKNOWN_ERROR, EcompLoggerErrorCode.getByValue("E_ABC")); + } + + @Test + public void convertEcompErrorForLogging_Success() { + assertEquals(EcompLoggerErrorCode.SUCCESS, EcompLoggerErrorCode.getByValue("E_0")); + } +} diff --git a/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerMetricTest.java b/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerMetricTest.java new file mode 100644 index 0000000000..3bd1afcce9 --- /dev/null +++ b/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerMetricTest.java @@ -0,0 +1,122 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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.sdc.common.log.elements; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.common.log.enums.LogLevel; +import org.openecomp.sdc.common.log.utils.LoggingThreadLocalsHolder; +import org.slf4j.Logger; +import org.slf4j.MDC; + +import javax.ws.rs.core.Response; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.UUID; + +import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.*; +import static org.onap.logging.ref.slf4j.ONAPLogConstants.ResponseStatus.COMPLETE; +import static org.openecomp.sdc.common.log.api.LogConfigurationConstants.*; +import static org.openecomp.sdc.common.log.elements.LogFieldsMdcHandler.hostAddress; + +/** + * Created by dd4296 on 12/31/2017. + */ +@RunWith(MockitoJUnitRunner.class) +public class LoggerMetricTest { + @Mock + private Logger logger; + + @Mock + Response.StatusType statusType; + + private LoggerMetric metricLog; + + @Before + public void init() { + metricLog = new LoggerMetric(LogFieldsMdcHandler.getInstance(), logger); + } + + @After + public void tearDown() { + MDC.clear(); + LoggingThreadLocalsHolder.setUuid(null); + } + + @Test + public void whenNoMetricFieldsArePopulated_ShouldReturnassertEquals_onMdcMap() { + metricLog.clear() + .log(LogLevel.DEBUG, "some error code"); + Assert.assertNotNull(MDC.get(SERVER_FQDN)); + Assert.assertNotNull(MDC.get(MDC_SERVER_IP_ADDRESS)); + } + + @Test + public void whenAllMetricFieldsArePopulated_ShouldReturnassertEquals_onEachMACField() throws UnknownHostException { + String uuid = UUID.randomUUID().toString(); + LoggingThreadLocalsHolder.setUuid(uuid); + + String hostName = InetAddress.getByName(hostAddress).getCanonicalHostName(); + String hostAddress = InetAddress.getLocalHost().getHostAddress(); + + metricLog.clear() + .startTimer() + .stopTimer() + .setInstanceUUID(INSTANCE_UUID) + .setRemoteHost(MDC_REMOTE_HOST) + .setServiceName(SERVICE_NAME) + .setResponseCode(500) + .setStatusCode(COMPLETE.name()) + .setResponseDesc(RESPONSE_DESCRIPTION) + .setPartnerName(PARTNER_NAME) + .setOptClassName(LoggerMetricTest.class.toString()) + .setOptServiceInstanceId(MDC_SERVICE_INSTANCE_ID) + .setTargetEntity(TARGET_ENTITY) + .setTargetServiceName(TARGET_SERVICE_NAME) + .setTargetVirtualEntity(MDC_TARGET_VIRTUAL_ENTITY) + .log(LogLevel.DEBUG, ""); + + + Assert.assertFalse(LogFieldsMdcHandler.getInstance().isMDCParamEmpty(INVOKE_TIMESTAMP)); + Assert.assertFalse(LogFieldsMdcHandler.getInstance().isMDCParamEmpty(MDC_END_TIMESTAMP)); + Assert.assertFalse(LogFieldsMdcHandler.getInstance().isMDCParamEmpty(MDC_ELAPSED_TIME)); + Assert.assertEquals(MDC.get(MDC_SERVER_IP_ADDRESS),hostAddress); + Assert.assertEquals(MDC.get(SERVER_FQDN), hostName); + Assert.assertEquals(MDC.get(MDC_REMOTE_HOST), MDC_REMOTE_HOST); + Assert.assertEquals(MDC.get(RESPONSE_STATUS_CODE) , "COMPLETE"); + Assert.assertEquals(MDC.get(REQUEST_ID), uuid); + Assert.assertEquals(MDC.get(SERVICE_NAME) , SERVICE_NAME); + Assert.assertEquals(MDC.get(PARTNER_NAME) , PARTNER_NAME); + Assert.assertEquals(MDC.get(RESPONSE_CODE) ,"500"); + Assert.assertEquals(MDC.get(RESPONSE_DESCRIPTION) , RESPONSE_DESCRIPTION); + Assert.assertEquals(MDC.get(INSTANCE_UUID) , INSTANCE_UUID); + Assert.assertEquals(MDC.get(MDC_CLASS_NAME) ,LoggerMetricTest.class.toString()); + Assert.assertEquals(MDC.get(MDC_SERVICE_INSTANCE_ID) ,MDC_SERVICE_INSTANCE_ID); + Assert.assertEquals(MDC.get(TARGET_ENTITY) , TARGET_ENTITY); + Assert.assertEquals(MDC.get(TARGET_SERVICE_NAME) , TARGET_SERVICE_NAME); + Assert.assertEquals(MDC.get(MDC_TARGET_VIRTUAL_ENTITY) ,MDC_TARGET_VIRTUAL_ENTITY); + } +} diff --git a/common-app-logging/src/test/java/org/openecomp/sdc/common/log/wrappers/LoggerTest.java b/common-app-logging/src/test/java/org/openecomp/sdc/common/log/wrappers/LoggerTest.java new file mode 100644 index 0000000000..fd66efffc7 --- /dev/null +++ b/common-app-logging/src/test/java/org/openecomp/sdc/common/log/wrappers/LoggerTest.java @@ -0,0 +1,378 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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.sdc.common.log.wrappers; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.openecomp.sdc.common.log.api.LogConfigurationConstants; +import org.openecomp.sdc.common.log.elements.ErrorLogOptionalData; +import org.openecomp.sdc.common.log.elements.LoggerError; +import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; +import org.openecomp.sdc.common.log.enums.LogLevel; +import org.openecomp.sdc.common.log.enums.Severity; +import org.openecomp.sdc.common.log.utils.LoggingThreadLocalsHolder; +import org.slf4j.MDC; +import org.slf4j.Marker; +import org.slf4j.MarkerFactory; + +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; +import java.net.URI; +import java.net.URISyntaxException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; +import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.REQUEST_ID; +import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.SERVICE_NAME; +import static org.openecomp.sdc.common.log.api.LogConfigurationConstants.MDC_ERROR_CATEGORY; +import static org.openecomp.sdc.common.log.api.LogConfigurationConstants.MDC_ERROR_CODE; + +@RunWith(MockitoJUnitRunner.class) +public class LoggerTest { + + private final static String targetEntity = "DCEA"; + private final static String targetServiceName = "test target name"; + private final static String serviceName = "testService"; + private final static String message = "Logger message"; + private final static String exceptionMsg= "Exception testing"; + + @Mock + private org.slf4j.Logger logger; + @Mock + private ContainerRequestContext requestContext; + @Mock + private UriInfo uriInfo; + @Mock + private Response.StatusType statusType; + + @InjectMocks + private Logger commonLogger; + + @Captor + private ArgumentCaptor<String> captor; + + @Before + public void setUp() { + MDC.clear(); + } + + @Test + public void validateErrorLogWhenErrorSettingsProvided() { + when(logger.isErrorEnabled()).thenReturn(true); + commonLogger.error(EcompLoggerErrorCode.PERMISSION_ERROR, serviceName, targetEntity, message); + + verify(logger).error(any(Marker.class), captor.capture(), any(Object[].class)); + assertEquals(message, captor.getValue()); + assertEquals(String.valueOf(EcompLoggerErrorCode.PERMISSION_ERROR.getErrorCode()), MDC.get(LogConfigurationConstants.MDC_ERROR_CODE)); + assertEquals(LogLevel.ERROR.name(), MDC.get(LogConfigurationConstants.MDC_ERROR_CATEGORY)); + assertEquals(targetEntity, MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); + assertEquals(serviceName, MDC.get(SERVICE_NAME)); + } + + @Test + public void validateWarnMessageIsLoggedWhenAllErrorSettingsProvided() { + when(logger.isErrorEnabled()).thenReturn(true); + commonLogger.error(EcompLoggerErrorCode.AVAILABILITY_TIMEOUTS_ERROR, serviceName, targetEntity, message); + + verify(logger).error(any(Marker.class), captor.capture(), any(Object[].class)); + assertEquals(message, captor.getValue()); + assertEquals(String.valueOf(EcompLoggerErrorCode.AVAILABILITY_TIMEOUTS_ERROR.getErrorCode()), MDC.get(LogConfigurationConstants.MDC_ERROR_CODE)); + assertEquals(LogLevel.ERROR.name(), MDC.get(LogConfigurationConstants.MDC_ERROR_CATEGORY)); + assertEquals(targetEntity, MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); + assertEquals(serviceName, MDC.get(SERVICE_NAME)); + } + + @Test + public void validateFatalMessageIsLoggedWhenAllErrorSettingsProvided() { + when(logger.isErrorEnabled()).thenReturn(true); + commonLogger.fatal(EcompLoggerErrorCode.PERMISSION_ERROR, serviceName, targetEntity, message); + + verify(logger).error(any(Marker.class), captor.capture(), any(Object[].class)); + assertEquals(message, captor.getValue()); + assertEquals(String.valueOf(EcompLoggerErrorCode.PERMISSION_ERROR.getErrorCode()), MDC.get(LogConfigurationConstants.MDC_ERROR_CODE)); + assertEquals(LogLevel.FATAL.name(), MDC.get(LogConfigurationConstants.MDC_ERROR_CATEGORY)); + assertEquals(targetEntity, MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); + assertEquals(serviceName, MDC.get(SERVICE_NAME)); + } + + @Test + public void validateWarnMessage_AllErrorElements() { + when(logger.isWarnEnabled()).thenReturn(true); + ErrorLogOptionalData errorLogOptionalData = ErrorLogOptionalData.newBuilder() + .targetEntity(targetEntity) + .targetServiceName(targetServiceName).build(); + commonLogger.warn(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, serviceName,errorLogOptionalData, message); + verify(logger).warn(any(Marker.class), captor.capture(), any(Object[].class)); + assertEquals(message, captor.getValue()); + assertEquals(String.valueOf(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR.getErrorCode()), MDC.get(LogConfigurationConstants.MDC_ERROR_CODE)); + assertEquals(LogLevel.WARN.name(), MDC.get(LogConfigurationConstants.MDC_ERROR_CATEGORY)); + assertEquals(targetEntity, MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); + assertEquals(serviceName, MDC.get(SERVICE_NAME)); + assertEquals(targetServiceName, MDC.get(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME)); + } + + @Test + public void validateWarnMessage_emptyTargetEntity() { + when(logger.isWarnEnabled()).thenReturn(true); + ErrorLogOptionalData errorLogOptionalData = ErrorLogOptionalData.newBuilder() + .targetServiceName(targetServiceName).build(); + commonLogger.warn(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, serviceName,errorLogOptionalData, message); + verify(logger).warn(any(Marker.class), captor.capture(), any(Object[].class)); + assertEquals(message, captor.getValue()); + assertEquals(String.valueOf(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR.getErrorCode()), MDC.get(LogConfigurationConstants.MDC_ERROR_CODE)); + assertEquals(LogLevel.WARN.name(), MDC.get(LogConfigurationConstants.MDC_ERROR_CATEGORY)); + assertEquals(null, MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); + assertEquals(serviceName, MDC.get(SERVICE_NAME)); + assertEquals(targetServiceName, MDC.get(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME)); + } + + @Test + public void validateWarnMessage_emptyTargetServiceName() { + when(logger.isWarnEnabled()).thenReturn(true); + ErrorLogOptionalData errorLogOptionalData = ErrorLogOptionalData.newBuilder() + .targetEntity(targetEntity).build(); + commonLogger.warn(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, serviceName,errorLogOptionalData, message); + verify(logger).warn(any(Marker.class), captor.capture(), any(Object[].class)); + assertEquals(message, captor.getValue()); + assertEquals(String.valueOf(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR.getErrorCode()), MDC.get(LogConfigurationConstants.MDC_ERROR_CODE)); + assertEquals(LogLevel.WARN.name(), MDC.get(LogConfigurationConstants.MDC_ERROR_CATEGORY)); + assertEquals(targetEntity, MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); + assertEquals(serviceName, MDC.get(SERVICE_NAME)); + assertEquals(null, MDC.get(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME)); + } + + + @Test + public void validateErrorMessage_AllErrorElements() { + when(logger.isErrorEnabled()).thenReturn(true); + ErrorLogOptionalData errorLogOptionalData = ErrorLogOptionalData.newBuilder() + .targetEntity(targetEntity) + .targetServiceName(targetServiceName).build(); + commonLogger.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, serviceName,errorLogOptionalData, message); + verify(logger).error(any(Marker.class), captor.capture(), any(Object[].class)); + assertEquals(message, captor.getValue()); + assertEquals(String.valueOf(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR.getErrorCode()), MDC.get(LogConfigurationConstants.MDC_ERROR_CODE)); + assertEquals(LogLevel.ERROR.name(), MDC.get(LogConfigurationConstants.MDC_ERROR_CATEGORY)); + assertEquals(targetEntity, MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); + assertEquals(serviceName, MDC.get(SERVICE_NAME)); + assertEquals(targetServiceName, MDC.get(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME)); + } + + @Test + public void validateErrorMessage_emptyTargetEntity() { + when(logger.isErrorEnabled()).thenReturn(true); + ErrorLogOptionalData errorLogOptionalData = ErrorLogOptionalData.newBuilder() + .targetServiceName(targetServiceName).build(); + commonLogger.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, serviceName,errorLogOptionalData, message); + verify(logger).error(any(Marker.class), captor.capture(), any(Object[].class)); + assertEquals(message, captor.getValue()); + assertEquals(String.valueOf(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR.getErrorCode()), MDC.get(LogConfigurationConstants.MDC_ERROR_CODE)); + assertEquals(LogLevel.ERROR.name(), MDC.get(LogConfigurationConstants.MDC_ERROR_CATEGORY)); + assertEquals(null, MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); + assertEquals(serviceName, MDC.get(SERVICE_NAME)); + assertEquals(targetServiceName, MDC.get(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME)); + } + + @Test + public void validateErrorMessage_emptyTargetServiceName() { + when(logger.isErrorEnabled()).thenReturn(true); + ErrorLogOptionalData errorLogOptionalData = ErrorLogOptionalData.newBuilder() + .targetEntity(targetEntity).build(); + commonLogger.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, serviceName,errorLogOptionalData, message); + verify(logger).error(any(Marker.class), captor.capture(), any(Object[].class)); + assertEquals(message, captor.getValue()); + assertEquals(String.valueOf(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR.getErrorCode()), MDC.get(LogConfigurationConstants.MDC_ERROR_CODE)); + assertEquals(LogLevel.ERROR.name(), MDC.get(LogConfigurationConstants.MDC_ERROR_CATEGORY)); + assertEquals(targetEntity, MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); + assertEquals(serviceName, MDC.get(SERVICE_NAME)); + assertEquals(null, MDC.get(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME)); + } + + + + @Test + public void validateErrorMessageIsNotLoggedWhenErrorLevelIsDisabledEvenIfErrorSettingsProvided() { + commonLogger.error(EcompLoggerErrorCode.PERMISSION_ERROR, serviceName, targetEntity, message); + verify(logger, never()).error(any(Marker.class), any(String.class)); + } + + @Test + public void validateErrorLogWhenErrorSettingsProvidedPartially() { + when(logger.isErrorEnabled()).thenReturn(true); + commonLogger.error(message); + + verify(logger).error(any(Marker.class), eq(message), any(Object[].class)); + assertEquals(String.valueOf(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR.getErrorCode()), MDC.get(LogConfigurationConstants.MDC_ERROR_CODE)); + assertEquals(LogLevel.ERROR.name(), MDC.get(LogConfigurationConstants.MDC_ERROR_CATEGORY)); + assertNull(MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); + assertEquals(LoggerError.defaultServiceName, MDC.get(SERVICE_NAME)); + } + + @Test + public void errorMessageIsNotLoggedWhenErrorLevelIsDisabled() { + commonLogger.error(message); + verify(logger, times(0)).error(any(Marker.class), anyString()); + } + + @Test + public void traceMessageWithExceptionIsNotLoggedWhenTraceLevelIsDisabled() { + commonLogger.trace(message, new UnsupportedOperationException()); + verify(logger, times(0)).trace(any(Marker.class), anyString()); + } + + @Test + public void verifyInfoMessage() { + final String msg = "Info message"; + when(logger.isInfoEnabled()).thenReturn(true); + commonLogger.info(msg, new RuntimeException()); + verify(logger).info(any(Marker.class), anyString()); + } + + @Test + public void verifyWarnMessage() { + when(logger.isWarnEnabled()).thenReturn(true); + commonLogger.warn("Text"); + assertEquals(LogLevel.WARN.name(), MDC.get(MDC_ERROR_CATEGORY)); + assertEquals(String.valueOf(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR.getErrorCode()), MDC.get(MDC_ERROR_CODE)); + assertEquals(LoggerError.defaultServiceName, MDC.get(SERVICE_NAME)); + } + + @Test + public void validateErrorLogWithExceptionWhenErrorSettingsProvidedPartially() { + LoggingThreadLocalsHolder.setUuid("uuid"); + when(logger.isWarnEnabled()).thenReturn(true); + commonLogger.warn(message, new NullPointerException(exceptionMsg)); + + //the expected warn message + verify(logger).warn(any(Marker.class), contains(message), any(Object[].class)); + assertEquals(String.valueOf(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR.getErrorCode()), MDC.get(LogConfigurationConstants.MDC_ERROR_CODE)); + assertEquals(LogLevel.WARN.name(), MDC.get(LogConfigurationConstants.MDC_ERROR_CATEGORY)); + assertEquals("uuid", MDC.get(REQUEST_ID)); + assertNull(MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); + assertEquals(LoggerError.defaultServiceName, MDC.get(SERVICE_NAME)); + } + + + @Test + public void validateDebugLogWithException() { + final String msg = "Debug message"; + LoggingThreadLocalsHolder.setUuid("uuid"); + when(logger.isDebugEnabled()).thenReturn(true); + commonLogger.debug(msg, new RuntimeException()); + + verify(logger).debug(any(Marker.class), eq(msg), any(RuntimeException.class)); + } + + @Test + public void validateTraceLogWithExceptionAndPartialParamsAndDebugLevelDisabled() { + final String msg = "Debug message"; + when(logger.isTraceEnabled()).thenReturn(true); + commonLogger.trace(msg, new RuntimeException()); + + verify(logger).trace(any(Marker.class), eq(msg), any(RuntimeException.class)); + } + + @Test + public void warnMessageWithParameterIsNotLoggedIfWarnLevelIsDisabled() { + commonLogger.warn("msg", "param"); + verify(logger, times(0)).warn(any(Marker.class), + anyString(), any(Object.class)); + } + + @Test + public void verifyMdcValuesAreStoredWhenAuditAndErrorLoggersAreInvokedSequentially() throws URISyntaxException { + final String uuid = "12345"; + final String messageInt = "message"; + when(requestContext.getHeaderString(anyString())).thenReturn("ab2222"); + when(requestContext.getUriInfo()).thenReturn(uriInfo); + when(logger.isErrorEnabled()).thenReturn(true); + + URI uri = new URI("http:/abc.com/getId"); + when(uriInfo.getRequestUri()).thenReturn(uri); + when(uriInfo.getBaseUri()).thenReturn(uri); + when(statusType.getStatusCode()).thenReturn(200); + when(statusType.getReasonPhrase()).thenReturn("OK"); + LoggerSdcAudit audit = new LoggerSdcAudit(this.getClass()); + LoggingThreadLocalsHolder.setUuid(uuid); + audit.startLog(requestContext); + audit.logExit("abc.log.com", requestContext, statusType, LogLevel.INFO, Severity.OK, messageInt, + MarkerFactory.getMarker(ONAPLogConstants.Markers.EXIT.getName())); + + commonLogger.error(messageInt); + verify(logger).error(any(Marker.class), eq(messageInt), any(Object[].class)); + assertEquals(uuid, MDC.get(REQUEST_ID)); + assertEquals("/", MDC.get(SERVICE_NAME)); + assertEquals(LogLevel.ERROR.name(), MDC.get(MDC_ERROR_CATEGORY)); + assertEquals(String.valueOf(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR.getErrorCode()), MDC.get(MDC_ERROR_CODE)); + } + + @Test + public void verifyLoggerDoesNothingWhenTheLevelIsNotSet() { + if (commonLogger.isDebugEnabled()) { + commonLogger.debug("text"); + } + verify(logger, times(0)).debug(any(Marker.class), anyString(), eq((Object[])null)); + } + + @Test + public void verifyLoggerTraceMethodIsCalledWhenTheLevelIsSet() { + LoggingThreadLocalsHolder.setUuid("1234"); + when(logger.isTraceEnabled()).thenReturn(true); + if (commonLogger.isTraceEnabled()) { + commonLogger.trace("text"); + } + verify(logger, times(1)).trace(any(Marker.class), anyString(), eq((Object[])null)); + } + + + @Test + public void verifyMdcValuesAreStoredWhenTraceLoggerIsInvokedAfterAuditStart() throws URISyntaxException { + final String uuid = "12345"; + final String messageInt = "message"; + when(requestContext.getHeaderString(anyString())).thenReturn("ab2222"); + when(requestContext.getUriInfo()).thenReturn(uriInfo); + when(logger.isTraceEnabled()).thenReturn(true); + + URI uri = new URI("http:/abc.com/getId"); + when(uriInfo.getRequestUri()).thenReturn(uri); + when(uriInfo.getBaseUri()).thenReturn(uri); + LoggerSdcAudit audit = new LoggerSdcAudit(this.getClass()); + LoggingThreadLocalsHolder.setUuid(uuid); + audit.startLog(requestContext); + + commonLogger.trace(messageInt); + verify(logger).trace(any(Marker.class), captor.capture(), eq((Object[])null)); + assertEquals(messageInt, captor.getValue()); + assertEquals(uuid, MDC.get(REQUEST_ID)); + } + + +} |