diff options
24 files changed, 527 insertions, 499 deletions
diff --git a/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/AbstractAuditLogFilter.java b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/AbstractAuditLogFilter.java index 71d4e31..fd4e95a 100644 --- a/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/AbstractAuditLogFilter.java +++ b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/AbstractAuditLogFilter.java @@ -26,39 +26,38 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; -public abstract class AbstractAuditLogFilter<GenericRequest, GenericResponse> { +public abstract class AbstractAuditLogFilter<GenericRequest, GenericResponse> extends AbstractFilter { protected static final Logger logger = LoggerFactory.getLogger(AbstractAuditLogFilter.class); - protected void pre(MDCSetup mdcSetup, SimpleMap headers, GenericRequest request, - HttpServletRequest httpServletRequest) { + protected void pre(SimpleMap headers, GenericRequest request, HttpServletRequest httpServletRequest) { try { - String requestId = mdcSetup.getRequestId(headers); + String requestId = getRequestId(headers); MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, requestId); - mdcSetup.setInvocationId(headers); + setInvocationId(headers); setServiceName(request); - mdcSetup.setMDCPartnerName(headers); - mdcSetup.setServerFQDN(); - mdcSetup.setClientIPAddress(httpServletRequest); - mdcSetup.setInstanceID(); - mdcSetup.setEntryTimeStamp(); + setMDCPartnerName(headers); + setServerFQDN(); + setClientIPAddress(httpServletRequest); + setInstanceID(); + setEntryTimeStamp(); MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, ONAPLogConstants.ResponseStatus.INPROGRESS.toString()); additionalPreHandling(request); - mdcSetup.setLogTimestamp(); - mdcSetup.setElapsedTime(); + setLogTimestamp(); + setElapsedTime(); logger.info(ONAPLogConstants.Markers.ENTRY, "Entering"); } catch (Exception e) { logger.warn("Error in AbstractInboundFilter pre", e); } } - protected void post(MDCSetup mdcSetup, GenericResponse response) { + protected void post(GenericResponse response) { try { int responseCode = getResponseCode(response); - mdcSetup.setResponseStatusCode(responseCode); + setResponseStatusCode(responseCode); MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE, String.valueOf(responseCode)); - mdcSetup.setResponseDescription(responseCode); - mdcSetup.setLogTimestamp(); - mdcSetup.setElapsedTime(); + setResponseDescription(responseCode); + setLogTimestamp(); + setElapsedTime(); logger.info(ONAPLogConstants.Markers.EXIT, "Exiting."); additionalPostHandling(response); } catch (Exception e) { diff --git a/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/MDCSetup.java b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/AbstractFilter.java index 16fa210..13c88b0 100644 --- a/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/MDCSetup.java +++ b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/AbstractFilter.java @@ -35,17 +35,17 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; -public class MDCSetup { +public abstract class AbstractFilter { - protected static Logger logger = LoggerFactory.getLogger(MDCSetup.class); + protected static Logger logger = LoggerFactory.getLogger(AbstractFilter.class); private static final String INSTANCE_UUID = UUID.randomUUID().toString(); - public void setInstanceID() { + protected void setInstanceID() { MDC.put(ONAPLogConstants.MDCs.INSTANCE_UUID, INSTANCE_UUID); } - public void setServerFQDN() { + protected void setServerFQDN() { String serverFQDN = ""; InetAddress addr = null; try { @@ -59,7 +59,7 @@ public class MDCSetup { MDC.put(ONAPLogConstants.MDCs.SERVER_FQDN, serverFQDN); } - public void setClientIPAddress(HttpServletRequest httpServletRequest) { + protected void setClientIPAddress(HttpServletRequest httpServletRequest) { String clientIpAddress = ""; if (httpServletRequest != null) { // This logic is to avoid setting the client ip address to that of the load @@ -74,16 +74,12 @@ public class MDCSetup { MDC.put(ONAPLogConstants.MDCs.CLIENT_IP_ADDRESS, clientIpAddress); } - public void setEntryTimeStamp() { + protected 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 String getRequestId(SimpleMap headers) { + protected String getRequestId(SimpleMap headers) { logger.trace("Checking X-ONAP-RequestID header for requestId."); String requestId = headers.get(ONAPLogConstants.Headers.REQUEST_ID); if (requestId != null && !requestId.isEmpty()) { @@ -112,21 +108,21 @@ public class MDCSetup { return UUID.randomUUID().toString(); } - public void setInvocationId(SimpleMap headers) { + protected void setInvocationId(SimpleMap 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 setInvocationIdFromMDC() { + protected void setInvocationIdFromMDC() { String invocationId = MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID); if (invocationId == null || invocationId.isEmpty()) invocationId = UUID.randomUUID().toString(); MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, invocationId); } - public void setMDCPartnerName(SimpleMap headers) { + protected void setMDCPartnerName(SimpleMap headers) { logger.trace("Checking X-ONAP-PartnerName header for partnerName."); String partnerName = headers.get(ONAPLogConstants.Headers.PARTNER_NAME); if (partnerName == null || partnerName.isEmpty()) { @@ -144,12 +140,12 @@ public class MDCSetup { MDC.put(ONAPLogConstants.MDCs.PARTNER_NAME, partnerName); } - public void setLogTimestamp() { + protected void setLogTimestamp() { MDC.put(ONAPLogConstants.MDCs.LOG_TIMESTAMP, ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT)); } - public void setElapsedTime() { + protected void setElapsedTime() { DateTimeFormatter timeFormatter = DateTimeFormatter.ISO_ZONED_DATE_TIME; ZonedDateTime entryTimestamp = ZonedDateTime.parse(MDC.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP), timeFormatter); @@ -159,7 +155,7 @@ public class MDCSetup { Long.toString(ChronoUnit.MILLIS.between(entryTimestamp, endTimestamp))); } - public void setElapsedTimeInvokeTimestamp() { + protected void setElapsedTimeInvokeTimestamp() { DateTimeFormatter timeFormatter = DateTimeFormatter.ISO_ZONED_DATE_TIME; ZonedDateTime entryTimestamp = ZonedDateTime.parse(MDC.get(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP), timeFormatter); @@ -169,7 +165,7 @@ public class MDCSetup { Long.toString(ChronoUnit.MILLIS.between(entryTimestamp, endTimestamp))); } - public void setResponseStatusCode(int code) { + protected void setResponseStatusCode(int code) { String statusCode; if (Response.Status.Family.familyOf(code).equals(Response.Status.Family.SUCCESSFUL)) { statusCode = ONAPLogConstants.ResponseStatus.COMPLETE.toString(); @@ -181,11 +177,11 @@ public class MDCSetup { MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, statusCode); } - public void setTargetEntity(ONAPComponentsList targetEntity) { + protected void setTargetEntity(ONAPComponents targetEntity) { MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY, targetEntity.toString()); } - public void clearClientMDCs() { + protected void clearClientMDCs() { MDC.remove(ONAPLogConstants.MDCs.INVOCATION_ID); MDC.remove(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION); MDC.remove(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE); @@ -197,16 +193,30 @@ public class MDCSetup { MDC.remove(ONAPLogConstants.MDCs.ERROR_DESC); } - public void setResponseDescription(int statusCode) { + protected void setResponseDescription(int statusCode) { MDC.put(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION, Response.Status.fromStatusCode(statusCode).toString()); } - public void setErrorCode(int statusCode) { + protected void setErrorCode(int statusCode) { MDC.put(ONAPLogConstants.MDCs.ERROR_CODE, String.valueOf(statusCode)); } - public void setErrorDesc(int statusCode) { + protected void setErrorDesc(int statusCode) { MDC.put(ONAPLogConstants.MDCs.ERROR_DESC, Response.Status.fromStatusCode(statusCode).toString()); } + protected String getProperty(String property) { + logger.info("Checking for system property [{}]", property); + String propertyValue = System.getProperty(property); + if (propertyValue == null || propertyValue.isEmpty()) { + logger.info("System property was null or empty. Checking environment variable for: {}", property); + propertyValue = System.getenv(property); + if (propertyValue == null || propertyValue.isEmpty()) { + logger.info("Environment variable: {} was null or empty. Returning value: {}", property, + Constants.DefaultValues.UNKNOWN); + propertyValue = Constants.DefaultValues.UNKNOWN; + } + } + return propertyValue; + } } diff --git a/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/AbstractMetricLogFilter.java b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/AbstractMetricLogFilter.java new file mode 100644 index 0000000..7857af9 --- /dev/null +++ b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/AbstractMetricLogFilter.java @@ -0,0 +1,128 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - Logging + * ================================================================================ + * Copyright (C) 2019 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.logging.filter.base; + +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.util.UUID; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.slf4j.Marker; +import org.slf4j.MarkerFactory; + +public abstract class AbstractMetricLogFilter<Request, Response, RequestHeaders> extends AbstractFilter { + protected static final Logger logger = LoggerFactory.getLogger(AbstractMetricLogFilter.class); + private final String partnerName; + private static final Marker INVOKE_RETURN = MarkerFactory.getMarker("INVOKE-RETURN"); + + public AbstractMetricLogFilter() { + partnerName = getPartnerName(); + } + + protected abstract void addHeader(RequestHeaders requestHeaders, String headerName, String headerValue); + + protected abstract String getTargetServiceName(Request request); + + protected abstract String getServiceName(Request request); + + protected abstract int getHttpStatusCode(Response response); + + protected abstract String getResponseCode(Response response); + + protected abstract String getTargetEntity(Request request); + + protected void pre(Request request, RequestHeaders requestHeaders) { + try { + setupMDC(request); + setupHeaders(request, requestHeaders); + logger.info(ONAPLogConstants.Markers.INVOKE, "Invoke"); + } catch (Exception e) { + logger.warn("Error in AbstractMetricLogFilter pre", e); + } + } + + protected void setupHeaders(Request clientRequest, RequestHeaders requestHeaders) { + String requestId = extractRequestID(); + addHeader(requestHeaders, ONAPLogConstants.Headers.REQUEST_ID, requestId); + addHeader(requestHeaders, Constants.HttpHeaders.HEADER_REQUEST_ID, requestId); + addHeader(requestHeaders, Constants.HttpHeaders.TRANSACTION_ID, requestId); + addHeader(requestHeaders, Constants.HttpHeaders.ECOMP_REQUEST_ID, requestId); + addHeader(requestHeaders, ONAPLogConstants.Headers.INVOCATION_ID, MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID)); + addHeader(requestHeaders, ONAPLogConstants.Headers.PARTNER_NAME, partnerName); + } + + protected void setupMDC(Request request) { + MDC.put(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP, + ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT)); + MDC.put(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME, getTargetServiceName(request)); + MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, ONAPLogConstants.ResponseStatus.INPROGRESS.toString()); + setInvocationIdFromMDC(); + + if (MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY) == null) { + String targetEntity = getTargetEntity(request); + if (targetEntity != null) { + MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY, targetEntity); + } else { + MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY, Constants.DefaultValues.UNKNOWN_TARGET_ENTITY); + } + } + + if (MDC.get(ONAPLogConstants.MDCs.SERVICE_NAME) == null) { + MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, getServiceName(request)); + } + setServerFQDN(); + } + + protected String extractRequestID() { + String requestId = MDC.get(ONAPLogConstants.MDCs.REQUEST_ID); + if (requestId == null || requestId.isEmpty()) { + requestId = UUID.randomUUID().toString(); + setLogTimestamp(); + setElapsedTimeInvokeTimestamp(); + logger.warn("No value found in MDC when checking key {} value will be set to {}", + ONAPLogConstants.MDCs.REQUEST_ID, requestId); + MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, requestId); + } + return requestId; + } + + protected void post(Request request, Response response) { + try { + setLogTimestamp(); + setElapsedTimeInvokeTimestamp(); + setResponseStatusCode(getHttpStatusCode(response)); + setResponseDescription(getHttpStatusCode(response)); + MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE, getResponseCode(response)); + logger.info(INVOKE_RETURN, "InvokeReturn"); + clearClientMDCs(); + } catch (Exception e) { + logger.warn("Error in AbstractMetricLogFilter post", e); + } + } + + protected String getPartnerName() { + return getProperty(Constants.Property.PARTNER_NAME); + } + +} diff --git a/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/AuditLogContainerFilter.java b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/AuditLogContainerFilter.java index 3d04b62..4783e7b 100644 --- a/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/AuditLogContainerFilter.java +++ b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/AuditLogContainerFilter.java @@ -48,18 +48,16 @@ public class AuditLogContainerFilter extends AbstractAuditLogFilter<ContainerReq @Context private Providers providers; - private MDCSetup mdcSetup = new MDCSetup(); - @Override public void filter(ContainerRequestContext containerRequest) { SimpleMap headers = new SimpleJaxrsHeadersMap(containerRequest.getHeaders()); - pre(mdcSetup, headers, containerRequest, httpServletRequest); + pre(headers, containerRequest, httpServletRequest); } @Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { - post(mdcSetup, responseContext); + post(responseContext); } @Override diff --git a/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/AuditLogServletFilter.java b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/AuditLogServletFilter.java index ac7529f..a8f5eae 100644 --- a/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/AuditLogServletFilter.java +++ b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/AuditLogServletFilter.java @@ -45,15 +45,14 @@ public class AuditLogServletFilter extends AbstractAuditLogFilter<HttpServletReq @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain filterChain) throws IOException, ServletException { - MDCSetup mdcSetup = new MDCSetup(); try { if (request != null && request instanceof HttpServletRequest) { - pre((HttpServletRequest) request, mdcSetup); + pre((HttpServletRequest) request); } filterChain.doFilter(request, response); } finally { if (request != null && request instanceof HttpServletRequest) { - post((HttpServletRequest) request, (HttpServletResponse) response, mdcSetup); + post((HttpServletRequest) request, (HttpServletResponse) response); } MDC.clear(); } @@ -64,9 +63,9 @@ public class AuditLogServletFilter extends AbstractAuditLogFilter<HttpServletReq // this method does nothing } - protected void pre(HttpServletRequest request, MDCSetup mdcSetup) { + protected void pre(HttpServletRequest request) { SimpleMap headers = new SimpleServletHeadersMap(request); - pre(mdcSetup, headers, request, request); + pre(headers, request, request); } @Override @@ -74,8 +73,8 @@ public class AuditLogServletFilter extends AbstractAuditLogFilter<HttpServletReq MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, request.getRequestURI()); } - private void post(HttpServletRequest request, HttpServletResponse response, MDCSetup mdcSetup) { - post(mdcSetup, response); + private void post(HttpServletRequest request, HttpServletResponse response) { + post(response); } @Override diff --git a/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/MetricLogClientFilter.java b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/MetricLogClientFilter.java index 8533456..986d189 100644 --- a/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/MetricLogClientFilter.java +++ b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/MetricLogClientFilter.java @@ -20,10 +20,6 @@ package org.onap.logging.filter.base; -import java.time.ZoneOffset; -import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; -import java.util.UUID; import javax.annotation.Priority; import javax.ws.rs.client.ClientRequestContext; import javax.ws.rs.client.ClientRequestFilter; @@ -32,97 +28,53 @@ import javax.ws.rs.client.ClientResponseFilter; import javax.ws.rs.core.Context; import javax.ws.rs.core.MultivaluedMap; 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.slf4j.Marker; -import org.slf4j.MarkerFactory; @Priority(0) -public class MetricLogClientFilter implements ClientRequestFilter, ClientResponseFilter { +public class MetricLogClientFilter + extends AbstractMetricLogFilter<ClientRequestContext, ClientResponseContext, MultivaluedMap<String, Object>> + implements ClientRequestFilter, ClientResponseFilter { @Context private Providers providers; - private MDCSetup mdcSetup = new MDCSetup(); - private static final String TRACE = "trace-#"; - private static Logger logger = LoggerFactory.getLogger(MetricLogClientFilter.class); - private final String partnerName; - private static final Marker INVOKE_RETURN = MarkerFactory.getMarker("INVOKE-RETURN"); - public MetricLogClientFilter() { - partnerName = getPartnerName(); + @Override + public void filter(ClientRequestContext clientRequest) { + pre(clientRequest, clientRequest.getHeaders()); } @Override - public void filter(ClientRequestContext clientRequest) { - try { - setupMDC(clientRequest); - setupHeaders(clientRequest); - logger.info(ONAPLogConstants.Markers.INVOKE, "Invoke"); - } catch (Exception e) { - logger.warn("Error in JAX-RS client request filter", e); - } + public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) { + post(requestContext, responseContext); } - protected void setupHeaders(ClientRequestContext clientRequest) { - MultivaluedMap<String, Object> headers = clientRequest.getHeaders(); - String requestId = extractRequestID(clientRequest); - headers.add(ONAPLogConstants.Headers.REQUEST_ID, requestId); - headers.add(Constants.HttpHeaders.HEADER_REQUEST_ID, requestId); - headers.add(Constants.HttpHeaders.TRANSACTION_ID, requestId); - headers.add(Constants.HttpHeaders.ECOMP_REQUEST_ID, requestId); - headers.add(ONAPLogConstants.Headers.INVOCATION_ID, MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID)); - headers.add(ONAPLogConstants.Headers.PARTNER_NAME, partnerName); + @Override + protected void addHeader(MultivaluedMap<String, Object> requestHeaders, String headerName, String headerValue) { + requestHeaders.add(headerName, headerValue); } - protected 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()); - mdcSetup.setInvocationIdFromMDC(); - String targetEntity = MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY); - if (targetEntity != null) { - MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY, targetEntity); - } else { - MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY, Constants.DefaultValues.UNKNOWN_TARGET_ENTITY); - } - if (MDC.get(ONAPLogConstants.MDCs.SERVICE_NAME) == null) { - MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, clientRequest.getUri().getPath()); - } - mdcSetup.setServerFQDN(); + @Override + protected String getTargetServiceName(ClientRequestContext request) { + return request.getUri().toString(); } - protected String extractRequestID(ClientRequestContext clientRequest) { - String requestId = MDC.get(ONAPLogConstants.MDCs.REQUEST_ID); - if (requestId == null || requestId.isEmpty() || requestId.equals(TRACE)) { - requestId = UUID.randomUUID().toString(); - mdcSetup.setLogTimestamp(); - mdcSetup.setElapsedTimeInvokeTimestamp(); - logger.warn("Could not Find Request ID Generating New One: {}", clientRequest.getUri().getPath()); - MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, requestId); - } - return requestId; + @Override + protected String getServiceName(ClientRequestContext request) { + return request.getUri().getPath(); } @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(); - } catch (Exception e) { - logger.warn("Error in JAX-RS request,response client filter", e); - } + protected int getHttpStatusCode(ClientResponseContext response) { + return response.getStatus(); + } + + @Override + protected String getResponseCode(ClientResponseContext response) { + return String.valueOf(response.getStatus()); } - protected String getPartnerName() { - PropertyUtil p = new PropertyUtil(); - return p.getProperty(Constants.Property.PARTNER_NAME); + @Override + protected String getTargetEntity(ClientRequestContext request) { + return Constants.DefaultValues.UNKNOWN_TARGET_ENTITY; } + } diff --git a/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/PayloadLoggingClientFilter.java b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/PayloadLoggingClientFilter.java index 045a729..3777719 100644 --- a/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/PayloadLoggingClientFilter.java +++ b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/PayloadLoggingClientFilter.java @@ -56,10 +56,6 @@ public class PayloadLoggingClientFilter implements ClientRequestFilter, ClientRe 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()) { @@ -87,9 +83,8 @@ public class PayloadLoggingClientFilter implements ClientRequestFilter, ClientRe requestContext.setProperty(ENTITY_STREAM_PROPERTY, stream); } String method = formatMethod(requestContext); - log(new StringBuilder("Making " + method + " request to: " + requestContext.getUri() + "\nRequest Headers: " - + getHeaders(requestContext.getHeaders()))); - + logger.debug("Sending HTTP {} to:{} with request headers:{}", method, requestContext.getUri(), + getHeaders(requestContext.getHeaders())); } protected String getHeaders(MultivaluedMap<String, Object> headers) { @@ -107,10 +102,10 @@ public class PayloadLoggingClientFilter implements ClientRequestFilter, ClientRe 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())); } + String method = formatMethod(requestContext); + logger.debug("Response from method:{} performed on uri:{} has http status code:{} and response headers:{}", + method, requestContext.getUri(), responseContext.getStatus(), responseContext.getHeaders().toString()); } @Override @@ -118,7 +113,7 @@ public class PayloadLoggingClientFilter implements ClientRequestFilter, ClientRe final LoggingStream stream = (LoggingStream) context.getProperty(ENTITY_STREAM_PROPERTY); context.proceed(); if (stream != null) { - log(stream.getStringBuilder(DEFAULT_CHARSET)); + logger.debug(stream.getStringBuilder(DEFAULT_CHARSET).toString()); } } diff --git a/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/PayloadLoggingServletFilter.java b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/PayloadLoggingServletFilter.java index 3e85b9d..4b9cd1f 100644 --- a/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/PayloadLoggingServletFilter.java +++ b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/PayloadLoggingServletFilter.java @@ -205,18 +205,7 @@ public class PayloadLoggingServletFilter implements Filter { requestHeaders.append(":"); requestHeaders.append(httpRequest.getRequestURL().toString()); requestHeaders.append("|"); - String header; - for (Enumeration<String> e = httpRequest.getHeaderNames(); e.hasMoreElements();) { - header = e.nextElement(); - requestHeaders.append(header); - requestHeaders.append(":"); - if (header.equalsIgnoreCase(HttpHeaders.AUTHORIZATION)) { - requestHeaders.append(REDACTED); - } else { - requestHeaders.append(httpRequest.getHeader(header)); - } - requestHeaders.append(";"); - } + requestHeaders.append(getSecureRequestHeaders(httpRequest)); log.info(requestHeaders.toString()); log.info("REQUEST BODY|" + new String(bufferedRequest.getBuffer())); @@ -259,13 +248,7 @@ public class PayloadLoggingServletFilter implements Filter { try { byte[] bytes = baos.toByteArray(); StringBuilder responseHeaders = new StringBuilder("RESPONSE HEADERS|"); - - for (String headerName : response.getHeaderNames()) { - responseHeaders.append(headerName); - responseHeaders.append(":"); - responseHeaders.append(response.getHeader(headerName)); - responseHeaders.append(";"); - } + responseHeaders.append(formatResponseHeaders(response)); responseHeaders.append("Status:"); responseHeaders.append(response.getStatus()); responseHeaders.append(";IsCommited:" + wrappedResp.isCommitted()); @@ -346,4 +329,32 @@ public class PayloadLoggingServletFilter implements Filter { } return str.toString(); } + + protected String getSecureRequestHeaders(HttpServletRequest httpRequest) { + StringBuilder sb = new StringBuilder(); + String header; + for (Enumeration<String> e = httpRequest.getHeaderNames(); e.hasMoreElements();) { + header = e.nextElement(); + sb.append(header); + sb.append(":"); + if (header.equalsIgnoreCase(HttpHeaders.AUTHORIZATION)) { + sb.append(REDACTED); + } else { + sb.append(httpRequest.getHeader(header)); + } + sb.append(";"); + } + return sb.toString(); + } + + protected String formatResponseHeaders(HttpServletResponse response) { + StringBuilder sb = new StringBuilder(); + for (String headerName : response.getHeaderNames()) { + sb.append(headerName); + sb.append(":"); + sb.append(response.getHeader(headerName)); + sb.append(";"); + } + return sb.toString(); + } } diff --git a/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/PropertyUtil.java b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/PropertyUtil.java deleted file mode 100644 index 5a094eb..0000000 --- a/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/PropertyUtil.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - Logging - * ================================================================================ - * Copyright (C) 2019 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.logging.filter.base; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class PropertyUtil { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - public String getProperty(String property) { - logger.info("Checking for system property [{}]", property); - String propertyValue = System.getProperty(property); - if (propertyValue == null || propertyValue.isEmpty()) { - logger.info("System property was null or empty. Checking environment variable for: {}", property); - propertyValue = System.getenv(property); - if (propertyValue == null || propertyValue.isEmpty()) { - logger.info("Environment variable: {} was null or empty. Returning value: {}", property, - Constants.DefaultValues.UNKNOWN); - propertyValue = Constants.DefaultValues.UNKNOWN; - } - } - return propertyValue; - } -} diff --git a/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/MDCSetupTest.java b/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/AbstractFilterTest.java index 1687c19..cfa74ad 100644 --- a/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/MDCSetupTest.java +++ b/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/AbstractFilterTest.java @@ -32,35 +32,24 @@ import javax.ws.rs.core.MultivaluedMap; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; -import org.onap.logging.filter.base.Constants; -import org.onap.logging.filter.base.MDCSetup; -import org.onap.logging.filter.base.ONAPComponents; -import org.onap.logging.filter.base.SimpleHashMap; -import org.onap.logging.filter.base.SimpleJaxrsHeadersMap; -import org.onap.logging.filter.base.SimpleMap; import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.slf4j.MDC; @RunWith(MockitoJUnitRunner.class) -public class MDCSetupTest { +public class AbstractFilterTest extends AbstractFilter { @Mock private HttpServletRequest httpServletRequest; - @Spy - @InjectMocks - private MDCSetup mdcSetup = new MDCSetup(); - private String requestId = "4d31fe02-4918-4975-942f-fe51a44e6a9b"; private String invocationId = "4d31fe02-4918-4975-942f-fe51a44e6a9a"; @After public void tearDown() { MDC.clear(); + System.clearProperty("partnerName"); } @Test @@ -69,7 +58,7 @@ public class MDCSetupTest { MDC.put(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP, "2019-06-18T02:09:06.024Z"); MDC.put(ONAPLogConstants.MDCs.LOG_TIMESTAMP, "2019-06-18T02:09:06.342Z"); - mdcSetup.setElapsedTime(); + setElapsedTime(); assertEquals(expected, MDC.get(ONAPLogConstants.MDCs.ELAPSED_TIME)); } @@ -79,7 +68,7 @@ public class MDCSetupTest { MDC.put(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP, "2019-06-18T02:09:06.024Z"); MDC.put(ONAPLogConstants.MDCs.LOG_TIMESTAMP, "2019-06-18T02:09:06.342Z"); - mdcSetup.setElapsedTimeInvokeTimestamp(); + setElapsedTimeInvokeTimestamp(); assertEquals(expected, MDC.get(ONAPLogConstants.MDCs.ELAPSED_TIME)); } @@ -87,7 +76,7 @@ public class MDCSetupTest { public void setRequestIdTest() { HashMap<String, String> headers = new HashMap<>(); headers.put(ONAPLogConstants.Headers.REQUEST_ID, requestId); - String fetchedRequestId = mdcSetup.getRequestId(new SimpleHashMap(headers)); + String fetchedRequestId = getRequestId(new SimpleHashMap(headers)); assertEquals(requestId, fetchedRequestId); } @@ -95,7 +84,7 @@ public class MDCSetupTest { public void setRequestIdRequestIdHeaderTest() { HashMap<String, String> headers = new HashMap<>(); headers.put(Constants.HttpHeaders.HEADER_REQUEST_ID, requestId); - String fetchedRequestId = mdcSetup.getRequestId(new SimpleHashMap(headers)); + String fetchedRequestId = getRequestId(new SimpleHashMap(headers)); assertEquals(requestId, fetchedRequestId); } @@ -103,7 +92,7 @@ public class MDCSetupTest { public void setRequestIdTransactionIdHeaderTest() { HashMap<String, String> headers = new HashMap<>(); headers.put(Constants.HttpHeaders.TRANSACTION_ID, requestId); - String fetchedRequestId = mdcSetup.getRequestId(new SimpleHashMap(headers)); + String fetchedRequestId = getRequestId(new SimpleHashMap(headers)); assertEquals(requestId, fetchedRequestId); } @@ -111,14 +100,14 @@ public class MDCSetupTest { public void setRequestIdEcompRequestIdHeaderTest() { HashMap<String, String> headers = new HashMap<>(); headers.put(Constants.HttpHeaders.ECOMP_REQUEST_ID, requestId); - String fetchedRequestId = mdcSetup.getRequestId(new SimpleHashMap(headers)); + String fetchedRequestId = getRequestId(new SimpleHashMap(headers)); assertEquals(requestId, fetchedRequestId); } @Test public void setRequestIdNoHeaderTest() { HashMap<String, String> headers = new HashMap<>(); - String fetchedRequestId = mdcSetup.getRequestId(new SimpleHashMap(headers)); + String fetchedRequestId = getRequestId(new SimpleHashMap(headers)); assertNotNull(fetchedRequestId); } @@ -126,40 +115,40 @@ public class MDCSetupTest { public void setInvocationIdTest() { HashMap<String, String> headers = new HashMap<>(); headers.put(ONAPLogConstants.Headers.INVOCATION_ID, invocationId); - mdcSetup.setInvocationId(new SimpleHashMap(headers)); + setInvocationId(new SimpleHashMap(headers)); assertEquals(invocationId, MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID)); } @Test public void setInvocationIdNoHeaderTest() { HashMap<String, String> headers = new HashMap<>(); - mdcSetup.setInvocationId(new SimpleHashMap(headers)); + setInvocationId(new SimpleHashMap(headers)); assertNotNull(MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID)); } @Test public void setInvovationIdFromMDCTest() { MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, "7b77143c-9b50-410c-ac2f-05758a68e3e8"); - mdcSetup.setInvocationIdFromMDC(); + setInvocationIdFromMDC(); assertEquals("7b77143c-9b50-410c-ac2f-05758a68e3e8", MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID)); } @Test public void setInvocationIdFromMDCNoInvocationIdTest() { - mdcSetup.setInvocationIdFromMDC(); + setInvocationIdFromMDC(); // InvocationId is set to a random UUID assertNotNull(MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID)); } @Test public void setResponseStatusCodeTest() { - mdcSetup.setResponseStatusCode(200); + setResponseStatusCode(200); assertEquals("COMPLETE", MDC.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); } @Test public void setResponseStatusCodeErrorTest() { - mdcSetup.setResponseStatusCode(400); + setResponseStatusCode(400); assertEquals("ERROR", MDC.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); assertEquals("400", MDC.get(ONAPLogConstants.MDCs.ERROR_CODE)); assertEquals("Bad Request", MDC.get(ONAPLogConstants.MDCs.ERROR_DESC)); @@ -177,7 +166,7 @@ public class MDCSetupTest { MDC.put(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME, "SDNC"); MDC.put(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP, "2019-06-18T02:09:06.024Z"); - mdcSetup.clearClientMDCs(); + clearClientMDCs(); assertNull(MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID)); assertNull(MDC.get(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION)); assertNull(MDC.get(ONAPLogConstants.MDCs.ERROR_CODE)); @@ -191,13 +180,13 @@ public class MDCSetupTest { @Test public void setTargetEntityTest() { - mdcSetup.setTargetEntity(ONAPComponents.SO); + setTargetEntity(ONAPComponents.SO); assertEquals("SO", MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); } @Test public void setResponseDescriptionTest() { - mdcSetup.setResponseDescription(502); + setResponseDescription(502); assertEquals("Bad Gateway", MDC.get(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION)); } @@ -207,7 +196,7 @@ public class MDCSetupTest { headerMap.putSingle(ONAPLogConstants.Headers.PARTNER_NAME, "SO"); SimpleMap headers = new SimpleJaxrsHeadersMap(headerMap); - mdcSetup.setMDCPartnerName(headers); + setMDCPartnerName(headers); assertEquals("SO", MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME)); } @@ -218,7 +207,7 @@ public class MDCSetupTest { headerMap.putSingle(HttpHeaders.USER_AGENT, "Apache-HttpClient/4.5.8 (Java/1.8.0_191)"); SimpleMap headers = new SimpleJaxrsHeadersMap(headerMap); - mdcSetup.setMDCPartnerName(headers); + setMDCPartnerName(headers); assertEquals("Apache-HttpClient/4.5.8 (Java/1.8.0_191)", MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME)); } @@ -229,7 +218,7 @@ public class MDCSetupTest { headerMap.putSingle(Constants.HttpHeaders.CLIENT_ID, "SO"); SimpleMap headers = new SimpleJaxrsHeadersMap(headerMap); - mdcSetup.setMDCPartnerName(headers); + setMDCPartnerName(headers); assertEquals("SO", MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME)); } @@ -239,14 +228,14 @@ public class MDCSetupTest { MultivaluedMap<String, String> headerMap = new MultivaluedHashMap<>(); SimpleMap headers = new SimpleJaxrsHeadersMap(headerMap); - mdcSetup.setMDCPartnerName(headers); + setMDCPartnerName(headers); assertEquals("UNKNOWN", MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME)); } @Test public void setServerFQDNTest() { - mdcSetup.setServerFQDN(); + setServerFQDN(); assertNotNull(MDC.get(ONAPLogConstants.MDCs.SERVER_IP_ADDRESS)); assertNotNull(MDC.get(ONAPLogConstants.MDCs.SERVER_FQDN)); } @@ -254,7 +243,7 @@ public class MDCSetupTest { @Test public void setClientIPAddressTest() { when(httpServletRequest.getHeader("X-Forwarded-For")).thenReturn("127.0.0.2"); - mdcSetup.setClientIPAddress(httpServletRequest); + setClientIPAddress(httpServletRequest); assertEquals("127.0.0.2", MDC.get(ONAPLogConstants.MDCs.CLIENT_IP_ADDRESS)); } @@ -262,45 +251,51 @@ public class MDCSetupTest { @Test public void setClientIPAddressNoHeaderTest() { when(httpServletRequest.getRemoteAddr()).thenReturn("127.0.0.1"); - mdcSetup.setClientIPAddress(httpServletRequest); + setClientIPAddress(httpServletRequest); assertEquals("127.0.0.1", MDC.get(ONAPLogConstants.MDCs.CLIENT_IP_ADDRESS)); } @Test public void setClientIPAddressNullTest() { - mdcSetup.setClientIPAddress(null); + setClientIPAddress(null); assertEquals("", MDC.get(ONAPLogConstants.MDCs.CLIENT_IP_ADDRESS)); } @Test public void setEntryTimeStampTest() { - mdcSetup.setEntryTimeStamp(); + setEntryTimeStamp(); assertNotNull(MDC.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP)); } @Test public void setLogTimestampTest() { - mdcSetup.setLogTimestamp(); + setLogTimestamp(); assertNotNull(MDC.get(ONAPLogConstants.MDCs.LOG_TIMESTAMP)); } @Test public void setInstanceIDTest() { - mdcSetup.setInstanceID(); + setInstanceID(); assertNotNull(MDC.get(ONAPLogConstants.MDCs.INSTANCE_UUID)); } @Test - public void setServiceNameTest() { - String requestUri = "onap/so/serviceInstances"; - when(httpServletRequest.getRequestURI()).thenReturn(requestUri); - mdcSetup.setServiceName(httpServletRequest); + public void getPropertyTest() { + System.setProperty("partnerName", "partnerName"); - assertEquals("onap/so/serviceInstances", MDC.get(ONAPLogConstants.MDCs.SERVICE_NAME)); + String partnerName = getProperty("partnerName"); + assertEquals("partnerName", partnerName); } + + @Test + public void getPropertyNullTest() { + String partnerName = getProperty("partner"); + assertEquals("UNKNOWN", partnerName); + } + } diff --git a/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/AuditLogContainerFilterTest.java b/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/AuditLogContainerFilterTest.java index af80b19..119bdf1 100644 --- a/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/AuditLogContainerFilterTest.java +++ b/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/AuditLogContainerFilterTest.java @@ -21,11 +21,11 @@ package org.onap.logging.filter.base; import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.when; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerResponseContext; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.UriInfo; import org.junit.After; import org.junit.Test; @@ -34,14 +34,14 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; -import org.onap.logging.filter.base.AuditLogContainerFilter; -import org.onap.logging.filter.base.MDCSetup; -import org.onap.logging.filter.base.SimpleMap; import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.slf4j.MDC; @RunWith(MockitoJUnitRunner.class) public class AuditLogContainerFilterTest { + protected static final Logger logger = LoggerFactory.getLogger(AbstractMetricLogFilter.class); @Mock private ContainerRequestContext containerRequest; @@ -50,9 +50,6 @@ public class AuditLogContainerFilterTest { private ContainerResponseContext containerResponse; @Mock - private MDCSetup mdcSetup; - - @Mock private UriInfo uriInfo; @Spy @@ -64,11 +61,14 @@ public class AuditLogContainerFilterTest { MDC.clear(); } + @Test public void filterTest() { - when(mdcSetup.getRequestId(any(SimpleMap.class))).thenReturn("e3b08fa3-535f-4c1b-8228-91318d2bb4ee"); + MultivaluedMap<String, String> headerMap = new MultivaluedHashMap<>(); + headerMap.putSingle(ONAPLogConstants.Headers.REQUEST_ID, "e3b08fa3-535f-4c1b-8228-91318d2bb4ee"); + when(containerRequest.getHeaders()).thenReturn(headerMap); when(uriInfo.getPath()).thenReturn("onap/so/serviceInstances"); - doReturn(uriInfo).when(containerRequest).getUriInfo(); + when(containerRequest.getUriInfo()).thenReturn(uriInfo); auditLogContainerFilter.filter(containerRequest); assertEquals("e3b08fa3-535f-4c1b-8228-91318d2bb4ee", MDC.get(ONAPLogConstants.MDCs.REQUEST_ID)); diff --git a/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/AuditLogServletFilterTest.java b/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/AuditLogServletFilterTest.java index 1a0d0ef..f2a8218 100644 --- a/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/AuditLogServletFilterTest.java +++ b/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/AuditLogServletFilterTest.java @@ -21,7 +21,7 @@ package org.onap.logging.filter.base; import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; +import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.when; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; @@ -34,9 +34,6 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; -import org.onap.logging.filter.base.AuditLogServletFilter; -import org.onap.logging.filter.base.MDCSetup; -import org.onap.logging.filter.base.SimpleMap; import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.slf4j.MDC; @@ -50,9 +47,6 @@ public class AuditLogServletFilterTest { private ServletResponse response; @Mock - private MDCSetup mdcSetup; - - @Mock private HttpServletRequest servletRequest; @Mock @@ -69,11 +63,10 @@ public class AuditLogServletFilterTest { @Test public void preTest() { - when(mdcSetup.getRequestId(any(SimpleMap.class))).thenReturn("e3b08fa3-535f-4c1b-8228-91318d2bb4ee"); when(servletRequest.getRequestURI()).thenReturn("onap/so/serviceInstances"); - auditLogServletFilter.pre(servletRequest, mdcSetup); + auditLogServletFilter.pre(servletRequest); - assertEquals("e3b08fa3-535f-4c1b-8228-91318d2bb4ee", MDC.get(ONAPLogConstants.MDCs.REQUEST_ID)); + assertNotNull(MDC.get(ONAPLogConstants.MDCs.REQUEST_ID)); assertEquals("onap/so/serviceInstances", MDC.get(ONAPLogConstants.MDCs.SERVICE_NAME)); assertEquals("INPROGRESS", MDC.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); } @@ -85,4 +78,5 @@ public class AuditLogServletFilterTest { assertEquals(200, responseCode); } + } diff --git a/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/LoggingContainerFilterTest.java b/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/LoggingContainerFilterTest.java index 4f8d16d..4d1f102 100644 --- a/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/LoggingContainerFilterTest.java +++ b/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/LoggingContainerFilterTest.java @@ -24,8 +24,6 @@ import static org.junit.Assert.assertEquals; import javax.ws.rs.core.MultivaluedHashMap; import javax.ws.rs.core.MultivaluedMap; import org.junit.Test; -import org.onap.logging.filter.base.SimpleJaxrsHeadersMap; -import org.onap.logging.filter.base.SimpleMap; import org.onap.logging.ref.slf4j.ONAPLogConstants; public class LoggingContainerFilterTest { diff --git a/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/MetricLogClientFilterTest.java b/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/MetricLogClientFilterTest.java index 9a9f883..ed217aa 100644 --- a/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/MetricLogClientFilterTest.java +++ b/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/MetricLogClientFilterTest.java @@ -23,9 +23,11 @@ package org.onap.logging.filter.base; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.when; import java.net.URI; import java.net.URISyntaxException; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; import javax.ws.rs.client.ClientRequestContext; import javax.ws.rs.core.MultivaluedHashMap; import javax.ws.rs.core.MultivaluedMap; @@ -36,18 +38,11 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; -import org.onap.logging.filter.base.Constants; -import org.onap.logging.filter.base.MDCSetup; -import org.onap.logging.filter.base.MetricLogClientFilter; import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.slf4j.MDC; @RunWith(MockitoJUnitRunner.class) public class MetricLogClientFilterTest { - - @Mock - private MDCSetup mdcSetup; - @Mock private ClientRequestContext clientRequest; @@ -64,10 +59,9 @@ public class MetricLogClientFilterTest { public void setupHeadersTest() { MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, "8819bfb4-69d2-43fc-b0d6-81d2690533ea"); MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>(); - when(clientRequest.getHeaders()).thenReturn(headers); - doReturn("0a908a5d-e774-4558-96ff-6edcbba65483").when(metricLogClientFilter).extractRequestID(clientRequest); + doReturn("0a908a5d-e774-4558-96ff-6edcbba65483").when(metricLogClientFilter).extractRequestID(); - metricLogClientFilter.setupHeaders(clientRequest); + metricLogClientFilter.setupHeaders(clientRequest, headers); assertEquals("0a908a5d-e774-4558-96ff-6edcbba65483", headers.getFirst(ONAPLogConstants.Headers.REQUEST_ID)); assertEquals("0a908a5d-e774-4558-96ff-6edcbba65483", headers.getFirst(Constants.HttpHeaders.HEADER_REQUEST_ID)); @@ -80,6 +74,7 @@ public class MetricLogClientFilterTest { @Test public void setupMDCTest() throws URISyntaxException { + // TODO ingest change from upstream MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY, "SO"); URI uri = new URI("onap/so/serviceInstances"); doReturn(uri).when(clientRequest).getUri(); @@ -110,15 +105,15 @@ public class MetricLogClientFilterTest { @Test public void extractRequestIDTest() { MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, "0a908a5d-e774-4558-96ff-6edcbba65483"); - String requestId = metricLogClientFilter.extractRequestID(clientRequest); + String requestId = metricLogClientFilter.extractRequestID(); assertEquals("0a908a5d-e774-4558-96ff-6edcbba65483", requestId); } @Test public void extractRequestIDNullTest() throws URISyntaxException { - URI uri = new URI("onap/so/serviceInstances"); - doReturn(uri).when(clientRequest).getUri(); - String requestId = metricLogClientFilter.extractRequestID(clientRequest); + MDC.put(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP, + ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT)); + String requestId = metricLogClientFilter.extractRequestID(); assertNotNull(requestId); assertNotNull(ONAPLogConstants.MDCs.LOG_TIMESTAMP); assertNotNull(ONAPLogConstants.MDCs.ELAPSED_TIME); diff --git a/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/PayloadLoggingClientFilterTest.java b/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/PayloadLoggingClientFilterTest.java index 5156516..0290784 100644 --- a/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/PayloadLoggingClientFilterTest.java +++ b/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/PayloadLoggingClientFilterTest.java @@ -33,8 +33,6 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; -import org.onap.logging.filter.base.Constants; -import org.onap.logging.filter.base.PayloadLoggingClientFilter; @RunWith(MockitoJUnitRunner.class) public class PayloadLoggingClientFilterTest { diff --git a/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/PropertyUtilTest.java b/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/PropertyUtilTest.java deleted file mode 100644 index 4ec14bc..0000000 --- a/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/PropertyUtilTest.java +++ /dev/null @@ -1,50 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - Logging - * ================================================================================ - * Copyright (C) 2019 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.logging.filter.base; - -import static org.junit.Assert.assertEquals; -import org.junit.After; -import org.junit.Test; -import org.onap.logging.filter.base.PropertyUtil; - -public class PropertyUtilTest { - - private PropertyUtil propertyUtil = new PropertyUtil(); - - @After - public void tearDown() { - System.clearProperty("partnerName"); - } - - @Test - public void getPropertyTest() { - System.setProperty("partnerName", "partnerName"); - - String partnerName = propertyUtil.getProperty("partnerName"); - assertEquals("partnerName", partnerName); - } - - @Test - public void getPropertyNullTest() { - String partnerName = propertyUtil.getProperty("partner"); - assertEquals("UNKNOWN", partnerName); - } -} diff --git a/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/SimpleJaxrsHeadersMapTest.java b/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/SimpleJaxrsHeadersMapTest.java index a1c5f9b..e2c5da9 100644 --- a/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/SimpleJaxrsHeadersMapTest.java +++ b/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/SimpleJaxrsHeadersMapTest.java @@ -24,8 +24,6 @@ import static org.junit.Assert.assertEquals; import javax.ws.rs.core.MultivaluedHashMap; import javax.ws.rs.core.MultivaluedMap; import org.junit.Test; -import org.onap.logging.filter.base.SimpleJaxrsHeadersMap; -import org.onap.logging.filter.base.SimpleMap; import org.onap.logging.ref.slf4j.ONAPLogConstants; public class SimpleJaxrsHeadersMapTest { diff --git a/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/SimpleServletHeadersMapTest.java b/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/SimpleServletHeadersMapTest.java index f1e6af8..fff6776 100644 --- a/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/SimpleServletHeadersMapTest.java +++ b/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/SimpleServletHeadersMapTest.java @@ -29,7 +29,6 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; -import org.onap.logging.filter.base.SimpleServletHeadersMap; @RunWith(MockitoJUnitRunner.class) public class SimpleServletHeadersMapTest { diff --git a/reference/logging-filter/logging-filter-spring/src/main/java/org/onap/logging/filter/spring/LoggingInterceptor.java b/reference/logging-filter/logging-filter-spring/src/main/java/org/onap/logging/filter/spring/LoggingInterceptor.java index d8d6bf4..dc1918b 100644 --- a/reference/logging-filter/logging-filter-spring/src/main/java/org/onap/logging/filter/spring/LoggingInterceptor.java +++ b/reference/logging-filter/logging-filter-spring/src/main/java/org/onap/logging/filter/spring/LoggingInterceptor.java @@ -18,32 +18,25 @@ * ============LICENSE_END========================================================= */ + package org.onap.logging.filter.spring; -import java.util.Collections; -import java.util.Map; -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.ext.Providers; -import org.onap.logging.filter.base.MDCSetup; +import org.onap.logging.filter.base.AbstractAuditLogFilter; import org.onap.logging.filter.base.SimpleMap; import org.onap.logging.filter.base.SimpleServletHeadersMap; import org.onap.logging.ref.slf4j.ONAPLogConstants; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.slf4j.MDC; import org.springframework.stereotype.Component; +import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; -import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; @Component -public class LoggingInterceptor extends HandlerInterceptorAdapter { - - private static final Logger logger = LoggerFactory.getLogger(LoggingInterceptor.class); - - private MDCSetup mdcSetup = new MDCSetup(); +public class LoggingInterceptor extends AbstractAuditLogFilter<HttpServletRequest, HttpServletResponse> + implements HandlerInterceptor { @Context private Providers providers; @@ -52,45 +45,24 @@ public class LoggingInterceptor extends HandlerInterceptorAdapter { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { SimpleMap headers = new SimpleServletHeadersMap(request); - String requestId = mdcSetup.getRequestId(headers); - MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, requestId); - mdcSetup.setInvocationId(headers); - mdcSetup.setServiceName(request); - mdcSetup.setMDCPartnerName(headers); - mdcSetup.setClientIPAddress(request); - mdcSetup.setEntryTimeStamp(); - mdcSetup.setInstanceID(); - mdcSetup.setServerFQDN(); - MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, ONAPLogConstants.ResponseStatus.INPROGRESS.toString()); - mdcSetup.setLogTimestamp(); - mdcSetup.setElapsedTime(); - logger.info(ONAPLogConstants.Markers.ENTRY, "Entering"); - if (logger.isDebugEnabled()) - logRequestInformation(request); + pre(headers, request, 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 { + post(response); + } + @Override + protected int getResponseCode(HttpServletResponse response) { + return response.getStatus(); } @Override - public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, - ModelAndView modelAndView) throws Exception { - mdcSetup.setResponseStatusCode(response.getStatus()); - mdcSetup.setLogTimestamp(); - mdcSetup.setElapsedTime(); - mdcSetup.setResponseDescription(response.getStatus()); - MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE, String.valueOf(response.getStatus())); - logger.info(ONAPLogConstants.Markers.EXIT, "Exiting."); - MDC.clear(); + protected void setServiceName(HttpServletRequest request) { + MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, request.getRequestURI()); } + } diff --git a/reference/logging-filter/logging-filter-spring/src/main/java/org/onap/logging/filter/spring/SpringClientFilter.java b/reference/logging-filter/logging-filter-spring/src/main/java/org/onap/logging/filter/spring/SpringClientFilter.java index 6eeee1a..1437435 100644 --- a/reference/logging-filter/logging-filter-spring/src/main/java/org/onap/logging/filter/spring/SpringClientFilter.java +++ b/reference/logging-filter/logging-filter-spring/src/main/java/org/onap/logging/filter/spring/SpringClientFilter.java @@ -21,99 +21,69 @@ package org.onap.logging.filter.spring; import java.io.IOException; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.time.ZoneOffset; -import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; import java.util.List; -import java.util.UUID; +import org.onap.logging.filter.base.AbstractMetricLogFilter; import org.onap.logging.filter.base.Constants; -import org.onap.logging.filter.base.MDCSetup; -import org.onap.logging.filter.base.PropertyUtil; import org.onap.logging.ref.slf4j.ONAPLogConstants; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.slf4j.MDC; -import org.slf4j.Marker; -import org.slf4j.MarkerFactory; 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; -public class SpringClientFilter implements ClientHttpRequestInterceptor { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - private static final String TRACE = "trace-#"; - private MDCSetup mdcSetup = new MDCSetup(); - private final String partnerName; - private static final Marker INVOKE_RETURN = MarkerFactory.getMarker("INVOKE-RETURN"); +public class SpringClientFilter extends AbstractMetricLogFilter<HttpRequest, ClientHttpResponse, HttpHeaders> + implements ClientHttpRequestInterceptor { public SpringClientFilter() { - this.partnerName = getPartnerName(); + } @Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { - processRequest(request, body); + pre(request, request.getHeaders()); ClientHttpResponse response = execution.execute(request, body); - processResponse(response); + post(request, response); return response; } - protected void processRequest(HttpRequest request, byte[] body) throws IOException { - mdcSetup.setInvocationIdFromMDC(); - setupMDC(request); - setupHeaders(request); - if (logger.isDebugEnabled()) { - logger.debug("===========================request begin================================================"); - logger.debug("URI : {}", request.getURI()); - logger.debug("Method : {}", request.getMethod()); - logger.debug("Headers : {}", request.getHeaders()); - logger.debug("Request body: {}", new String(body, StandardCharsets.UTF_8)); - logger.debug("==========================request end================================================"); - } + @Override + protected void addHeader(HttpHeaders requestHeaders, String headerName, String headerValue) { + requestHeaders.add(headerName, headerValue); } - protected void setupHeaders(HttpRequest clientRequest) { - HttpHeaders headers = clientRequest.getHeaders(); - String requestId = extractRequestID(clientRequest); - headers.add(ONAPLogConstants.Headers.REQUEST_ID, requestId); - headers.add(Constants.HttpHeaders.HEADER_REQUEST_ID, requestId); - headers.add(Constants.HttpHeaders.TRANSACTION_ID, requestId); - headers.add(Constants.HttpHeaders.ECOMP_REQUEST_ID, requestId); - headers.add(ONAPLogConstants.Headers.INVOCATION_ID, MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID)); - headers.add(ONAPLogConstants.Headers.PARTNER_NAME, partnerName); + @Override + protected String getTargetServiceName(HttpRequest request) { + return request.getURI().toString(); + } + + @Override + protected String getServiceName(HttpRequest request) { + return request.getURI().getPath(); } - protected String extractRequestID(HttpRequest clientRequest) { - String requestId = MDC.get(ONAPLogConstants.MDCs.REQUEST_ID); - if (requestId == null || requestId.isEmpty() || requestId.equals(TRACE)) { - requestId = UUID.randomUUID().toString(); - mdcSetup.setLogTimestamp(); - mdcSetup.setElapsedTimeInvokeTimestamp(); - logger.warn("Could not Find Request ID Generating New One: {}", clientRequest.getURI()); - MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, requestId); + @Override + protected int getHttpStatusCode(ClientHttpResponse response) { + try { + return response.getStatusCode().value(); + } catch (IOException e) { + // TODO figure out the right thing to do here + return 500; } - return requestId; } - protected 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)); - if (MDC.get(ONAPLogConstants.MDCs.SERVICE_NAME) == null) { - MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, clientRequest.getURI().getPath()); + @Override + protected String getResponseCode(ClientHttpResponse response) { + try { + return response.getStatusCode().toString(); + } catch (IOException e) { + return "500"; } - mdcSetup.setServerFQDN(); } - protected String extractTargetEntity(HttpRequest clientRequest) { + @Override + protected String getTargetEntity(HttpRequest clientRequest) { HttpHeaders headers = clientRequest.getHeaders(); String headerTargetEntity = null; List<String> headerTargetEntityList = headers.get(Constants.HttpHeaders.TARGET_ENTITY_HEADER); @@ -131,27 +101,4 @@ public class SpringClientFilter implements ClientHttpRequestInterceptor { return targetEntity; } - 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(); - } - - protected String getPartnerName() { - PropertyUtil p = new PropertyUtil(); - return p.getProperty(Constants.Property.PARTNER_NAME); - } } diff --git a/reference/logging-filter/logging-filter-spring/src/main/java/org/onap/logging/filter/spring/SpringClientPayloadFilter.java b/reference/logging-filter/logging-filter-spring/src/main/java/org/onap/logging/filter/spring/SpringClientPayloadFilter.java new file mode 100644 index 0000000..47ea031 --- /dev/null +++ b/reference/logging-filter/logging-filter-spring/src/main/java/org/onap/logging/filter/spring/SpringClientPayloadFilter.java @@ -0,0 +1,69 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - Logging + * ================================================================================ + * Copyright (C) 2019 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.logging.filter.spring; + +import java.io.IOException; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +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; + +public class SpringClientPayloadFilter implements ClientHttpRequestInterceptor { + private final Logger logger = 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; + } + + protected void logRequest(HttpRequest request, byte[] body) throws IOException { + if (logger.isDebugEnabled()) { + logger.debug("===========================request begin================================================"); + logger.debug("URI : {}", request.getURI()); + logger.debug("Method : {}", request.getMethod()); + logger.debug("Headers : {}", request.getHeaders()); + logger.debug("Request body: {}", new String(body, StandardCharsets.UTF_8)); + logger.debug("==========================request end================================================"); + } + } + + protected void logResponse(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================================================="); + } + } + +} diff --git a/reference/logging-filter/logging-filter-spring/src/main/java/org/onap/logging/filter/spring/StatusLoggingInterceptor.java b/reference/logging-filter/logging-filter-spring/src/main/java/org/onap/logging/filter/spring/StatusLoggingInterceptor.java new file mode 100644 index 0000000..887e621 --- /dev/null +++ b/reference/logging-filter/logging-filter-spring/src/main/java/org/onap/logging/filter/spring/StatusLoggingInterceptor.java @@ -0,0 +1,74 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - Logging + * ================================================================================ + * Copyright (C) 2019 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.logging.filter.spring; + +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.filter.base.PayloadLoggingServletFilter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.HandlerInterceptor; +import org.springframework.web.servlet.ModelAndView; + +// TODO do we want this class to log message payloads? In the previous implementation it did not +@Component +public class StatusLoggingInterceptor extends PayloadLoggingServletFilter implements HandlerInterceptor { + + private static final Logger logger = LoggerFactory.getLogger(StatusLoggingInterceptor.class); + + @Context + private Providers providers; + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) + throws Exception { + if (logger.isDebugEnabled()) { + logRequestInformation(request); + } + return true; + } + + protected void logRequestInformation(HttpServletRequest request) { + logger.debug("===========================request begin================================================"); + logger.debug("URI : {}", request.getRequestURI()); + logger.debug("Method : {}", request.getMethod()); + logger.debug("Headers : {}", getSecureRequestHeaders(request)); + logger.debug("==========================request end================================================"); + } + + // TODO previously no response information was being logged, I followed the format in SpringClientPayloadFilter + @Override + public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, + ModelAndView modelAndView) throws Exception { + if (logger.isDebugEnabled()) { + logger.debug("============================response begin=========================================="); + logger.debug("Status code : {}", response.getStatus()); + logger.debug("Status text : {}", Response.Status.fromStatusCode(response.getStatus())); + logger.debug("Headers : {}", formatResponseHeaders(response)); + logger.debug("=======================response end================================================="); + } + } +} diff --git a/reference/logging-filter/logging-filter-spring/src/test/java/org/onap/logging/filter/spring/LoggingInterceptorTest.java b/reference/logging-filter/logging-filter-spring/src/test/java/org/onap/logging/filter/spring/LoggingInterceptorTest.java index 1a6d701..1d373dc 100644 --- a/reference/logging-filter/logging-filter-spring/src/test/java/org/onap/logging/filter/spring/LoggingInterceptorTest.java +++ b/reference/logging-filter/logging-filter-spring/src/test/java/org/onap/logging/filter/spring/LoggingInterceptorTest.java @@ -21,8 +21,7 @@ package org.onap.logging.filter.spring; import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; +import static org.junit.Assert.assertNotNull; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.Test; @@ -31,8 +30,6 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; -import org.onap.logging.filter.base.MDCSetup; -import org.onap.logging.filter.base.SimpleMap; import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.slf4j.MDC; @@ -48,18 +45,14 @@ public class LoggingInterceptorTest { @Mock private Object handler; - @Mock - private MDCSetup mdcSetup; - @Spy @InjectMocks private LoggingInterceptor loggingInterceptor; @Test public void preHandleTest() throws Exception { - when(mdcSetup.getRequestId(any(SimpleMap.class))).thenReturn("428443e6-eeb2-4e4a-9a8c-2ca9e2bc8067"); loggingInterceptor.preHandle(request, response, handler); assertEquals(MDC.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE), "INPROGRESS"); - assertEquals("428443e6-eeb2-4e4a-9a8c-2ca9e2bc8067", MDC.get(ONAPLogConstants.MDCs.REQUEST_ID)); + assertNotNull(MDC.get(ONAPLogConstants.MDCs.REQUEST_ID)); } } diff --git a/reference/logging-filter/logging-filter-spring/src/test/java/org/onap/logging/filter/spring/SpringClientFilterTest.java b/reference/logging-filter/logging-filter-spring/src/test/java/org/onap/logging/filter/spring/SpringClientFilterTest.java index 9de5d68..3836ab7 100644 --- a/reference/logging-filter/logging-filter-spring/src/test/java/org/onap/logging/filter/spring/SpringClientFilterTest.java +++ b/reference/logging-filter/logging-filter-spring/src/test/java/org/onap/logging/filter/spring/SpringClientFilterTest.java @@ -22,12 +22,14 @@ package org.onap.logging.filter.spring; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.when; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; @@ -35,8 +37,8 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; +import org.onap.logging.filter.base.AbstractFilter; import org.onap.logging.filter.base.Constants; -import org.onap.logging.filter.base.MDCSetup; import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.slf4j.MDC; import org.springframework.http.HttpHeaders; @@ -45,10 +47,10 @@ import org.springframework.http.client.ClientHttpRequestExecution; import org.springframework.http.client.ClientHttpResponse; @RunWith(MockitoJUnitRunner.class) -public class SpringClientFilterTest { +public class SpringClientFilterTest extends SpringClientFilter { @Mock - private MDCSetup mdcSetup; + private AbstractFilter mdcSetup; @Mock private ClientHttpResponse response; @@ -70,8 +72,7 @@ public class SpringClientFilterTest { @Test public void processResponseTest() throws IOException { - String partnerName = springClientFilter.getPartnerName(); - + String partnerName = getPartnerName(); assertEquals("UNKNOWN", partnerName); } @@ -81,7 +82,7 @@ public class SpringClientFilterTest { headers.add(Constants.HttpHeaders.TARGET_ENTITY_HEADER, "SO"); when(clientRequest.getHeaders()).thenReturn(headers); - String targetEntity = springClientFilter.extractTargetEntity(clientRequest); + String targetEntity = springClientFilter.getTargetEntity(clientRequest); assertEquals("SO", targetEntity); } @@ -91,7 +92,7 @@ public class SpringClientFilterTest { HttpHeaders headers = new HttpHeaders(); when(clientRequest.getHeaders()).thenReturn(headers); - String targetEntity = springClientFilter.extractTargetEntity(clientRequest); + String targetEntity = springClientFilter.getTargetEntity(clientRequest); assertEquals("SO", targetEntity); } @@ -100,20 +101,17 @@ public class SpringClientFilterTest { HttpHeaders headers = new HttpHeaders(); when(clientRequest.getHeaders()).thenReturn(headers); - String targetEntity = springClientFilter.extractTargetEntity(clientRequest); + String targetEntity = springClientFilter.getTargetEntity(clientRequest); assertEquals("Unknown-Target-Entity", targetEntity); } @Test public void setupMDCTest() throws URISyntaxException { - doReturn("SO").when(springClientFilter).extractTargetEntity(clientRequest); URI uri = new URI("onap/so/serviceInstances"); when(clientRequest.getURI()).thenReturn(uri); - - springClientFilter.setupMDC(clientRequest); - + when(clientRequest.getHeaders()).thenReturn(new HttpHeaders()); + setupMDC(clientRequest); assertEquals("onap/so/serviceInstances", MDC.get(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME)); - assertEquals("SO", MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); assertEquals("INPROGRESS", MDC.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); assertNotNull(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE); assertNotNull(ONAPLogConstants.MDCs.SERVICE_NAME); @@ -123,11 +121,10 @@ public class SpringClientFilterTest { @Test public void setupHeadersTest() { MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, "8819bfb4-69d2-43fc-b0d6-81d2690533ea"); - HttpHeaders headers = new HttpHeaders(); - when(clientRequest.getHeaders()).thenReturn(headers); - doReturn("0a908a5d-e774-4558-96ff-6edcbba65483").when(springClientFilter).extractRequestID(clientRequest); + MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, "0a908a5d-e774-4558-96ff-6edcbba65483"); - springClientFilter.setupHeaders(clientRequest); + HttpHeaders headers = new HttpHeaders(); + setupHeaders(clientRequest, headers); assertEquals("0a908a5d-e774-4558-96ff-6edcbba65483", headers.getFirst(ONAPLogConstants.Headers.REQUEST_ID)); assertEquals("0a908a5d-e774-4558-96ff-6edcbba65483", headers.getFirst(Constants.HttpHeaders.HEADER_REQUEST_ID)); @@ -141,13 +138,16 @@ public class SpringClientFilterTest { @Test public void extractRequestIDTest() { MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, "0a908a5d-e774-4558-96ff-6edcbba65483"); - String requestId = springClientFilter.extractRequestID(clientRequest); + String requestId = extractRequestID(); assertEquals("0a908a5d-e774-4558-96ff-6edcbba65483", requestId); } @Test public void extractRequestIDNullTest() { - String requestId = springClientFilter.extractRequestID(clientRequest); + // NPE exception will occur when extractRequestID is called if INVOKE_TIMESTAMP is null + MDC.put(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP, + ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT)); + String requestId = extractRequestID(); assertNotNull(requestId); assertNotNull(ONAPLogConstants.MDCs.LOG_TIMESTAMP); assertNotNull(ONAPLogConstants.MDCs.ELAPSED_TIME); @@ -156,10 +156,7 @@ public class SpringClientFilterTest { @Test public void interceptTest() throws IOException { byte[] body = new byte[3]; - doNothing().when(springClientFilter).processRequest(clientRequest, body); doReturn(response).when(execution).execute(clientRequest, body); - doNothing().when(springClientFilter).processResponse(response); - ClientHttpResponse httpResponse = springClientFilter.intercept(clientRequest, body, execution); assertEquals(response, httpResponse); } |