diff options
Diffstat (limited to 'common/src/main/java/org/onap/so/logging')
10 files changed, 130 insertions, 909 deletions
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 deleted file mode 100644 index 5dbf88d346..0000000000 --- a/common/src/main/java/org/onap/so/logging/jaxrs/filter/JaxRsClientLogging.java +++ /dev/null @@ -1,136 +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; - - -import org.onap.logging.ref.slf4j.ONAPLogConstants; -import org.onap.so.utils.TargetEntity; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.MDC; -import org.springframework.stereotype.Component; -import javax.annotation.Priority; -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.Context; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; -import javax.ws.rs.ext.Providers; -import java.time.ZoneOffset; -import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; -import java.util.UUID; - -@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection") -@Component -@Priority(0) -public class JaxRsClientLogging implements ClientRequestFilter, ClientResponseFilter { - - @Context - private Providers providers; - - private static final String TRACE = "trace-#"; - private static final String SO = "SO"; - private static Logger logger = LoggerFactory.getLogger(JaxRsClientLogging.class); - - public void setTargetService(TargetEntity targetEntity) { - MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY, targetEntity.toString()); - } - - @Override - public void filter(ClientRequestContext clientRequest) { - try { - setupMDC(clientRequest); - setupHeaders(clientRequest); - logger.info(ONAPLogConstants.Markers.INVOKE, "Invoke"); - } catch (Exception e) { - logger.warn("Error in incoming JAX-RS Inteceptor", e); - } - } - - private void setupHeaders(ClientRequestContext clientRequest) { - MultivaluedMap<String, Object> headers = clientRequest.getHeaders(); - headers.add(ONAPLogConstants.Headers.REQUEST_ID, extractRequestID(clientRequest)); - headers.add(ONAPLogConstants.Headers.INVOCATION_ID, MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID)); - headers.add(ONAPLogConstants.Headers.PARTNER_NAME, SO); - } - - private void setupMDC(ClientRequestContext clientRequest) { - MDC.put(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP, - ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT)); - MDC.put(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME, clientRequest.getUri().toString()); - MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, ONAPLogConstants.ResponseStatus.INPROGRESS.toString()); - setInvocationId(); - MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY, MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); - } - - private String extractRequestID(ClientRequestContext clientRequest) { - String requestId = MDC.get(ONAPLogConstants.MDCs.REQUEST_ID); - if (requestId == null || requestId.isEmpty() || requestId.equals(TRACE)) { - requestId = UUID.randomUUID().toString(); - logger.warn("Could not Find Request ID Generating New One: {}", clientRequest.getUri().getPath()); - } - return requestId; - } - - private void setInvocationId() { - String invocationId = MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID); - if (invocationId == null || invocationId.isEmpty()) - invocationId = UUID.randomUUID().toString(); - MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, invocationId); - } - - - @Override - public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) { - - try { - 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_CODE, String.valueOf(responseContext.getStatus())); - MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, statusCode); - logger.info(ONAPLogConstants.Markers.INVOKE_RETURN, "InvokeReturn"); - clearClientMDCs(); - } catch (Exception e) { - logger.warn("Error in outgoing JAX-RS Inteceptor", e); - } - } - - private void clearClientMDCs() { - MDC.remove(ONAPLogConstants.MDCs.INVOCATION_ID); - MDC.remove(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION); - MDC.remove(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE); - MDC.remove(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION); - MDC.remove(ONAPLogConstants.MDCs.RESPONSE_CODE); - MDC.remove(ONAPLogConstants.MDCs.TARGET_ENTITY); - MDC.remove(ONAPLogConstants.MDCs.PARTNER_NAME); - MDC.remove(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME); - MDC.remove(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP); - } - -} 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 deleted file mode 100644 index 7e2b603ba6..0000000000 --- a/common/src/main/java/org/onap/so/logging/jaxrs/filter/JaxRsFilterLogging.java +++ /dev/null @@ -1,173 +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; - -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.onap.so.logger.HttpHeadersConstants; -import org.onap.so.logger.LogConstants; -import org.onap.so.logger.MdcConstants; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.MDC; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -@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<String, String> 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(HttpHeadersConstants.REQUESTOR_ID, headers.getFirst("X-RequestorID")); - MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, ONAPLogConstants.ResponseStatus.INPROGRESS.toString()); - MDC.put(LogConstants.URI_BASE, containerRequest.getUriInfo().getBaseUri().toString()); - MDC.put(MdcConstants.ORIGINAL_PARTNER_NAME, MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME)); - 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<Object> bodyWriter = (MessageBodyWriter<Object>) 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<String, String> 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<String, String> headers) { - MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, findInvocationId(headers)); - } - - private void setMDCPartnerName(MultivaluedMap<String, String> 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<String, String> 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()); - } - - private void clearClientMDCs() { - MDC.remove(ONAPLogConstants.MDCs.INVOCATION_ID); - MDC.remove(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION); - MDC.remove(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE); - MDC.remove(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION); - MDC.remove(ONAPLogConstants.MDCs.RESPONSE_CODE); - MDC.remove(ONAPLogConstants.MDCs.TARGET_ENTITY); - MDC.remove(ONAPLogConstants.MDCs.PARTNER_NAME); - MDC.remove(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME); - } - -} 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 deleted file mode 100644 index 607f067ec4..0000000000 --- a/common/src/main/java/org/onap/so/logging/jaxrs/filter/MDCSetup.java +++ /dev/null @@ -1,111 +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; - -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.time.ZoneOffset; -import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; -import java.util.Map; -import java.util.UUID; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.core.Response; -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)); - } - - public void setServiceName(HttpServletRequest request) { - MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, request.getRequestURI()); - } - - public void setRequestId(Map<String, String> headers) { - String requestId = headers.get(ONAPLogConstants.Headers.REQUEST_ID); - if (requestId == null || requestId.isEmpty()) - requestId = UUID.randomUUID().toString(); - MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, requestId); - } - - public void setInvocationId(Map<String, String> headers) { - String invocationId = headers.get(ONAPLogConstants.Headers.INVOCATION_ID); - if (invocationId == null || invocationId.isEmpty()) - invocationId = UUID.randomUUID().toString(); - MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, invocationId); - } - - public void setMDCPartnerName(Map<String, String> headers) { - String partnerName = headers.get(ONAPLogConstants.Headers.PARTNER_NAME); - if (partnerName == null || partnerName.isEmpty()) - partnerName = ""; - MDC.put(ONAPLogConstants.MDCs.PARTNER_NAME, partnerName); - } - - - public void setResponseStatusCode(HttpServletResponse response) { - String statusCode; - if (Response.Status.Family.familyOf(response.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); - } -} diff --git a/common/src/main/java/org/onap/so/logging/jaxrs/filter/MDCTaskDecorator.java b/common/src/main/java/org/onap/so/logging/jaxrs/filter/MDCTaskDecorator.java deleted file mode 100644 index e644f9e030..0000000000 --- a/common/src/main/java/org/onap/so/logging/jaxrs/filter/MDCTaskDecorator.java +++ /dev/null @@ -1,43 +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; - -import java.util.Map; -import org.slf4j.MDC; -import org.springframework.core.task.TaskDecorator; - -public class MDCTaskDecorator implements TaskDecorator { - - @Override - public Runnable decorate(Runnable runnable) { - Map<String, String> contextMap = MDC.getCopyOfContextMap(); - return () -> { - try { - if (contextMap != null) { - MDC.setContextMap(contextMap); - runnable.run(); - } - } finally { - MDC.clear(); - } - }; - } -} diff --git a/common/src/main/java/org/onap/so/logging/jaxrs/filter/PayloadLoggingFilter.java b/common/src/main/java/org/onap/so/logging/jaxrs/filter/PayloadLoggingFilter.java deleted file mode 100644 index 21c0b52a91..0000000000 --- a/common/src/main/java/org/onap/so/logging/jaxrs/filter/PayloadLoggingFilter.java +++ /dev/null @@ -1,158 +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; - -import java.io.BufferedInputStream; -import java.io.ByteArrayOutputStream; -import java.io.FilterOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import javax.annotation.Priority; -import javax.ws.rs.WebApplicationException; -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.ext.Provider; -import javax.ws.rs.ext.WriterInterceptor; -import javax.ws.rs.ext.WriterInterceptorContext; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - - -@Provider -@Priority(1) -public class PayloadLoggingFilter implements ClientRequestFilter, ClientResponseFilter, WriterInterceptor { - - private static final Logger logger = LoggerFactory.getLogger(PayloadLoggingFilter.class); - private static final String ENTITY_STREAM_PROPERTY = "LoggingFilter.entityStream"; - private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8; - private final int maxEntitySize; - - public PayloadLoggingFilter() { - maxEntitySize = 1024 * 1024; - } - - public PayloadLoggingFilter(int maxPayloadSize) { - this.maxEntitySize = Integer.min(maxPayloadSize, 1024 * 1024); - } - - private void log(StringBuilder sb) { - logger.debug(sb.toString()); - } - - protected InputStream logInboundEntity(final StringBuilder b, InputStream stream, final Charset charset) - throws IOException { - if (!stream.markSupported()) { - stream = new BufferedInputStream(stream); - } - stream.mark(maxEntitySize + 1); - final byte[] entity = new byte[maxEntitySize + 1]; - final int entitySize = stream.read(entity); - if (entitySize != -1) { - b.append(new String(entity, 0, Math.min(entitySize, maxEntitySize), charset)); - } - if (entitySize > maxEntitySize) { - b.append("...more..."); - } - b.append('\n'); - stream.reset(); - return stream; - } - - @Override - public void filter(ClientRequestContext requestContext) throws IOException { - if (requestContext.hasEntity()) { - final OutputStream stream = new LoggingStream(requestContext.getEntityStream()); - requestContext.setEntityStream(stream); - requestContext.setProperty(ENTITY_STREAM_PROPERTY, stream); - } - String method = formatMethod(requestContext); - log(new StringBuilder("Making " + method + " request to: " + requestContext.getUri() + "\nRequest Headers: " - + requestContext.getHeaders().toString())); - - } - - @Override - public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException { - final StringBuilder sb = new StringBuilder(); - if (responseContext.hasEntity()) { - responseContext.setEntityStream(logInboundEntity(sb, responseContext.getEntityStream(), DEFAULT_CHARSET)); - String method = formatMethod(requestContext); - log(sb.insert(0, "Response from " + method + ": " + requestContext.getUri() + "\nResponse Headers: " - + responseContext.getHeaders().toString())); - } - } - - @Override - public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException { - final LoggingStream stream = (LoggingStream) context.getProperty(ENTITY_STREAM_PROPERTY); - context.proceed(); - if (stream != null) { - log(stream.getStringBuilder(DEFAULT_CHARSET)); - } - } - - private class LoggingStream extends FilterOutputStream { - - private final StringBuilder sb = new StringBuilder(); - private final ByteArrayOutputStream baos = new ByteArrayOutputStream(); - - LoggingStream(OutputStream out) { - super(out); - } - - StringBuilder getStringBuilder(Charset charset) { - // write entity to the builder - final byte[] entity = baos.toByteArray(); - - sb.append(new String(entity, 0, entity.length, charset)); - if (entity.length > maxEntitySize) { - sb.append("...more..."); - } - sb.append('\n'); - - return sb; - } - - @Override - public void write(final int i) throws IOException { - if (baos.size() <= maxEntitySize) { - baos.write(i); - } - out.write(i); - } - } - - private String formatMethod(ClientRequestContext requestContext) { - String method = requestContext.getHeaderString("X-HTTP-Method-Override"); - if (method == null) { - method = requestContext.getMethod(); - } else { - method = requestContext.getMethod() + " (overridden to " + method + ")"; - } - - return method; - } -} diff --git a/common/src/main/java/org/onap/so/logging/jaxrs/filter/SOAuditLogContainerFilter.java b/common/src/main/java/org/onap/so/logging/jaxrs/filter/SOAuditLogContainerFilter.java new file mode 100644 index 0000000000..5ae1082464 --- /dev/null +++ b/common/src/main/java/org/onap/so/logging/jaxrs/filter/SOAuditLogContainerFilter.java @@ -0,0 +1,34 @@ +package org.onap.so.logging.jaxrs.filter; + +import javax.annotation.Priority; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.container.ContainerResponseContext; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.onap.so.logger.HttpHeadersConstants; +import org.onap.so.logger.LogConstants; +import org.slf4j.MDC; +import org.springframework.stereotype.Component; +import org.onap.logging.filter.base.AuditLogContainerFilter; + +@Priority(1) +@Component +public class SOAuditLogContainerFilter extends AuditLogContainerFilter { + + private static final String ORIGINAL_PARTNER_NAME = "OriginalPartnerName"; + + @Override + protected void additionalPreHandling(ContainerRequestContext request) { + request.setProperty("requestId", MDC.get(ONAPLogConstants.MDCs.REQUEST_ID)); + MDC.put(ORIGINAL_PARTNER_NAME, MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME)); + String requestorId = request.getHeaders().getFirst("X-RequestorID"); + if (requestorId != null) { + MDC.put(HttpHeadersConstants.REQUESTOR_ID, requestorId); + } + MDC.put(LogConstants.URI_BASE, request.getUriInfo().getBaseUri().toString()); + } + + @Override + protected void additionalPostHandling(ContainerResponseContext response) { + // override to add additional post handling + } +} diff --git a/common/src/main/java/org/onap/so/logging/jaxrs/filter/SOMetricLogClientFilter.java b/common/src/main/java/org/onap/so/logging/jaxrs/filter/SOMetricLogClientFilter.java new file mode 100644 index 0000000000..248e2f00bf --- /dev/null +++ b/common/src/main/java/org/onap/so/logging/jaxrs/filter/SOMetricLogClientFilter.java @@ -0,0 +1,44 @@ +package org.onap.so.logging.jaxrs.filter; + +import javax.ws.rs.client.ClientRequestContext; +import javax.ws.rs.client.ClientResponseContext; +import org.onap.logging.filter.base.MDCSetup; +import org.onap.logging.filter.base.MetricLogClientFilter; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.onap.so.logger.MdcConstants; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.slf4j.Marker; +import org.slf4j.MarkerFactory; + + +public class SOMetricLogClientFilter extends MetricLogClientFilter { + + protected static Logger logger = LoggerFactory.getLogger(MDCSetup.class); + private static final Marker INVOKE_RETURN = MarkerFactory.getMarker("INVOKE-RETURN"); + + private MDCSetup mdcSetup = new MDCSetup(); + + @Override + public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) { + try { + mdcSetup.setLogTimestamp(); + mdcSetup.setElapsedTimeInvokeTimestamp(); + mdcSetup.setResponseStatusCode(responseContext.getStatus()); + mdcSetup.setResponseDescription(responseContext.getStatus()); + MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE, String.valueOf(responseContext.getStatus())); + logger.info(INVOKE_RETURN, "InvokeReturn"); + mdcSetup.clearClientMDCs(); + setOpenStackResponseCode(); + } catch (Exception e) { + logger.warn("Error in JAX-RS request,response client filter", e); + } + } + + protected void setOpenStackResponseCode() { + if (MDC.get(MdcConstants.OPENSTACK_STATUS_CODE) != null) { + MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, MDC.get(MdcConstants.OPENSTACK_STATUS_CODE)); + } + } +} diff --git a/common/src/main/java/org/onap/so/logging/jaxrs/filter/SOSpringClientFilter.java b/common/src/main/java/org/onap/so/logging/jaxrs/filter/SOSpringClientFilter.java new file mode 100644 index 0000000000..c2b8df37c2 --- /dev/null +++ b/common/src/main/java/org/onap/so/logging/jaxrs/filter/SOSpringClientFilter.java @@ -0,0 +1,52 @@ +package org.onap.so.logging.jaxrs.filter; + +import java.io.IOException; +import java.nio.charset.Charset; +import org.onap.logging.filter.base.MDCSetup; +import org.onap.logging.filter.spring.SpringClientFilter; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.onap.so.logger.MdcConstants; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.slf4j.Marker; +import org.slf4j.MarkerFactory; +import org.springframework.http.client.ClientHttpRequestInterceptor; +import org.springframework.http.client.ClientHttpResponse; +import org.springframework.stereotype.Component; +import org.springframework.util.StreamUtils; + +@Component +public class SOSpringClientFilter extends SpringClientFilter implements ClientHttpRequestInterceptor { + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private MDCSetup mdcSetup = new MDCSetup(); + private static final Marker INVOKE_RETURN = MarkerFactory.getMarker("INVOKE-RETURN"); + + + protected void processResponse(ClientHttpResponse response) throws IOException { + if (logger.isDebugEnabled()) { + logger.debug("============================response begin=========================================="); + logger.debug("Status code : {}", response.getStatusCode()); + logger.debug("Status text : {}", response.getStatusText()); + logger.debug("Headers : {}", response.getHeaders()); + logger.debug("Response body: {}", StreamUtils.copyToString(response.getBody(), Charset.defaultCharset())); + logger.debug("=======================response end================================================="); + } + mdcSetup.setLogTimestamp(); + mdcSetup.setElapsedTimeInvokeTimestamp(); + mdcSetup.setResponseStatusCode(response.getRawStatusCode()); + int statusCode = response.getRawStatusCode(); + MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE, String.valueOf(statusCode)); + mdcSetup.setResponseDescription(statusCode); + logger.info(INVOKE_RETURN, "InvokeReturn"); + mdcSetup.clearClientMDCs(); + setOpenStackResponseCode(); + } + + protected void setOpenStackResponseCode() { + if (MDC.get(MdcConstants.OPENSTACK_STATUS_CODE) != null) { + MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, MDC.get(MdcConstants.OPENSTACK_STATUS_CODE)); + } + } +} 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 deleted file mode 100644 index c763dd4374..0000000000 --- a/common/src/main/java/org/onap/so/logging/jaxrs/filter/SpringClientFilter.java +++ /dev/null @@ -1,156 +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; - -import org.onap.logging.ref.slf4j.ONAPLogConstants; -import org.onap.so.logger.LogConstants; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.MDC; -import org.springframework.http.HttpHeaders; -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; -import java.time.ZoneOffset; -import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; -import java.util.List; -import java.util.UUID; -import javax.ws.rs.core.Response; - -public class SpringClientFilter implements ClientHttpRequestInterceptor { - - private final Logger log = LoggerFactory.getLogger(this.getClass()); - - private static final String TRACE = "trace-#"; - private static final String SO = "SO"; - - @Override - public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) - throws IOException { - processRequest(request, body); - ClientHttpResponse response = execution.execute(request, body); - processResponse(response); - return response; - } - - private void processRequest(HttpRequest request, byte[] body) throws IOException { - setInvocationId(); - setupHeaders(request); - setupMDC(request); - 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 setupHeaders(HttpRequest clientRequest) { - HttpHeaders headers = clientRequest.getHeaders(); - headers.add(ONAPLogConstants.Headers.REQUEST_ID, extractRequestID(clientRequest)); - headers.add(ONAPLogConstants.Headers.INVOCATION_ID, MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID)); - headers.add(ONAPLogConstants.Headers.PARTNER_NAME, SO); - } - - private String extractRequestID(HttpRequest clientRequest) { - String requestId = MDC.get(ONAPLogConstants.MDCs.REQUEST_ID); - if (requestId == null || requestId.isEmpty() || requestId.equals(TRACE)) { - requestId = UUID.randomUUID().toString(); - log.warn("Could not Find Request ID Generating New One: {}", clientRequest.getURI()); - } - return requestId; - } - - private void setupMDC(HttpRequest clientRequest) { - MDC.put(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP, - ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT)); - MDC.put(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME, clientRequest.getURI().toString()); - MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, ONAPLogConstants.ResponseStatus.INPROGRESS.toString()); - MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY, extractTargetEntity(clientRequest)); - } - - private String extractTargetEntity(HttpRequest clientRequest) { - HttpHeaders headers = clientRequest.getHeaders(); - String headerTargetEntity = null; - List<String> headerTargetEntityList = headers.get(LogConstants.TARGET_ENTITY_HEADER); - if (headerTargetEntityList != null && !headerTargetEntityList.isEmpty()) - headerTargetEntity = headerTargetEntityList.get(0); - String targetEntity = MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY); - if (targetEntity != null && !targetEntity.isEmpty()) { - return targetEntity; - } else if (headerTargetEntity != null && !headerTargetEntity.isEmpty()) { - targetEntity = headerTargetEntity; - } else { - targetEntity = LogConstants.UNKNOWN_TARGET_ENTITY; - log.warn("Could not Target Entity: {}", clientRequest.getURI()); - } - return targetEntity; - } - - private void setInvocationId() { - String invocationId = MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID); - if (invocationId == null || invocationId.isEmpty()) - invocationId = UUID.randomUUID().toString(); - MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, invocationId); - } - - - private void processResponse(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================================================="); - } - String statusCode; - if (Response.Status.Family.familyOf(response.getRawStatusCode()).equals(Response.Status.Family.SUCCESSFUL)) { - statusCode = ONAPLogConstants.ResponseStatus.COMPLETED.toString(); - } else { - statusCode = ONAPLogConstants.ResponseStatus.ERROR.toString(); - } - MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE, String.valueOf(response.getRawStatusCode())); - MDC.put(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION, ""); - MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, statusCode); - log.info(ONAPLogConstants.Markers.INVOKE_RETURN, "InvokeReturn"); - clearClientMDCs(); - } - - private void clearClientMDCs() { - MDC.remove(ONAPLogConstants.MDCs.INVOCATION_ID); - MDC.remove(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION); - MDC.remove(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE); - MDC.remove(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION); - MDC.remove(ONAPLogConstants.MDCs.RESPONSE_CODE); - MDC.remove(ONAPLogConstants.MDCs.TARGET_ENTITY); - MDC.remove(ONAPLogConstants.MDCs.PARTNER_NAME); - MDC.remove(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME); - MDC.remove(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP); - } -} diff --git a/common/src/main/java/org/onap/so/logging/spring/interceptor/LoggingInterceptor.java b/common/src/main/java/org/onap/so/logging/spring/interceptor/LoggingInterceptor.java deleted file mode 100644 index fa5a5d5da4..0000000000 --- a/common/src/main/java/org/onap/so/logging/spring/interceptor/LoggingInterceptor.java +++ /dev/null @@ -1,132 +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.spring.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.servlet.http.HttpServletResponse; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.Response; -import javax.ws.rs.ext.Providers; -import org.onap.logging.ref.slf4j.ONAPLogConstants; -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; -import org.springframework.web.servlet.ModelAndView; -import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; - -@Component -public class LoggingInterceptor extends HandlerInterceptorAdapter { - - Logger logger = LoggerFactory.getLogger(LoggingInterceptor.class); - - @Autowired - private MDCSetup mdcSetup; - - @Context - private Providers providers; - - @Override - public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) - throws Exception { - - Map<String, String> headers = Collections.list((request).getHeaderNames()).stream() - .collect(Collectors.toMap(h -> h, request::getHeader)); - setRequestId(headers); - setInvocationId(headers); - setServiceName(request); - setMDCPartnerName(headers); - mdcSetup.setClientIPAddress(request); - mdcSetup.setEntryTimeStamp(); - mdcSetup.setInstanceUUID(); - mdcSetup.setServerFQDN(); - MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, ONAPLogConstants.ResponseStatus.INPROGRESS.toString()); - logger.info(ONAPLogConstants.Markers.ENTRY, "Entering"); - if (logger.isDebugEnabled()) - logRequestInformation(request); - return true; - } - - protected void logRequestInformation(HttpServletRequest request) { - Map<String, String> headers = Collections.list((request).getHeaderNames()).stream() - .collect(Collectors.toMap(h -> h, request::getHeader)); - - logger.debug("===========================request begin================================================"); - logger.debug("URI : {}", request.getRequestURI()); - logger.debug("Method : {}", request.getMethod()); - logger.debug("Headers : {}", headers); - logger.debug("==========================request end================================================"); - - } - - @Override - public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, - ModelAndView modelAndView) throws Exception { - setResponseStatusCode(response); - MDC.put(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION, ""); - MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE, String.valueOf(response.getStatus())); - logger.info(ONAPLogConstants.Markers.EXIT, "Exiting."); - MDC.clear(); - } - - protected void setResponseStatusCode(HttpServletResponse response) { - String statusCode; - if (Response.Status.Family.familyOf(response.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); - } - - protected void setServiceName(HttpServletRequest request) { - MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, request.getRequestURI()); - } - - protected void setRequestId(Map<String, String> headers) { - String requestId = headers.get(ONAPLogConstants.Headers.REQUEST_ID.toLowerCase()); - if (requestId == null || requestId.isEmpty()) - requestId = UUID.randomUUID().toString(); - MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, requestId); - } - - protected void setInvocationId(Map<String, String> headers) { - String invocationId = headers.get(ONAPLogConstants.Headers.INVOCATION_ID.toLowerCase()); - if (invocationId == null || invocationId.isEmpty()) - invocationId = UUID.randomUUID().toString(); - MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, invocationId); - } - - protected void setMDCPartnerName(Map<String, String> headers) { - String partnerName = headers.get(ONAPLogConstants.Headers.PARTNER_NAME.toLowerCase()); - if (partnerName == null || partnerName.isEmpty()) - partnerName = ""; - MDC.put(ONAPLogConstants.MDCs.PARTNER_NAME, partnerName); - } - - -} |