From b92b1f86492d1fb0e546ef5124116abdf2d07dc9 Mon Sep 17 00:00:00 2001 From: "Smokowski, Steve (ss835w)" Date: Thu, 30 Aug 2018 19:06:46 -0400 Subject: Update Logging Add CXF interceptor for SOAP based logging Clean up extra logging statements Add UT to ensure MDC properly populated Change package name on Jax-RS Filter to be more accurate Issue-ID: SO-947 Change-Id: I3a2afc58de3bf370675658ce3d19cf899b90def7 Change-Id: I3a2afc58de3bf370675658ce3d19cf899b90def7 Signed-off-by: Smokowski, Steve (ss835w) --- .../main/java/org/onap/so/client/RestClient.java | 2 +- .../java/org/onap/so/exceptions/MSOException.java | 36 ++++ .../main/java/org/onap/so/logger/MsoLogger.java | 36 ++-- .../cxf/interceptor/SOAPLoggingInInterceptor.java | 96 ++++++++++ .../cxf/interceptor/SOAPLoggingOutInterceptor.java | 63 +++++++ .../logging/jaxrs/filter/JaxRsClientLogging.java | 135 ++++++++++++++ .../logging/jaxrs/filter/JaxRsFilterLogging.java | 169 ++++++++++++++++++ .../org/onap/so/logging/jaxrs/filter/MDCSetup.java | 51 ++++++ .../logging/jaxrs/filter/SpringClientFilter.java | 67 +++++++ .../jaxrs/filter/jersey/JaxRsClientLogging.java | 135 -------------- .../jaxrs/filter/jersey/JaxRsFilterLogging.java | 195 --------------------- .../jaxrs/filter/jersey/SpringClientFilter.java | 67 ------- 12 files changed, 642 insertions(+), 410 deletions(-) create mode 100644 common/src/main/java/org/onap/so/exceptions/MSOException.java create mode 100644 common/src/main/java/org/onap/so/logging/cxf/interceptor/SOAPLoggingInInterceptor.java create mode 100644 common/src/main/java/org/onap/so/logging/cxf/interceptor/SOAPLoggingOutInterceptor.java create mode 100644 common/src/main/java/org/onap/so/logging/jaxrs/filter/JaxRsClientLogging.java create mode 100644 common/src/main/java/org/onap/so/logging/jaxrs/filter/JaxRsFilterLogging.java create mode 100644 common/src/main/java/org/onap/so/logging/jaxrs/filter/MDCSetup.java create mode 100644 common/src/main/java/org/onap/so/logging/jaxrs/filter/SpringClientFilter.java delete mode 100644 common/src/main/java/org/onap/so/logging/jaxrs/filter/jersey/JaxRsClientLogging.java delete mode 100644 common/src/main/java/org/onap/so/logging/jaxrs/filter/jersey/JaxRsFilterLogging.java delete mode 100644 common/src/main/java/org/onap/so/logging/jaxrs/filter/jersey/SpringClientFilter.java (limited to 'common/src/main/java') diff --git a/common/src/main/java/org/onap/so/client/RestClient.java b/common/src/main/java/org/onap/so/client/RestClient.java index 0f4bbea03c..cb8e1f0a91 100644 --- a/common/src/main/java/org/onap/so/client/RestClient.java +++ b/common/src/main/java/org/onap/so/client/RestClient.java @@ -50,7 +50,7 @@ import javax.ws.rs.core.UriBuilder; import org.onap.so.client.policy.CommonObjectMapperProvider; import org.onap.so.client.policy.LoggingFilter; import org.onap.so.logger.MsoLogger; -import org.onap.so.logging.jaxrs.filter.jersey.JaxRsClientLogging; +import org.onap.so.logging.jaxrs.filter.JaxRsClientLogging; import org.onap.so.utils.CryptoUtils; import org.onap.so.utils.TargetEntity; import org.slf4j.MDC; diff --git a/common/src/main/java/org/onap/so/exceptions/MSOException.java b/common/src/main/java/org/onap/so/exceptions/MSOException.java new file mode 100644 index 0000000000..c4be075cf0 --- /dev/null +++ b/common/src/main/java/org/onap/so/exceptions/MSOException.java @@ -0,0 +1,36 @@ +package org.onap.so.exceptions; + + +public class MSOException extends Exception{ + /** + * + */ + private static final long serialVersionUID = 4563920496855255206L; + private Integer errorCode; + + public MSOException(String msg){ + super(msg); + } + + public MSOException (Throwable e) { + super(e); + } + + public MSOException (String msg, Throwable e) { + super (msg, e); + } + + public MSOException(String msg, int errorCode){ + super(msg); + this.errorCode=errorCode; + } + + public MSOException(String msg, int errorCode, Throwable t){ + super(msg,t); + this.errorCode=errorCode; + } + + public Integer getErrorCode(){ + return errorCode; + } +} diff --git a/common/src/main/java/org/onap/so/logger/MsoLogger.java b/common/src/main/java/org/onap/so/logger/MsoLogger.java index e4cac067ba..3ef01f5216 100644 --- a/common/src/main/java/org/onap/so/logger/MsoLogger.java +++ b/common/src/main/java/org/onap/so/logger/MsoLogger.java @@ -60,13 +60,26 @@ public class MsoLogger { public static final String RESPONSECODE = "ResponseCode"; public static final String RESPONSEDESC = "ResponseDesc"; public static final String FQDN = "ServerFQDN"; + public static final String ENTRY_TIMESTAMP = "EntryTimestamp"; + public static final String CLIENT_IPADDRESS = "EntryTimestamp"; - public static final String SERVICE_INSTANCE_ID = "ServiceInstanceId"; + //HTTP Headers + public static final String HEADER_FROM_APP_ID = "X-FromAppId"; + public static final String ONAP_PARTNER_NAME = "X-ONAP-PartnerName"; + public static final String HEADER_REQUEST_ID = "X-RequestId"; + public static final String TRANSACTION_ID = "X-TransactionID"; + public static final String ECOMP_REQUEST_ID = "X-ECOMP-RequestID"; + public static final String ONAP_REQUEST_ID = "X-ONAP-RequestID"; + public static final String CLIENT_ID = "X-ClientID"; + public static final String INVOCATION_ID_HEADER = "X-InvocationID"; + //Default values for not found + public static final String UNKNOWN_PARTNER = "UnknownPartner"; + + public static final String SERVICE_INSTANCE_ID = "ServiceInstanceId"; public static final String SERVICE_NAME_IS_METHOD_NAME = "ServiceNameIsMethodName"; - public static final String SERVER_IP = "ServerIPAddress"; - + public static final String SERVER_IP = "ServerIPAddress"; public static final String REMOTE_HOST = "RemoteHost"; public static final String ALERT_SEVERITY = "AlertSeverity"; @@ -77,16 +90,15 @@ public class MsoLogger { public static final String CAT_LOG_LEVEL = "CategoryLogLevel"; public static final String AUDI_CAT_LOG_LEVEL = "AuditCategoryLogLevel"; - //For getting an identity of calling application - public static final String HEADER_FROM_APP_ID = "X-FromAppId"; - public static final String FROM_APP_ID = "FromAppId"; - public static final String HEADER_REQUEST_ID = "X-RequestId"; - public static final String TRANSACTION_ID = "X-TransactionID"; - public static final String ECOMP_REQUEST_ID = "X-ECOMP-RequestID"; - public static final String ONAP_REQUEST_ID = "X-ONAP-RequestID"; + + + public static final String PARTNER_NAME = "PartnerName"; + - public static final String CLIENT_ID = "X-ClientID"; - public static final String INVOCATION_ID_HEADER = "X-InvocationID"; + + + + // Audit/Metric log specific public static final String BEGINTIME = "BeginTimestamp"; diff --git a/common/src/main/java/org/onap/so/logging/cxf/interceptor/SOAPLoggingInInterceptor.java b/common/src/main/java/org/onap/so/logging/cxf/interceptor/SOAPLoggingInInterceptor.java new file mode 100644 index 0000000000..9aed537668 --- /dev/null +++ b/common/src/main/java/org/onap/so/logging/cxf/interceptor/SOAPLoggingInInterceptor.java @@ -0,0 +1,96 @@ +package org.onap.so.logging.cxf.interceptor; + + +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.stream.Collectors; +import javax.servlet.http.HttpServletRequest; +import javax.xml.namespace.QName; +import org.apache.cxf.binding.soap.SoapMessage; +import org.apache.cxf.binding.soap.interceptor.AbstractSoapInterceptor; +import org.apache.cxf.interceptor.Fault; +import org.apache.cxf.message.Message; +import org.apache.cxf.phase.Phase; +import org.apache.cxf.service.model.MessageInfo; +import org.apache.cxf.service.model.OperationInfo; +import org.apache.cxf.transport.http.AbstractHTTPDestination; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.onap.so.logging.jaxrs.filter.JaxRsFilterLogging; +import org.onap.so.logging.jaxrs.filter.MDCSetup; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class SOAPLoggingInInterceptor extends AbstractSoapInterceptor{ + + protected static Logger logger = LoggerFactory.getLogger(SOAPLoggingInInterceptor.class); + + @Autowired + MDCSetup mdcSetup; + + public SOAPLoggingInInterceptor() { + super(Phase.READ); + } + + @Override + public void handleMessage(SoapMessage message) throws Fault { + try { + + Map> headers = (Map>) message.get(Message.PROTOCOL_HEADERS); + HttpServletRequest request = (HttpServletRequest)message.get(AbstractHTTPDestination.HTTP_REQUEST); + request.getRemoteAddr(); + + setRequestId(headers); + setInvocationId(headers); + setServiceName(message); + setMDCPartnerName(headers); + mdcSetup.setServerFQDN(); + mdcSetup.setClientIPAddress(request); + mdcSetup.setInstanceUUID(); + mdcSetup.setEntryTimeStamp(); + MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, "INPROGRESS"); + logger.info(ONAPLogConstants.Markers.ENTRY, "Entering"); + } catch (Exception e) { + logger.warn("Error in incoming SOAP Message Inteceptor", e); + } + } + + private void setServiceName(SoapMessage message) { + String requestURI = (String) message.get(Message.REQUEST_URI); + MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, requestURI); + } + + //CXF Appears to flatten headers to lower case + private void setMDCPartnerName(Map> headers){ + String partnerName=getValueOrDefault(headers, ONAPLogConstants.Headers.PARTNER_NAME.toLowerCase(),""); + MDC.put(ONAPLogConstants.MDCs.PARTNER_NAME,partnerName); + } + + private void setInvocationId(Map> headers) { + String invocationId=getValueOrDefault(headers, ONAPLogConstants.Headers.INVOCATION_ID.toLowerCase(),UUID.randomUUID().toString()); + MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, invocationId); + } + + private void setRequestId(Map> headers) { + String requestId=getValueOrDefault(headers, ONAPLogConstants.Headers.REQUEST_ID.toLowerCase(),UUID.randomUUID().toString()); + MDC.put(ONAPLogConstants.MDCs.REQUEST_ID,requestId); + } + + private String getValueOrDefault(Map> headers, String headerName, String defaultValue){ + String headerValue; + List headerList=headers.get(headerName); + if(headerList != null && !headerList.isEmpty()){ + headerValue= headerList.get(0); + if(headerValue == null || headerValue.isEmpty()) + headerValue = defaultValue; + }else + headerValue = defaultValue; + return headerValue; + } + +} diff --git a/common/src/main/java/org/onap/so/logging/cxf/interceptor/SOAPLoggingOutInterceptor.java b/common/src/main/java/org/onap/so/logging/cxf/interceptor/SOAPLoggingOutInterceptor.java new file mode 100644 index 0000000000..c50e505cd8 --- /dev/null +++ b/common/src/main/java/org/onap/so/logging/cxf/interceptor/SOAPLoggingOutInterceptor.java @@ -0,0 +1,63 @@ +package org.onap.so.logging.cxf.interceptor; + + +import java.util.Collections; +import java.util.Map; +import java.util.UUID; +import java.util.stream.Collectors; +import javax.servlet.http.HttpServletRequest; +import javax.xml.namespace.QName; +import org.apache.cxf.binding.soap.SoapMessage; +import org.apache.cxf.binding.soap.interceptor.AbstractSoapInterceptor; +import org.apache.cxf.interceptor.Fault; +import org.apache.cxf.message.Message; +import org.apache.cxf.phase.Phase; +import org.apache.cxf.service.model.MessageInfo; +import org.apache.cxf.service.model.OperationInfo; +import org.apache.cxf.transport.http.AbstractHTTPDestination; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.onap.so.exceptions.MSOException; +import org.onap.so.logging.jaxrs.filter.JaxRsFilterLogging; +import org.onap.so.logging.jaxrs.filter.MDCSetup; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class SOAPLoggingOutInterceptor extends AbstractSoapInterceptor{ + + private static final String _500 = "500"; + + protected static Logger logger = LoggerFactory.getLogger(SOAPLoggingOutInterceptor.class); + + @Autowired + MDCSetup mdcSetup; + + public SOAPLoggingOutInterceptor() { + super(Phase.WRITE); + } + + @Override + public void handleMessage(SoapMessage message) throws Fault { + try { + Exception ex = message.getContent(Exception.class); + if (ex == null) { + MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, ONAPLogConstants.ResponseStatus.COMPLETED.toString()); + }else{ + int responseCode = 0; + responseCode = (int) message.get(Message.RESPONSE_CODE); + if(responseCode != 0 ) + MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE, String.valueOf(responseCode)); + else + MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE, _500); + + MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, ONAPLogConstants.ResponseStatus.ERROR.toString()); + } + logger.info(ONAPLogConstants.Markers.EXIT, "Exiting"); + } catch (Exception e) { + logger.warn("Error in incoming SOAP Message Inteceptor", e); + } + } +} diff --git a/common/src/main/java/org/onap/so/logging/jaxrs/filter/JaxRsClientLogging.java b/common/src/main/java/org/onap/so/logging/jaxrs/filter/JaxRsClientLogging.java new file mode 100644 index 0000000000..2cb375bed8 --- /dev/null +++ b/common/src/main/java/org/onap/so/logging/jaxrs/filter/JaxRsClientLogging.java @@ -0,0 +1,135 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.logging.jaxrs.filter; + + +import org.apache.commons.io.IOUtils; +import org.onap.so.logger.MsoLogger; +import org.onap.so.utils.TargetEntity; +import org.slf4j.MDC; +import org.springframework.stereotype.Component; + +import javax.ws.rs.client.ClientRequestContext; +import javax.ws.rs.client.ClientRequestFilter; +import javax.ws.rs.client.ClientResponseContext; +import javax.ws.rs.client.ClientResponseFilter; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; + +import java.io.*; + +import java.time.Instant; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.Locale; +import java.util.UUID; + +@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection") +@Component +public class JaxRsClientLogging implements ClientRequestFilter,ClientResponseFilter { + + private static MsoLogger logger = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA,JaxRsClientLogging.class); + + private TargetEntity targetEntity; + + public void setTargetService(TargetEntity targetEntity){ + this.targetEntity = targetEntity; + } + + @Override + public void filter(ClientRequestContext clientRequest) { + try{ + MultivaluedMap headers = clientRequest.getHeaders(); + + + Instant instant = Instant.now(); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX" ) + .withLocale( Locale.US ) + .withZone( ZoneId.systemDefault() ); + + String requestId = MDC.get(MsoLogger.REQUEST_ID); + if(requestId == null || requestId.isEmpty()){ + requestId = UUID.randomUUID().toString(); + logger.warnSimple(clientRequest.getUri().getPath(),"Could not Find Request ID Generating New One"); + } + + MDC.put(MsoLogger.METRIC_BEGIN_TIME, formatter.format(instant)); + MDC.put(MsoLogger.METRIC_START_TIME, String.valueOf(System.currentTimeMillis())); + MDC.put(MsoLogger.REQUEST_ID,requestId); + MDC.put(MsoLogger.TARGETSERVICENAME, clientRequest.getUri().toString()); + } catch (Exception e) { + logger.warnSimple("Error in incoming JAX-RS Inteceptor", e); + } + } + + + @Override + public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) { + + try { + Instant instant = Instant.now(); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX" ) + .withLocale( Locale.US ) + .withZone( ZoneId.systemDefault() ); + String startTime= MDC.get(MsoLogger.METRIC_START_TIME); + + long elapsedTime = System.currentTimeMillis()-Long.parseLong(startTime); + String statusCode; + if(Response.Status.Family.familyOf(responseContext.getStatus()).equals(Response.Status.Family.SUCCESSFUL)){ + statusCode=MsoLogger.COMPLETE; + }else{ + statusCode=MsoLogger.StatusCode.ERROR.toString(); + } + MultivaluedMap headers = responseContext.getHeaders(); + + String partnerName = headers.getFirst(MsoLogger.HEADER_FROM_APP_ID ); + if(partnerName == null || partnerName.isEmpty()) + partnerName="UNKNOWN"; + MDC.put(MsoLogger.RESPONSEDESC,getStringFromInputStream(responseContext)); + MDC.put(MsoLogger.STATUSCODE, statusCode); + MDC.put(MsoLogger.RESPONSECODE,String.valueOf(responseContext.getStatus())); + MDC.put(MsoLogger.METRIC_TIMER, String.valueOf(elapsedTime)); + MDC.put(MsoLogger.METRIC_END_TIME,formatter.format(instant)); + MDC.put(MsoLogger.PARTNERNAME,partnerName); + MDC.put(MsoLogger.TARGETENTITY, targetEntity.toString()); + logger.recordMetricEvent(); + } catch ( Exception e) { + logger.warnSimple("Error in outgoing JAX-RS Inteceptor", e); + } + } + + private static String getStringFromInputStream(ClientResponseContext clientResponseContext) { + + InputStream is = clientResponseContext.getEntityStream(); + ByteArrayOutputStream boas = new ByteArrayOutputStream(); + + try { + IOUtils.copy(is,boas); + InputStream copiedStream = new ByteArrayInputStream(boas.toByteArray()); + clientResponseContext.setEntityStream(copiedStream); + return boas.toString(); + + } catch (IOException e) { + logger.warnSimple("Failed to read response body", e); + } + return "Unable to read input stream"; + } +} diff --git a/common/src/main/java/org/onap/so/logging/jaxrs/filter/JaxRsFilterLogging.java b/common/src/main/java/org/onap/so/logging/jaxrs/filter/JaxRsFilterLogging.java new file mode 100644 index 0000000000..7d02136860 --- /dev/null +++ b/common/src/main/java/org/onap/so/logging/jaxrs/filter/JaxRsFilterLogging.java @@ -0,0 +1,169 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.logging.jaxrs.filter; + + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; +import java.util.UUID; +import javax.annotation.Priority; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.container.ContainerRequestFilter; +import javax.ws.rs.container.ContainerResponseContext; +import javax.ws.rs.container.ContainerResponseFilter; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.MessageBodyWriter; +import javax.ws.rs.ext.Provider; +import javax.ws.rs.ext.Providers; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import com.fasterxml.jackson.databind.ObjectMapper; + +@Priority(1) +@Provider +@Component +public class JaxRsFilterLogging implements ContainerRequestFilter,ContainerResponseFilter { + + protected static Logger logger = LoggerFactory.getLogger(JaxRsFilterLogging.class); + + @Context + private HttpServletRequest httpServletRequest; + + @Context + private Providers providers; + + @Autowired + private MDCSetup mdcSetup; + + @Override + public void filter(ContainerRequestContext containerRequest) { + try { + MultivaluedMap headers = containerRequest.getHeaders(); + setRequestId(headers); + containerRequest.setProperty("requestId", MDC.get(ONAPLogConstants.MDCs.REQUEST_ID)); + setInvocationId(headers); + setServiceName(containerRequest); + setMDCPartnerName(headers); + mdcSetup.setServerFQDN(); + mdcSetup.setClientIPAddress(httpServletRequest); + mdcSetup.setInstanceUUID(); + mdcSetup.setEntryTimeStamp(); + MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, "INPROGRESS"); + logger.info(ONAPLogConstants.Markers.ENTRY, "Entering"); + } catch (Exception e) { + logger.warn("Error in incoming JAX-RS Inteceptor", e); + } + } + + @Override + public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) + throws IOException { + try { + setResponseStatusCode(responseContext); + MDC.put(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION,payloadMessage(responseContext)); + MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE,String.valueOf(responseContext.getStatus())); + logger.info(ONAPLogConstants.Markers.EXIT, "Exiting."); + MDC.clear(); + } catch ( Exception e) { + MDC.clear(); + logger.warn("Error in outgoing JAX-RS Inteceptor", e); + } + } + + private void setResponseStatusCode(ContainerResponseContext responseContext) { + String statusCode; + if(Response.Status.Family.familyOf(responseContext.getStatus()).equals(Response.Status.Family.SUCCESSFUL)){ + statusCode=ONAPLogConstants.ResponseStatus.COMPLETED.toString(); + }else{ + statusCode= ONAPLogConstants.ResponseStatus.ERROR.toString(); + } + MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, statusCode); + } + + private String payloadMessage(ContainerResponseContext responseContext) throws IOException { + String message = ""; + if (responseContext.hasEntity()) { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + Class entityClass = responseContext.getEntityClass(); + Type entityType = responseContext.getEntityType(); + Annotation[] entityAnnotations = responseContext.getEntityAnnotations(); + MediaType mediaType = responseContext.getMediaType(); + @SuppressWarnings("unchecked") + MessageBodyWriter bodyWriter = (MessageBodyWriter) providers.getMessageBodyWriter(entityClass, + entityType, + entityAnnotations, + mediaType); + bodyWriter.writeTo(responseContext.getEntity(), + entityClass, + entityType, + entityAnnotations, + mediaType, + responseContext.getHeaders(), + baos); + message = message.concat(new String(baos.toByteArray())); + } + return message; + } + + + private void setRequestId(MultivaluedMap headers){ + String requestId=headers.getFirst(ONAPLogConstants.Headers.REQUEST_ID); + if(requestId == null || requestId.isEmpty()) + requestId = UUID.randomUUID().toString(); + MDC.put(ONAPLogConstants.MDCs.REQUEST_ID,requestId); + } + + private void setInvocationId(MultivaluedMap headers){ + MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, findInvocationId(headers)); + } + + private void setMDCPartnerName(MultivaluedMap headers){ + String partnerName=headers.getFirst(ONAPLogConstants.Headers.PARTNER_NAME); + if(partnerName == null || partnerName.isEmpty()) + partnerName = ""; + MDC.put(ONAPLogConstants.MDCs.PARTNER_NAME,partnerName); + } + + private String findInvocationId(MultivaluedMap headers) { + String invocationId = headers.getFirst(ONAPLogConstants.Headers.INVOCATION_ID); + if(invocationId == null || invocationId.isEmpty()) + invocationId =UUID.randomUUID().toString(); + return invocationId; + } + + private void setServiceName(ContainerRequestContext containerRequest){ + MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, containerRequest.getUriInfo().getPath()); + } + + + + +} diff --git a/common/src/main/java/org/onap/so/logging/jaxrs/filter/MDCSetup.java b/common/src/main/java/org/onap/so/logging/jaxrs/filter/MDCSetup.java new file mode 100644 index 0000000000..3c04fa1a8e --- /dev/null +++ b/common/src/main/java/org/onap/so/logging/jaxrs/filter/MDCSetup.java @@ -0,0 +1,51 @@ +package org.onap.so.logging.jaxrs.filter; + +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.util.UUID; +import javax.servlet.http.HttpServletRequest; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.springframework.stereotype.Component; + +@Component +public class MDCSetup { + + protected static Logger logger = LoggerFactory.getLogger(MDCSetup.class); + + private static final String INSTANCE_UUID = UUID.randomUUID().toString(); + + public void setInstanceUUID(){ + MDC.put(ONAPLogConstants.MDCs.INSTANCE_UUID, INSTANCE_UUID); + } + + public void setServerFQDN(){ + String serverFQDN = ""; + InetAddress addr= null; + try { + addr = InetAddress.getLocalHost(); + serverFQDN = addr.toString(); + } catch (UnknownHostException e) { + logger.warn("Cannot Resolve Host Name"); + serverFQDN = ""; + } + MDC.put(ONAPLogConstants.MDCs.SERVER_FQDN, serverFQDN); + } + + public void setClientIPAddress(HttpServletRequest httpServletRequest){ + String remoteIpAddress = ""; + if (httpServletRequest != null) { + remoteIpAddress = httpServletRequest.getRemoteAddr(); + } + MDC.put(ONAPLogConstants.MDCs.CLIENT_IP_ADDRESS, remoteIpAddress); + } + + public void setEntryTimeStamp() { + MDC.put(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP,ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT)); + } +} \ No newline at end of file diff --git a/common/src/main/java/org/onap/so/logging/jaxrs/filter/SpringClientFilter.java b/common/src/main/java/org/onap/so/logging/jaxrs/filter/SpringClientFilter.java new file mode 100644 index 0000000000..6af7a916d0 --- /dev/null +++ b/common/src/main/java/org/onap/so/logging/jaxrs/filter/SpringClientFilter.java @@ -0,0 +1,67 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.logging.jaxrs.filter; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpRequest; +import org.springframework.http.client.ClientHttpRequestExecution; +import org.springframework.http.client.ClientHttpRequestInterceptor; +import org.springframework.http.client.ClientHttpResponse; +import org.springframework.util.StreamUtils; + +import java.io.IOException; +import java.nio.charset.Charset; + +public class SpringClientFilter implements ClientHttpRequestInterceptor { + + private final Logger log = LoggerFactory.getLogger(this.getClass()); + + @Override + public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { + logRequest(request, body); + ClientHttpResponse response = execution.execute(request, body); + logResponse(response); + return response; + } + + private void logRequest(HttpRequest request, byte[] body) throws IOException { + if (log.isDebugEnabled()) { + log.debug("===========================request begin================================================"); + log.debug("URI : {}", request.getURI()); + log.debug("Method : {}", request.getMethod()); + log.debug("Headers : {}", request.getHeaders()); + log.debug("Request body: {}", new String(body, "UTF-8")); + log.debug("==========================request end================================================"); + } + } + + private void logResponse(ClientHttpResponse response) throws IOException { + if (log.isDebugEnabled()) { + log.debug("============================response begin=========================================="); + log.debug("Status code : {}", response.getStatusCode()); + log.debug("Status text : {}", response.getStatusText()); + log.debug("Headers : {}", response.getHeaders()); + log.debug("Response body: {}", StreamUtils.copyToString(response.getBody(), Charset.defaultCharset())); + log.debug("=======================response end================================================="); + } + } +} diff --git a/common/src/main/java/org/onap/so/logging/jaxrs/filter/jersey/JaxRsClientLogging.java b/common/src/main/java/org/onap/so/logging/jaxrs/filter/jersey/JaxRsClientLogging.java deleted file mode 100644 index 2888cbf3a1..0000000000 --- a/common/src/main/java/org/onap/so/logging/jaxrs/filter/jersey/JaxRsClientLogging.java +++ /dev/null @@ -1,135 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.so.logging.jaxrs.filter.jersey; - - -import org.apache.commons.io.IOUtils; -import org.onap.so.logger.MsoLogger; -import org.onap.so.utils.TargetEntity; -import org.slf4j.MDC; -import org.springframework.stereotype.Component; - -import javax.ws.rs.client.ClientRequestContext; -import javax.ws.rs.client.ClientRequestFilter; -import javax.ws.rs.client.ClientResponseContext; -import javax.ws.rs.client.ClientResponseFilter; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; - -import java.io.*; - -import java.time.Instant; -import java.time.ZoneId; -import java.time.format.DateTimeFormatter; -import java.util.Locale; -import java.util.UUID; - -@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection") -@Component -public class JaxRsClientLogging implements ClientRequestFilter,ClientResponseFilter { - - private static MsoLogger logger = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA,JaxRsClientLogging.class); - - private TargetEntity targetEntity; - - public void setTargetService(TargetEntity targetEntity){ - this.targetEntity = targetEntity; - } - - @Override - public void filter(ClientRequestContext clientRequest) { - try{ - MultivaluedMap headers = clientRequest.getHeaders(); - - - Instant instant = Instant.now(); - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX" ) - .withLocale( Locale.US ) - .withZone( ZoneId.systemDefault() ); - - String requestId = MDC.get(MsoLogger.REQUEST_ID); - if(requestId == null || requestId.isEmpty()){ - requestId = UUID.randomUUID().toString(); - logger.warnSimple(clientRequest.getUri().getPath(),"Could not Find Request ID Generating New One"); - } - - MDC.put(MsoLogger.METRIC_BEGIN_TIME, formatter.format(instant)); - MDC.put(MsoLogger.METRIC_START_TIME, String.valueOf(System.currentTimeMillis())); - MDC.put(MsoLogger.REQUEST_ID,requestId); - MDC.put(MsoLogger.TARGETSERVICENAME, clientRequest.getUri().toString()); - } catch (Exception e) { - logger.warnSimple("Error in incoming JAX-RS Inteceptor", e); - } - } - - - @Override - public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) { - - try { - Instant instant = Instant.now(); - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX" ) - .withLocale( Locale.US ) - .withZone( ZoneId.systemDefault() ); - String startTime= MDC.get(MsoLogger.METRIC_START_TIME); - - long elapsedTime = System.currentTimeMillis()-Long.parseLong(startTime); - String statusCode; - if(Response.Status.Family.familyOf(responseContext.getStatus()).equals(Response.Status.Family.SUCCESSFUL)){ - statusCode=MsoLogger.COMPLETE; - }else{ - statusCode=MsoLogger.StatusCode.ERROR.toString(); - } - MultivaluedMap headers = responseContext.getHeaders(); - - String partnerName = headers.getFirst(MsoLogger.HEADER_FROM_APP_ID ); - if(partnerName == null || partnerName.isEmpty()) - partnerName="UNKNOWN"; - MDC.put(MsoLogger.RESPONSEDESC,getStringFromInputStream(responseContext)); - MDC.put(MsoLogger.STATUSCODE, statusCode); - MDC.put(MsoLogger.RESPONSECODE,String.valueOf(responseContext.getStatus())); - MDC.put(MsoLogger.METRIC_TIMER, String.valueOf(elapsedTime)); - MDC.put(MsoLogger.METRIC_END_TIME,formatter.format(instant)); - MDC.put(MsoLogger.PARTNERNAME,partnerName); - MDC.put(MsoLogger.TARGETENTITY, targetEntity.toString()); - logger.recordMetricEvent(); - } catch ( Exception e) { - logger.warnSimple("Error in outgoing JAX-RS Inteceptor", e); - } - } - - private static String getStringFromInputStream(ClientResponseContext clientResponseContext) { - - InputStream is = clientResponseContext.getEntityStream(); - ByteArrayOutputStream boas = new ByteArrayOutputStream(); - - try { - IOUtils.copy(is,boas); - InputStream copiedStream = new ByteArrayInputStream(boas.toByteArray()); - clientResponseContext.setEntityStream(copiedStream); - return boas.toString(); - - } catch (IOException e) { - logger.warnSimple("Failed to read response body", e); - } - return "Unable to read input stream"; - } -} diff --git a/common/src/main/java/org/onap/so/logging/jaxrs/filter/jersey/JaxRsFilterLogging.java b/common/src/main/java/org/onap/so/logging/jaxrs/filter/jersey/JaxRsFilterLogging.java deleted file mode 100644 index d278a5f761..0000000000 --- a/common/src/main/java/org/onap/so/logging/jaxrs/filter/jersey/JaxRsFilterLogging.java +++ /dev/null @@ -1,195 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.so.logging.jaxrs.filter.jersey; - - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.lang.annotation.Annotation; -import java.lang.reflect.Type; -import java.time.Instant; -import java.time.ZoneId; -import java.time.format.DateTimeFormatter; -import java.util.Locale; -import java.util.UUID; - -import javax.annotation.Priority; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.container.ContainerRequestContext; -import javax.ws.rs.container.ContainerRequestFilter; -import javax.ws.rs.container.ContainerResponseContext; -import javax.ws.rs.container.ContainerResponseFilter; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; -import javax.ws.rs.ext.MessageBodyWriter; -import javax.ws.rs.ext.Provider; -import javax.ws.rs.ext.Providers; -import org.onap.so.logger.MsoLogger; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.MDC; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; -import com.fasterxml.jackson.databind.ObjectMapper; - -@Priority(1) -@Provider -@Component -public class JaxRsFilterLogging implements ContainerRequestFilter,ContainerResponseFilter { - - protected static Logger logger = LoggerFactory.getLogger(JaxRsFilterLogging.class); - - @Context - private HttpServletRequest httpServletRequest; - - @Context - private Providers providers; - - @Autowired - ObjectMapper objectMapper; - - @Override - public void filter(ContainerRequestContext containerRequest) { - - try { - String clientID = null; - //check headers for request id - MultivaluedMap headers = containerRequest.getHeaders(); - String requestId = findRequestId(headers); - containerRequest.setProperty("requestId", requestId); - if(headers.containsKey(MsoLogger.CLIENT_ID)){ - clientID = headers.getFirst(MsoLogger.CLIENT_ID); - }else{ - clientID = "UNKNOWN"; - headers.add(MsoLogger.CLIENT_ID, clientID); - } - - String remoteIpAddress = ""; - if (httpServletRequest != null) { - remoteIpAddress = httpServletRequest.getRemoteAddr(); - } - Instant instant = Instant.now(); - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX" ) - .withLocale( Locale.US ) - .withZone( ZoneId.systemDefault() ); - - String partnerName = headers.getFirst(MsoLogger.HEADER_FROM_APP_ID ); - if(partnerName == null || partnerName.isEmpty()) - partnerName="UNKNOWN"; - - MDC.put(MsoLogger.REQUEST_ID,requestId); - MDC.put(MsoLogger.INVOCATION_ID,requestId); - MDC.put(MsoLogger.FROM_APP_ID,partnerName); - MDC.put(MsoLogger.SERVICE_NAME, containerRequest.getUriInfo().getPath()); - MDC.put(MsoLogger.INVOCATION_ID, findInvocationId(headers)); - MDC.put(MsoLogger.STATUSCODE, MsoLogger.INPROGRESS); - MDC.put(MsoLogger.BEGINTIME, formatter.format(instant)); - MDC.put(MsoLogger.PARTNERNAME,partnerName); - MDC.put(MsoLogger.REMOTE_HOST, String.valueOf(remoteIpAddress)); - MDC.put(MsoLogger.STARTTIME, String.valueOf(System.currentTimeMillis())); - logger.debug(MsoLogger.ENTRY, "Entering."); - } catch (Exception e) { - logger.warn("Error in incoming JAX-RS Inteceptor", e); - } - } - - - private String findRequestId(MultivaluedMap headers) { - String requestId = (String) headers.getFirst(MsoLogger.HEADER_REQUEST_ID ); - if(requestId == null || requestId.isEmpty()){ - if(headers.containsKey(MsoLogger.ONAP_REQUEST_ID)){ - requestId = headers.getFirst(MsoLogger.ONAP_REQUEST_ID); - }else if(headers.containsKey(MsoLogger.ECOMP_REQUEST_ID)){ - requestId = headers.getFirst(MsoLogger.ECOMP_REQUEST_ID); - }else{ - requestId = UUID.randomUUID().toString(); - } - } - return requestId; - } - - private String findInvocationId(MultivaluedMap headers) { - String invocationId = (String) headers.getFirst(MsoLogger.INVOCATION_ID_HEADER ); - if(invocationId == null || invocationId.isEmpty()) - invocationId =UUID.randomUUID().toString(); - return invocationId; - } - - @Override - public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) - throws IOException { - try { - Instant instant = Instant.now(); - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX" ) - .withLocale( Locale.US ) - .withZone( ZoneId.systemDefault() ); - String startTime= MDC.get(MsoLogger.STARTTIME); - long elapsedTime; - try { - elapsedTime = System.currentTimeMillis() - Long.parseLong(startTime); - }catch(NumberFormatException e){ - elapsedTime = 0; - } - String statusCode; - if(Response.Status.Family.familyOf(responseContext.getStatus()).equals(Response.Status.Family.SUCCESSFUL)){ - statusCode=MsoLogger.COMPLETE; - }else{ - statusCode= MsoLogger.StatusCode.ERROR.toString(); - } - - MDC.put(MsoLogger.RESPONSEDESC,payloadMessage(responseContext)); - MDC.put(MsoLogger.STATUSCODE, statusCode); - MDC.put(MsoLogger.RESPONSECODE,String.valueOf(responseContext.getStatus())); - MDC.put(MsoLogger.TIMER, String.valueOf(elapsedTime)); - MDC.put(MsoLogger.ENDTIME,formatter.format(instant)); - logger.debug(MsoLogger.EXIT, "Exiting."); - } catch ( Exception e) { - logger.warn("Error in outgoing JAX-RS Inteceptor", e); - } - } - - private String payloadMessage(ContainerResponseContext responseContext) throws IOException { - String message = new String(); - if (responseContext.hasEntity()) { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - Class entityClass = responseContext.getEntityClass(); - Type entityType = responseContext.getEntityType(); - Annotation[] entityAnnotations = responseContext.getEntityAnnotations(); - MediaType mediaType = responseContext.getMediaType(); - @SuppressWarnings("unchecked") - MessageBodyWriter bodyWriter = (MessageBodyWriter) providers.getMessageBodyWriter(entityClass, - entityType, - entityAnnotations, - mediaType); - bodyWriter.writeTo(responseContext.getEntity(), - entityClass, - entityType, - entityAnnotations, - mediaType, - responseContext.getHeaders(), - baos); - message = message.concat(new String(baos.toByteArray())); - } - return message; - } -} diff --git a/common/src/main/java/org/onap/so/logging/jaxrs/filter/jersey/SpringClientFilter.java b/common/src/main/java/org/onap/so/logging/jaxrs/filter/jersey/SpringClientFilter.java deleted file mode 100644 index 0477c9a429..0000000000 --- a/common/src/main/java/org/onap/so/logging/jaxrs/filter/jersey/SpringClientFilter.java +++ /dev/null @@ -1,67 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.so.logging.jaxrs.filter.jersey; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.HttpRequest; -import org.springframework.http.client.ClientHttpRequestExecution; -import org.springframework.http.client.ClientHttpRequestInterceptor; -import org.springframework.http.client.ClientHttpResponse; -import org.springframework.util.StreamUtils; - -import java.io.IOException; -import java.nio.charset.Charset; - -public class SpringClientFilter implements ClientHttpRequestInterceptor { - - private final Logger log = LoggerFactory.getLogger(this.getClass()); - - @Override - public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { - logRequest(request, body); - ClientHttpResponse response = execution.execute(request, body); - logResponse(response); - return response; - } - - private void logRequest(HttpRequest request, byte[] body) throws IOException { - if (log.isDebugEnabled()) { - log.debug("===========================request begin================================================"); - log.debug("URI : {}", request.getURI()); - log.debug("Method : {}", request.getMethod()); - log.debug("Headers : {}", request.getHeaders()); - log.debug("Request body: {}", new String(body, "UTF-8")); - log.debug("==========================request end================================================"); - } - } - - private void logResponse(ClientHttpResponse response) throws IOException { - if (log.isDebugEnabled()) { - log.debug("============================response begin=========================================="); - log.debug("Status code : {}", response.getStatusCode()); - log.debug("Status text : {}", response.getStatusText()); - log.debug("Headers : {}", response.getHeaders()); - log.debug("Response body: {}", StreamUtils.copyToString(response.getBody(), Charset.defaultCharset())); - log.debug("=======================response end================================================="); - } - } -} -- cgit 1.2.3-korg