diff options
Diffstat (limited to 'openecomp-be/lib/openecomp-sdc-logging-lib')
39 files changed, 176 insertions, 358 deletions
diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/LoggingConstants.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/LoggingConstants.java index e8635b2418..522ad28caf 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/LoggingConstants.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/LoggingConstants.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging; /** @@ -28,7 +27,6 @@ public class LoggingConstants { * Default HTTP header for propagation of a request ID for distributed tracing. */ public static final String DEFAULT_REQUEST_ID_HEADER = "X-ECOMP-RequestID"; - /** * Default HTTP header for exchanging a partner name between components. */ diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/AuditData.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/AuditData.java index 090f680aa7..8bf8852354 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/AuditData.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/AuditData.java @@ -13,15 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.api; -import org.onap.logging.ref.slf4j.ONAPLogConstants.ResponseStatus; import lombok.Getter; +import org.onap.logging.ref.slf4j.ONAPLogConstants.ResponseStatus; /** - * Builder to populate <i>audit</i> data. This includes only data known to an application, and not otherwise available - * to the logging framework. As opposed, for example, to local runtime, host address, etc. + * Builder to populate <i>audit</i> data. This includes only data known to an application, and not otherwise available to the logging framework. As + * opposed, for example, to local runtime, host address, etc. * * @author KATYR, evitaliy * @since February 15, 2018 @@ -30,7 +29,6 @@ import lombok.Getter; public class AuditData { // don't inherit from MetricsData because it has a very different meaning - private final long startTime; private final long endTime; private final ResponseStatus statusCode; @@ -47,17 +45,16 @@ public class AuditData { this.clientIpAddress = builder.clientIpAddress; } - @Override - public String toString() { - return "AuditData{startTime=" + startTime + ", endTime=" + endTime + ", statusCode=" + statusCode - + ", responseCode=" + responseCode + ", responseDescription=" + responseDescription - + ", clientIpAddress=" + clientIpAddress + '}'; - } - public static AuditDataBuilder builder() { return new AuditDataBuilder(); } + @Override + public String toString() { + return "AuditData{startTime=" + startTime + ", endTime=" + endTime + ", statusCode=" + statusCode + ", responseCode=" + responseCode + + ", responseDescription=" + responseDescription + ", clientIpAddress=" + clientIpAddress + '}'; + } + /** * Fluent API for building audit data. */ @@ -95,8 +92,8 @@ public class AuditData { } /** - * Indicate whether an invocation was successful. It is up the the application to decide if a particular result - * must be treated as a success or a failure. + * Indicate whether an invocation was successful. It is up the the application to decide if a particular result must be treated as a success + * or a failure. * * @param statusCode invocation status success/failure * @return this builder for fluent API @@ -118,8 +115,8 @@ public class AuditData { } /** - * Response description that explains {@link #responseCode(String)} in a human-friendly way. For a Web API, it - * is likely to be a standard HTTP response phrase. + * Response description that explains {@link #responseCode(String)} in a human-friendly way. For a Web API, it is likely to be a standard HTTP + * response phrase. * * @param responseDescription human-friendly response description * @return this builder for fluent API diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/ContextData.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/ContextData.java index 6eb747f9d9..ba556caac3 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/ContextData.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/ContextData.java @@ -13,15 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.api; import java.util.Objects; /** - * Builder to populate logging <i>context</i> data, i.e. data that should be available to any log writing event - * throughout an application. This includes only data known at some point to the application (e.g. at an API call), - * and not otherwise available to the logging framework (e.g. information about local runtime, machine, etc.). + * Builder to populate logging <i>context</i> data, i.e. data that should be available to any log writing event throughout an application. This + * includes only data known at some point to the application (e.g. at an API call), and not otherwise available to the logging framework (e.g. + * information about local runtime, machine, etc.). * * @author evitaliy * @since Mar 22, 2018 @@ -38,6 +37,10 @@ public class ContextData { this.partnerName = builder.partnerName; } + public static ContextDataBuilder builder() { + return new ContextDataBuilder(); + } + /** * Uniques request ID received from a calling peer, or created. * @@ -67,18 +70,15 @@ public class ContextData { @Override public boolean equals(Object o) { - if (this == o) { return true; } - if (o == null || getClass() != o.getClass()) { return false; } - ContextData that = (ContextData) o; - return Objects.equals(requestId, that.requestId) && Objects.equals(serviceName, that.serviceName) - && Objects.equals(partnerName, that.partnerName); + return Objects.equals(requestId, that.requestId) && Objects.equals(serviceName, that.serviceName) && Objects + .equals(partnerName, that.partnerName); } @Override @@ -88,12 +88,7 @@ public class ContextData { @Override public String toString() { - return "ContextData{responseCode=" + requestId + ", responseDescription=" + serviceName - + ", clientIpAddress=" + partnerName + '}'; - } - - public static ContextDataBuilder builder() { - return new ContextDataBuilder(); + return "ContextData{responseCode=" + requestId + ", responseDescription=" + serviceName + ", clientIpAddress=" + partnerName + '}'; } /** diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/Logger.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/Logger.java index 6fbd25a134..9d670e8dcb 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/Logger.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/Logger.java @@ -4,16 +4,15 @@ * 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. */ - package org.openecomp.sdc.logging.api; /** diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/LoggerFactory.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/LoggerFactory.java index 6ef57761d8..b772f5682c 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/LoggerFactory.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/LoggerFactory.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.api; import java.util.Objects; @@ -22,22 +21,19 @@ import org.openecomp.sdc.logging.spi.LoggerCreationService; /** * <a>Factory to hide a concrete, framework-specific implementation of logger creation.</a> * <p>The service used by this factory must implement {@link LoggerCreationService}. If no - * implementation has been configured or could be instantiated, a <b>no-op logger</b> will be - * used, and <b>no events</b> will be logged. This is done to prevent recursion if attempts are - * being made to log exceptions that resulted from logger initialization. </p> + * implementation has been configured or could be instantiated, a <b>no-op logger</b> will be used, and <b>no events</b> will be logged. This is done + * to prevent recursion if attempts are being made to log exceptions that resulted from logger initialization. </p> * * @author evitaliy - * @since 13/09/2016. - * * @see ServiceBinder * @see LoggerCreationService + * @since 13/09/2016. */ public class LoggerFactory { - // use the no-op service to prevent recursion in case of an attempt to log an exception as a + // result of a logger initialization error - private static final LoggerCreationService SERVICE = ServiceBinder.getCreationServiceBinding().orElseGet( - NoOpLoggerCreationService::new); + private static final LoggerCreationService SERVICE = ServiceBinder.getCreationServiceBinding().orElseGet(NoOpLoggerCreationService::new); private LoggerFactory() { // prevent instantiation @@ -53,6 +49,18 @@ public class LoggerFactory { private static class NoOpLoggerCreationService implements LoggerCreationService { + @Override + public Logger getLogger(String className) { + Objects.requireNonNull(className, "Name cannot be null"); + return NoOpLogger.INSTANCE; + } + + @Override + public Logger getLogger(Class<?> clazz) { + Objects.requireNonNull(clazz, "Class cannot be null"); + return NoOpLogger.INSTANCE; + } + private static class NoOpLogger implements Logger { private static final Logger INSTANCE = new NoOpLogger(); @@ -212,18 +220,5 @@ public class LoggerFactory { // no-op } } - - @Override - public Logger getLogger(String className) { - Objects.requireNonNull(className, "Name cannot be null"); - return NoOpLogger.INSTANCE; - } - - @Override - public Logger getLogger(Class<?> clazz) { - Objects.requireNonNull(clazz, "Class cannot be null"); - return NoOpLogger.INSTANCE; - } } } - diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/LoggingContext.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/LoggingContext.java index 894dd2c00c..29e3f33fa0 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/LoggingContext.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/LoggingContext.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.api; import java.util.Objects; @@ -24,9 +23,8 @@ import org.openecomp.sdc.logging.spi.LoggingContextService; * <p>Factory to hide a concrete, framework-specific implementation of diagnostic context.</p> * * <p>The service used by this factory must implement {@link LoggingContextService}. If no implementation has been - * configured or could be instantiated, a <b>no-op context service</b> will be used, and <b>no context</b> will be - * stored or propagated. No errors will be generated, so that the application can still work (albeit without proper - * logging).</p> + * configured or could be instantiated, a <b>no-op context service</b> will be used, and <b>no context</b> will be stored or propagated. No errors + * will be generated, so that the application can still work (albeit without proper logging).</p> * * @author evitaliy * @see ServiceBinder @@ -35,8 +33,7 @@ import org.openecomp.sdc.logging.spi.LoggingContextService; */ public class LoggingContext { - private static final LoggingContextService SERVICE = - ServiceBinder.getContextServiceBinding().orElseGet(NoOpLoggingContextService::new); + private static final LoggingContextService SERVICE = ServiceBinder.getContextServiceBinding().orElseGet(NoOpLoggingContextService::new); private LoggingContext() { // prevent instantiation diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/MetricsData.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/MetricsData.java index 2fef96d2bb..e85c22cb67 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/MetricsData.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/MetricsData.java @@ -13,15 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.api; -import org.onap.logging.ref.slf4j.ONAPLogConstants.ResponseStatus; import lombok.Getter; +import org.onap.logging.ref.slf4j.ONAPLogConstants.ResponseStatus; /** - * Builder to populate <i>metrics</i> data. This includes only data known to an application, and not otherwise available - * to the logging framework. + * Builder to populate <i>metrics</i> data. This includes only data known to an application, and not otherwise available to the logging framework. * * @author evitaliy * @since 26 Mar 2018 @@ -30,7 +28,6 @@ import lombok.Getter; public class MetricsData { // don't inherit from AuditData because it has a very different meaning - private final long startTime; private final long endTime; private final ResponseStatus statusCode; @@ -51,17 +48,16 @@ public class MetricsData { this.targetVirtualEntity = builder.targetVirtualEntity; } - @Override - public String toString() { - return "AuditData{startTime=" + startTime + ", endTime=" + endTime + ", statusCode=" + statusCode - + ", responseCode=" + responseCode + ", responseDescription=" + responseDescription - + ", clientIpAddress=" + clientIpAddress + '}'; - } - public static MetricsDataBuilder builder() { return new MetricsDataBuilder(); } + @Override + public String toString() { + return "AuditData{startTime=" + startTime + ", endTime=" + endTime + ", statusCode=" + statusCode + ", responseCode=" + responseCode + + ", responseDescription=" + responseDescription + ", clientIpAddress=" + clientIpAddress + '}'; + } + /** * Fluent API for building metrics data. */ @@ -101,8 +97,8 @@ public class MetricsData { } /** - * Indicate whether an invocation was successful. It is up the the application to decide if a particular result - * must be treated as a success or a failure. + * Indicate whether an invocation was successful. It is up the the application to decide if a particular result must be treated as a success + * or a failure. * * @param statusCode invocation status success/failure * @return this builder for fluent API @@ -124,8 +120,8 @@ public class MetricsData { } /** - * Response description that explains {@link #responseCode(String)} in a human-friendly way. For a Web API, it - * is likely to be a standard HTTP response phrase. + * Response description that explains {@link #responseCode(String)} in a human-friendly way. For a Web API, it is likely to be a standard HTTP + * response phrase. * * @param responseDescription human-friendly response description * @return this builder for fluent API diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/ServiceBinder.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/ServiceBinder.java index 6e5b3e3501..65d624aa86 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/ServiceBinder.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/ServiceBinder.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.api; import java.util.Iterator; @@ -35,6 +34,7 @@ import org.openecomp.sdc.logging.spi.LoggingServiceProvider; */ // No advanced logging can be used here because we don't know + // which underlying implementation will be used @SuppressWarnings({"UseOfSystemOutOrSystemErr", "squid:S106", "squid:S1166"}) class ServiceBinder { @@ -46,31 +46,23 @@ class ServiceBinder { } private static LoggingServiceProvider lookupProvider() { - ServiceLoader<LoggingServiceProvider> loader = ServiceLoader.load(LoggingServiceProvider.class); Iterator<LoggingServiceProvider> iterator = loader.iterator(); - if (!iterator.hasNext()) { - System.err.printf("[ERROR] No provider configured for logging services %s. " - + "Default implementation will be used.\n", LoggingServiceProvider.class.getName()); + System.err.printf("[ERROR] No provider configured for logging services %s. " + "Default implementation will be used.\n", + LoggingServiceProvider.class.getName()); return null; } - try { - LoggingServiceProvider provider = iterator.next(); if (!iterator.hasNext()) { return provider; } - Logger logger = provider.getLogger(ServiceBinder.class); if (logger.isWarnEnabled()) { - logger.warn("More than one provider for logging services {} found", - LoggingServiceProvider.class.getName()); + logger.warn("More than one provider for logging services {} found", LoggingServiceProvider.class.getName()); } - return provider; - } catch (Exception e) { // don't fail if the provider cannot be instantiated e.printStackTrace(System.err); @@ -86,4 +78,3 @@ class ServiceBinder { return Optional.ofNullable(PROVIDER); } } - diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/package-info.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/package-info.java index cfe80da244..5faad5a7a3 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/package-info.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/package-info.java @@ -17,9 +17,9 @@ /** * <p>Client-visible API for logging, implemented according to * <a href="https://wiki.onap.org/download/attachments/1015849/ONAP%20application%20logging%20guidelines.pdf?api=v2"> - * ONAP application logging guidelines</a>. The actual implementation is delegated to a service provider bound through - * the <a href="https://docs.oracle.com/javase/tutorial/ext/basics/spi.html">Java SPI</a> mechanism. The provider must - * implement {@link org.openecomp.sdc.logging.spi.LoggingServiceProvider}.</p> + * ONAP application logging guidelines</a>. The actual implementation is delegated to a service provider bound through the <a + * href="https://docs.oracle.com/javase/tutorial/ext/basics/spi.html">Java SPI</a> mechanism. The provider must implement {@link + * org.openecomp.sdc.logging.spi.LoggingServiceProvider}.</p> * <p>The logging API collects the following types of data:</p> * <ol> * <li>Context that must be propagated throughout the application, and available at any point for debug and error @@ -35,4 +35,4 @@ * @author evitaliy * @since 26 Mar 2018 */ -package org.openecomp.sdc.logging.api; +package org.openecomp.sdc.logging.api; diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/AuditTracker.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/AuditTracker.java index 2aeacf1ad5..371aaf68b6 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/AuditTracker.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/AuditTracker.java @@ -13,20 +13,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.servlet; +import static org.onap.logging.ref.slf4j.ONAPLogConstants.ResponseStatus.COMPLETE; + import java.util.Objects; import javax.servlet.http.HttpServletRequest; import org.openecomp.sdc.logging.api.AuditData; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; -import static org.onap.logging.ref.slf4j.ONAPLogConstants.ResponseStatus.COMPLETE; - /** - * Tracks and logs audit information when a request is being processed. An instance of this class cannot be reused, and - * the pre- and post-request methods must be called only once. + * Tracks and logs audit information when a request is being processed. An instance of this class cannot be reused, and the pre- and post-request + * methods must be called only once. * * @author evitaliy * @since 31 Jul 2018 @@ -57,35 +56,27 @@ public class AuditTracker implements Tracker { @Override public synchronized void preRequest(HttpServletRequest request) { - if (this.started > 0) { throw new IllegalStateException("Pre-request has been already called"); } - this.started = System.currentTimeMillis(); this.clientIpAddress = request.getRemoteAddr(); - AuditData auditData = AuditData.builder().startTime(started).endTime(started).statusCode(COMPLETE) - .clientIpAddress(clientIpAddress) - .build(); + AuditData auditData = AuditData.builder().startTime(started).endTime(started).statusCode(COMPLETE).clientIpAddress(clientIpAddress).build(); logger.auditEntry(auditData); } @Override public synchronized void postRequest(RequestProcessingResult result) { - if (this.started == 0) { throw new IllegalStateException("Pre-request must be called first"); } - if (!logger.isAuditEnabled()) { return; } - long end = System.currentTimeMillis(); AuditData auditData = AuditData.builder().startTime(started).endTime(end).statusCode(result.getStatusCode()) - .responseCode(Integer.toString(result.getStatus())) - .responseDescription(result.getStatusPhrase()).clientIpAddress(clientIpAddress) - .build(); + .responseCode(Integer.toString(result.getStatus())).responseDescription(result.getStatusPhrase()).clientIpAddress(clientIpAddress) + .build(); logger.auditExit(auditData); } } diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/CombinedTracker.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/CombinedTracker.java index 5d940aa821..513a8a0361 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/CombinedTracker.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/CombinedTracker.java @@ -13,15 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.servlet; import javax.servlet.http.HttpServletRequest; /** - * Tracker for all the elements of ONAP logging and tracing at an entry point to an application. - * The order of invocations is important, and on {@link #preRequest(HttpServletRequest)} it respects the order of - * trackers passed to the constructor. On {@link #postRequest(RequestProcessingResult)}, the invocation will be in the + * Tracker for all the elements of ONAP logging and tracing at an entry point to an application. The order of invocations is important, and on {@link + * #preRequest(HttpServletRequest)} it respects the order of trackers passed to the constructor. On {@link #postRequest(RequestProcessingResult)}, the + * invocation will be in the * <b>reverse</b> order. * * @author evitaliy @@ -38,7 +37,6 @@ public class CombinedTracker implements Tracker { @Override public void preRequest(HttpServletRequest request) { - for (Tracker t : trackers) { t.preRequest(request); } @@ -46,7 +44,6 @@ public class CombinedTracker implements Tracker { @Override public void postRequest(RequestProcessingResult result) { - for (int i = trackers.length - 1; i > -1; i--) { trackers[i].postRequest(result); } diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/ContextTracker.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/ContextTracker.java index 02745f6287..51ba005521 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/ContextTracker.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/ContextTracker.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.servlet; import java.util.Objects; @@ -34,13 +33,12 @@ public class ContextTracker implements Tracker { private final HttpHeader partnerNameHeaders; private final HttpHeader requestIdHeaders; - private final Supplier<Void> loggingContextClear; private final Consumer<ContextData> loggingContextPut; /** - * Constructs tracker to handle required logging context in Servlet-based applications. Refer to ONAP logging - * guidelines for fields required to be put on logging context. + * Constructs tracker to handle required logging context in Servlet-based applications. Refer to ONAP logging guidelines for fields required to be + * put on logging context. * * @param partnerNameHeaders HTTP headers to check for a partner name, cannot be null * @param requestIdHeaders HTTP headers to check for a request ID, cannot be null @@ -56,36 +54,30 @@ public class ContextTracker implements Tracker { } /** - * Package level constructor used for tests. Clean and Put are passed as functions - * in order to avoid static mock and service loader config - LoggingServiceProvider in LoggingContext + * Package level constructor used for tests. Clean and Put are passed as functions in order to avoid static mock and service loader config - + * LoggingServiceProvider in LoggingContext * * @param partnerNameHeaders * @param requestIdHeaders * @param loggingContextClear * @param loggingContextPut */ - ContextTracker(HttpHeader partnerNameHeaders, - HttpHeader requestIdHeaders, - Supplier<Void> loggingContextClear, - Consumer<ContextData> loggingContextPut) { + ContextTracker(HttpHeader partnerNameHeaders, HttpHeader requestIdHeaders, Supplier<Void> loggingContextClear, + Consumer<ContextData> loggingContextPut) { this.partnerNameHeaders = Objects.requireNonNull(partnerNameHeaders); this.requestIdHeaders = Objects.requireNonNull(requestIdHeaders); this.loggingContextPut = loggingContextPut; - this.loggingContextClear =loggingContextClear; + this.loggingContextClear = loggingContextClear; } @Override public void preRequest(HttpServletRequest request) { - loggingContextClear.get(); - String serviceName = ServiceNameFormatter.format(request); String requestId = requestIdHeaders.getAny(request::getHeader).orElse(UUID.randomUUID().toString()); - ContextData.ContextDataBuilder contextBuilder = - ContextData.builder().serviceName(serviceName).requestId(requestId); + ContextData.ContextDataBuilder contextBuilder = ContextData.builder().serviceName(serviceName).requestId(requestId); String partnerName = partnerNameHeaders.getAny(request::getHeader).orElse("UNKNOWN"); contextBuilder.partnerName(partnerName); - loggingContextPut.accept(contextBuilder.build()); } diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/HttpHeader.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/HttpHeader.java index dd5af859d4..95963b504f 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/HttpHeader.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/HttpHeader.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.servlet; import java.util.ArrayList; @@ -24,9 +23,9 @@ import java.util.Optional; import java.util.function.Function; /** - * Handles any of possible header names to read a value for that header. This is useful for backward compatibility, if - * multiple headers may have the same meaning. For instance, when requests come from multiple service, some using an old - * header and others using a new header to pass the same information. + * Handles any of possible header names to read a value for that header. This is useful for backward compatibility, if multiple headers may have the + * same meaning. For instance, when requests come from multiple service, some using an old header and others using a new header to pass the same + * information. * * @author evitaliy * @since 25 Mar 2018 @@ -35,7 +34,6 @@ public class HttpHeader { private static final String NAMES_CANNOT_BE_NULL = "Names cannot be null"; private static final String AT_LEAST_ONE_NAME_REQUIRED = "At least one name required"; - private final List<String> headerNames; /** @@ -44,11 +42,9 @@ public class HttpHeader { * @param headerNames cannot be null or empty */ public HttpHeader(String... headerNames) { - if (Objects.requireNonNull(headerNames, NAMES_CANNOT_BE_NULL).length < 1) { throw new IllegalArgumentException(AT_LEAST_ONE_NAME_REQUIRED); } - this.headerNames = Arrays.asList(headerNames); } @@ -58,11 +54,9 @@ public class HttpHeader { * @param headerNames cannot be null or empty */ public HttpHeader(List<String> headerNames) { - if (Objects.requireNonNull(headerNames, NAMES_CANNOT_BE_NULL).isEmpty()) { throw new IllegalArgumentException(AT_LEAST_ONE_NAME_REQUIRED); } - this.headerNames = new ArrayList<>(headerNames); } @@ -73,29 +67,23 @@ public class HttpHeader { * @return value or empty if not found */ public Optional<String> getAny(Function<String, String> reader) { - for (String k : headerNames) { - String value = reader.apply(k); if (value != null) { return Optional.of(value); } } - return Optional.empty(); } @Override public boolean equals(Object o) { - if (this == o) { return true; } - if (o == null || getClass() != o.getClass()) { return false; } - HttpHeader that = (HttpHeader) o; return Objects.equals(headerNames, that.headerNames); } diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/RequestProcessingResult.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/RequestProcessingResult.java index ff77ef8a93..bf1d1e5d0f 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/RequestProcessingResult.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/RequestProcessingResult.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.servlet; import org.onap.logging.ref.slf4j.ONAPLogConstants.ResponseStatus; diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/ServiceNameFormatter.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/ServiceNameFormatter.java index fcbd281e88..dd5c0a7153 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/ServiceNameFormatter.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/ServiceNameFormatter.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.servlet; import javax.servlet.http.HttpServletRequest; diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/Tracker.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/Tracker.java index c0337cfb4d..98b1d71969 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/Tracker.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/Tracker.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.servlet; import javax.servlet.http.HttpServletRequest; @@ -34,9 +33,9 @@ public interface Tracker { void preRequest(HttpServletRequest request); /** - * Will be executed after a request has been processed. Results may be treated differently depending on a container - * and application. For instance, JAX-RS applications may take into account exception mappers before generating a - * response; some applications may Swagger annotations to map a response status to a human-friendly message, etc. + * Will be executed after a request has been processed. Results may be treated differently depending on a container and application. For + * instance, JAX-RS applications may take into account exception mappers before generating a response; some applications may Swagger annotations + * to map a response status to a human-friendly message, etc. * * @param result application- and container-specific request results */ diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/jaxrs/LoggingRequestFilter.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/jaxrs/LoggingRequestFilter.java index fb651495ac..71d61b0de2 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/jaxrs/LoggingRequestFilter.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/jaxrs/LoggingRequestFilter.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.servlet.jaxrs; import static org.openecomp.sdc.logging.LoggingConstants.DEFAULT_PARTNER_NAME_HEADER; @@ -35,8 +34,7 @@ import org.openecomp.sdc.logging.servlet.Tracker; /** * <p>Takes care of logging initialization an HTTP request hits the application. This includes populating logging - * context and tracking the request for audit. The filter <b>works in tandem</b> with {@link LoggingResponseFilter} or - * a similar implementation.</p> + * context and tracking the request for audit. The filter <b>works in tandem</b> with {@link LoggingResponseFilter} or a similar implementation.</p> * <p>The filter requires a few HTTP header names to be configured. These HTTP headers are used for propagating logging * and tracing information between ONAP components. Sample configuration for a Spring environment:</p> * <pre> @@ -59,15 +57,11 @@ import org.openecomp.sdc.logging.servlet.Tracker; public class LoggingRequestFilter implements ContainerRequestFilter { static final String LOGGING_TRACKER_KEY = "onap.logging.tracker"; - private static final String MULTI_VALUE_SEPARATOR = ","; private static final Logger LOGGER = LoggerFactory.getLogger(LoggingRequestFilter.class); - private HttpServletRequest httpRequest; - private HttpHeader requestIdHeader = new HttpHeader(DEFAULT_REQUEST_ID_HEADER); private HttpHeader partnerNameHeader = new HttpHeader(DEFAULT_PARTNER_NAME_HEADER); - private ResourceInfo resource; /** @@ -109,9 +103,7 @@ public class LoggingRequestFilter implements ContainerRequestFilter { @Override public void filter(ContainerRequestContext requestContext) { Class<?> resourceClass = resource.getResourceMethod().getDeclaringClass(); - Tracker tracker = new CombinedTracker( - new ContextTracker(partnerNameHeader, requestIdHeader), - new AuditTracker(resourceClass)); + Tracker tracker = new CombinedTracker(new ContextTracker(partnerNameHeader, requestIdHeader), new AuditTracker(resourceClass)); requestContext.setProperty(LOGGING_TRACKER_KEY, tracker); tracker.preRequest(httpRequest); } diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/jaxrs/LoggingResponseFilter.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/jaxrs/LoggingResponseFilter.java index b0ae88ccaa..e5bdd56534 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/jaxrs/LoggingResponseFilter.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/jaxrs/LoggingResponseFilter.java @@ -13,12 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.servlet.jaxrs; import static javax.ws.rs.core.Response.Status.Family.REDIRECTION; import static javax.ws.rs.core.Response.Status.Family.SUCCESSFUL; -import static org.onap.logging.ref.slf4j.ONAPLogConstants.ResponseStatus.*; +import static org.onap.logging.ref.slf4j.ONAPLogConstants.ResponseStatus.COMPLETE; +import static org.onap.logging.ref.slf4j.ONAPLogConstants.ResponseStatus.ERROR; import static org.openecomp.sdc.logging.servlet.jaxrs.LoggingRequestFilter.LOGGING_TRACKER_KEY; import javax.ws.rs.container.ContainerRequestContext; @@ -26,7 +26,6 @@ import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.container.ContainerResponseFilter; import javax.ws.rs.core.Response; import javax.ws.rs.ext.Provider; - import org.onap.logging.ref.slf4j.ONAPLogConstants.ResponseStatus; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; @@ -35,8 +34,7 @@ import org.openecomp.sdc.logging.servlet.Tracker; /** * <p>Takes care of logging when an HTTP request leaves the application. This includes writing to audit and clearing - * logging context. This filter <b>only works properly in tandem</b> with {@link LoggingRequestFilter} or a similar - * implementation.</p> + * logging context. This filter <b>only works properly in tandem</b> with {@link LoggingRequestFilter} or a similar implementation.</p> * <p>Sample configuration for a Spring environment:</p> * <pre> * <jaxrs:providers> @@ -57,14 +55,11 @@ public class LoggingResponseFilter implements ContainerResponseFilter { @Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) { - Tracker tracker = (Tracker) requestContext.getProperty(LOGGING_TRACKER_KEY); - if (tracker == null) { LOGGER.debug("No logging tracker received"); return; } - tracker.postRequest(new ContainerResponseResult(responseContext.getStatusInfo())); } @@ -93,4 +88,3 @@ public class LoggingResponseFilter implements ContainerResponseFilter { } } } - diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/spi/LoggerCreationService.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/spi/LoggerCreationService.java index 54b5be3a27..d30412557a 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/spi/LoggerCreationService.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/spi/LoggerCreationService.java @@ -4,16 +4,15 @@ * 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. */ - package org.openecomp.sdc.logging.spi; import org.openecomp.sdc.logging.api.Logger; diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/spi/LoggingContextService.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/spi/LoggingContextService.java index 37e212ac54..7d08b2559c 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/spi/LoggingContextService.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/spi/LoggingContextService.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.spi; import java.util.concurrent.Callable; @@ -22,16 +21,14 @@ import org.openecomp.sdc.logging.api.ContextData; /** * Should be used to implement a framework-specific mechanism of managing a per-thread diagnostic context (for instance * <a href="http://www.slf4j.org/manual.html#mdc">MDC</a>), and propagating it to child threads if needed. Context - * propagation should be used when creating a child thread directly, or submitting tasks for potentially postponed - * execution via an <a href="http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executor.html">Executor</a> - * (including any of the <a href="http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html"> - * executor services</a> and <a href="http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ForkJoinPool.html"> - * ForkJoinPool</a>). + * propagation should be used when creating a child thread directly, or submitting tasks for potentially postponed execution via an <a + * href="http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executor.html">Executor</a> (including any of the <a + * href="http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html"> executor services</a> and <a + * href="http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ForkJoinPool.html"> ForkJoinPool</a>). * * @author evitaliy * @since 07 Jan 2018 */ - public interface LoggingContextService { /** @@ -50,14 +47,14 @@ public interface LoggingContextService { void clear(); /** - * Copies logging context of current thread onto a {@link Runnable}, so that the context is available when this - * {@link Runnable} runs in another thread. + * Copies logging context of current thread onto a {@link Runnable}, so that the context is available when this {@link Runnable} runs in another + * thread. */ Runnable copyToRunnable(Runnable runnable); /** - * Copies logging context of current thread onto a {@link Callable}, so that the context is available when this - * {@link Callable} runs in another thread + * Copies logging context of current thread onto a {@link Callable}, so that the context is available when this {@link Callable} runs in another + * thread */ <V> Callable<V> copyToCallable(Callable<V> callable); } diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/spi/LoggingServiceProvider.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/spi/LoggingServiceProvider.java index 12e4040feb..4af0baebd2 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/spi/LoggingServiceProvider.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/spi/LoggingServiceProvider.java @@ -13,18 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.spi; /** * <p>From the application code (consumer) perspective, logger creation (factory) and logging context are independent - * services. From the service provider perspective, however, these services are related and must be implemented together - * using the same underlying mechanism. Therefore, the service provider-facing interface combines the two services - * — to eliminate the chance that their implementations don't work well together.</p> + * services. From the service provider perspective, however, these services are related and must be implemented together using the same underlying + * mechanism. Therefore, the service provider-facing interface combines the two services — to eliminate the chance that their implementations + * don't work well together.</p> * * @author EVITALIY * @since 07 Jan 18 */ public interface LoggingServiceProvider extends LoggerCreationService, LoggingContextService { // single provider must implement two separate consumer services -} +} diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/context/HostAddressCache.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/context/HostAddressCache.java index 6e63728a07..b27a0c857e 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/context/HostAddressCache.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/context/HostAddressCache.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.context; import java.net.InetAddress; @@ -25,10 +24,10 @@ import java.util.Optional; import java.util.function.Supplier; /** - * Holds a reference to local host address as returned by Java runtime. A value of host address will be cached for the - * interval specified in the constructor or {@link #DEFAULT_REFRESH_INTERVAL}. The caching helps to avoid many low-level - * calls, but at the same time pick up any IP or FQDN changes. Although the underlying JDK implementation uses caching - * too, the refresh interval for logging may be much longer due to the nature of the use. + * Holds a reference to local host address as returned by Java runtime. A value of host address will be cached for the interval specified in the + * constructor or {@link #DEFAULT_REFRESH_INTERVAL}. The caching helps to avoid many low-level calls, but at the same time pick up any IP or FQDN + * changes. Although the underlying JDK implementation uses caching too, the refresh interval for logging may be much longer due to the nature of the + * use. * * @author evitaliy * @since 26 Mar 2018 @@ -37,12 +36,9 @@ import java.util.function.Supplier; public class HostAddressCache { private static final long DEFAULT_REFRESH_INTERVAL = 60000L; // 1 min - private final long interval; - - private volatile CacheEntry cachedAddress; - private final Supplier<InetAddress> readAddress; + private volatile CacheEntry cachedAddress; public HostAddressCache() { this(DEFAULT_REFRESH_INTERVAL); @@ -69,54 +65,27 @@ public class HostAddressCache { this.cachedAddress = new CacheEntry(System.currentTimeMillis(), this.readAddress.get()); } - /** - * Returns an address (host name and IP address) of the local system. - * - * @return local host address or <code>null</code> if it could not be read for some reason - */ - public synchronized Optional<InetAddress> get() { - - long current = System.currentTimeMillis(); - if (current - cachedAddress.lastUpdated < interval) { - return Optional.ofNullable(cachedAddress.address); - } - - InetAddress address = readAddress.get(); // register the attempt even if null, i.e. failed to get a meaningful address - cachedAddress = new CacheEntry(current, address); - return Optional.ofNullable(address); - } - private static InetAddress read() { - try { return InetAddress.getLocalHost(); } catch (UnknownHostException e) { - System.err.println( - "[WARNING] Failed to get local host address. Using a fallback. If you are on Linux, make sure " - + "/etc/hosts contains the host name of your machine, " - + "e.g. '127.0.0.1 localhost my-host.example.com'."); - + System.err.println("[WARNING] Failed to get local host address. Using a fallback. If you are on Linux, make sure " + + "/etc/hosts contains the host name of your machine, " + "e.g. '127.0.0.1 localhost my-host.example.com'."); e.printStackTrace(); // can't really use logging return getFallbackLocalHost(); } } private static InetAddress getFallbackLocalHost() { - try { - Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces(); - while (networkInterfaces.hasMoreElements()) { - InetAddress address = getAddress(networkInterfaces.nextElement()); if (address != null) { return address; } } - return null; - } catch (SocketException e) { e.printStackTrace(); // can't really use logging return null; @@ -124,26 +93,36 @@ public class HostAddressCache { } private static InetAddress getAddress(NetworkInterface networkInterface) throws SocketException { - if (networkInterface.isLoopback() || networkInterface.isUp()) { return null; } - Enumeration<InetAddress> interfaceAddresses = networkInterface.getInetAddresses(); while (interfaceAddresses.hasMoreElements()) { - InetAddress address = interfaceAddresses.nextElement(); if (isHostAddress(address)) { return address; } } - return null; } private static boolean isHostAddress(InetAddress address) { - return !address.isLoopbackAddress() && !address.isAnyLocalAddress() && !address.isLinkLocalAddress() - && !address.isMulticastAddress(); + return !address.isLoopbackAddress() && !address.isAnyLocalAddress() && !address.isLinkLocalAddress() && !address.isMulticastAddress(); + } + + /** + * Returns an address (host name and IP address) of the local system. + * + * @return local host address or <code>null</code> if it could not be read for some reason + */ + public synchronized Optional<InetAddress> get() { + long current = System.currentTimeMillis(); + if (current - cachedAddress.lastUpdated < interval) { + return Optional.ofNullable(cachedAddress.address); + } + InetAddress address = readAddress.get(); // register the attempt even if null, i.e. failed to get a meaningful address + cachedAddress = new CacheEntry(current, address); + return Optional.ofNullable(address); } private static class CacheEntry { diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/context/InstanceId.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/context/InstanceId.java index 73544e1d9f..354aaa24df 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/context/InstanceId.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/context/InstanceId.java @@ -13,14 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.context; import java.util.UUID; /** - * Holds a unique ID of the logging entity. Is useful to distinguish between different nodes of the same application. If - * it can be assumed, that the node can be re-started, then the unique ID must be retained on the disk. + * Holds a unique ID of the logging entity. Is useful to distinguish between different nodes of the same application. If it can be assumed, that the + * node can be re-started, then the unique ID must be retained on the disk. * * @author evitaliy * @since 04 Mar 2018 @@ -32,7 +31,9 @@ public class InstanceId { static { // for some reason Java Preferences API + // https://docs.oracle.com/javase/8/docs/technotes/guides/preferences/overview.html + // didn't work in a Docker container, so for now just generate an ID every time INSTANCE_ID = UUID.randomUUID().toString(); } diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/logback/EventTypeDiscriminator.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/logback/EventTypeDiscriminator.java index aa4657f83e..15471258b3 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/logback/EventTypeDiscriminator.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/logback/EventTypeDiscriminator.java @@ -4,16 +4,15 @@ * 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. */ - package org.openecomp.sdc.logging.logback; import ch.qos.logback.classic.Level; @@ -23,8 +22,7 @@ import org.openecomp.sdc.logging.slf4j.Markers; import org.slf4j.Marker; /** - * Can be used with {@link ch.qos.logback.classic.sift.SiftingAppender} to route events of different types to - * separate log files. For example, + * Can be used with {@link ch.qos.logback.classic.sift.SiftingAppender} to route events of different types to separate log files. For example, * * <pre> * <configuration> @@ -60,30 +58,25 @@ import org.slf4j.Marker; public class EventTypeDiscriminator extends AbstractDiscriminator<ILoggingEvent> { private static final String KEY = "eventType"; - private static final String AUDIT = "Audit"; private static final String METRICS = "Metrics"; private static final String ERROR = "Error"; private static final String DEBUG = "Debug"; private static final String DEFAULT = DEBUG; - private static final int MIN_ERROR_LEVEL = Level.WARN_INT; private static final int MAX_ERROR_LEVEL = Level.ERROR_INT; private static final int DEFAULT_LEVEL = Level.DEBUG_INT; @Override public String getDiscriminatingValue(ILoggingEvent event) { - Level level = event.getLevel(); final int levelInt = level == null ? DEFAULT_LEVEL : level.toInt(); if ((levelInt > MIN_ERROR_LEVEL - 1) && (levelInt < MAX_ERROR_LEVEL + 1)) { return ERROR; } - if (levelInt == Level.DEBUG_INT) { return DEBUG; } - /* * After DEBUG, ERROR, and WARNING have been filtered out, * only TRACE and INFO are left. TRACE is less than DEBUG @@ -91,22 +84,17 @@ public class EventTypeDiscriminator extends AbstractDiscriminator<ILoggingEvent> * custom routing like AUDIT and METRICS */ if (levelInt == Level.INFO_INT) { - final Marker marker = event.getMarker(); if (marker != null) { - - if (marker.contains(Markers.ENTRY) || marker.contains(Markers.EXIT)){ + if (marker.contains(Markers.ENTRY) || marker.contains(Markers.EXIT)) { return AUDIT; } - if (marker.contains(Markers.METRICS)) { return METRICS; } } - return ERROR; } - return DEFAULT; } diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/AuditField.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/AuditField.java index c08952a84d..26cb095fd5 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/AuditField.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/AuditField.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.slf4j; import org.onap.logging.ref.slf4j.ONAPLogConstants; @@ -25,7 +24,7 @@ import org.onap.logging.ref.slf4j.ONAPLogConstants; * @since 25 Mar 2018 */ enum AuditField implements MDCField { - + // @formatter:off BEGIN_TIMESTAMP(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP), END_TIMESTAMP("EndTimestamp"), ELAPSED_TIME("ElapsedTime"), @@ -34,6 +33,7 @@ enum AuditField implements MDCField { RESPONSE_DESCRIPTION(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION), CLIENT_IP_ADDRESS(ONAPLogConstants.MDCs.CLIENT_IP_ADDRESS), INVOCATION_ID(ONAPLogConstants.MDCs.INVOCATION_ID); + // @formatter:on private final String key; diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/Context.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/Context.java index 25784fefcd..c086d6d47d 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/Context.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/Context.java @@ -13,14 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.slf4j; import java.util.Map; /** - * Does not store a state other than initial context values. Objects of this class may be reused by multiple threads, - * therefore they must be stateless to prevent inadvertent exchange of context values between threads. + * Does not store a state other than initial context values. Objects of this class may be reused by multiple threads, therefore they must be stateless + * to prevent inadvertent exchange of context values between threads. * * @author evitaliy * @since 08 Jan 2018 @@ -34,8 +33,8 @@ final class Context { } /** - * Pushes the initial context onto current thread, and returns the existing context. The result cannot be stored as - * local state (see the class comments), and must be kept in a local variable to work properly. + * Pushes the initial context onto current thread, and returns the existing context. The result cannot be stored as local state (see the class + * comments), and must be kept in a local variable to work properly. * * @return previous context values */ diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/ContextField.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/ContextField.java index 87aa0e3a32..619426b883 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/ContextField.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/ContextField.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.slf4j; import org.onap.logging.ref.slf4j.ONAPLogConstants; @@ -25,13 +24,14 @@ import org.onap.logging.ref.slf4j.ONAPLogConstants; * @since 23 Mar 2018 */ enum ContextField implements MDCField { - + // @formatter:off REQUEST_ID(ONAPLogConstants.MDCs.REQUEST_ID), SERVICE_NAME(ONAPLogConstants.MDCs.SERVICE_NAME), PARTNER_NAME(ONAPLogConstants.MDCs.PARTNER_NAME), INSTANCE_ID(ONAPLogConstants.MDCs.INSTANCE_UUID), SERVER(ONAPLogConstants.MDCs.SERVER_FQDN), SERVER_IP_ADDRESS("ServerIpAddress"); + // @formatter:on private final String key; diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/ContextProvider.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/ContextProvider.java index f9a7144b22..e62ceb6f91 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/ContextProvider.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/ContextProvider.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.slf4j; import java.util.Map; @@ -25,5 +24,6 @@ import java.util.Map; * @since 23 Mar 2018 */ interface ContextProvider { + Map<ContextField, String> values(); } diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/GlobalContextProvider.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/GlobalContextProvider.java index f6e933d57b..109671bf25 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/GlobalContextProvider.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/GlobalContextProvider.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.slf4j; import java.net.InetAddress; @@ -35,16 +34,13 @@ class GlobalContextProvider implements ContextProvider { @Override public Map<ContextField, String> values() { - Map<ContextField, String> values = new EnumMap<>(ContextField.class); values.put(ContextField.INSTANCE_ID, InstanceId.get()); - Optional<InetAddress> hostAddress = HOST_ADDRESS_CACHE.get(); hostAddress.ifPresent(address -> { values.put(ContextField.SERVER, address.getHostName()); values.put(ContextField.SERVER_IP_ADDRESS, address.getHostAddress()); }); - return values; } } diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/MDCCallableWrapper.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/MDCCallableWrapper.java index 84aa256d95..bf10fc2598 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/MDCCallableWrapper.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/MDCCallableWrapper.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.slf4j; import java.util.Map; @@ -28,7 +27,6 @@ import java.util.concurrent.Callable; class MDCCallableWrapper<V> implements Callable<V> { private final Context context = new Context(); - private final Callable<V> task; MDCCallableWrapper(Callable<V> task) { @@ -37,9 +35,7 @@ class MDCCallableWrapper<V> implements Callable<V> { @Override public V call() throws Exception { - Map<ContextField, String> oldContext = context.replace(); - try { return task.call(); } finally { diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/MDCDelegate.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/MDCDelegate.java index 026d3fa99b..23544f844b 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/MDCDelegate.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/MDCDelegate.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.slf4j; import java.util.EnumMap; @@ -21,8 +20,7 @@ import java.util.Map; import org.slf4j.MDC; /** - * Because we don't know which information should be carried over from MDC, and which shouldn't, copy just the keys that - * the logging service uses. + * Because we don't know which information should be carried over from MDC, and which shouldn't, copy just the keys that the logging service uses. * * @author evitaliy * @since 23 Mar 2018 @@ -37,7 +35,6 @@ class MDCDelegate { * Get a copy of logging MDC fields. */ static Map<ContextField, String> copy() { - Map<ContextField, String> copy = new EnumMap<>(ContextField.class); for (ContextField k : ContextField.values()) { String v = MDC.get(k.asKey()); @@ -45,7 +42,6 @@ class MDCDelegate { copy.put(k, v); } } - return copy; } @@ -60,22 +56,18 @@ class MDCDelegate { * Reads selected fields from MDC. */ static Map<ContextField, String> get(ContextField... fields) { - Map<ContextField, String> values = new EnumMap<>(ContextField.class); - for (ContextField key : fields) { values.put(key, MDC.get(key.asKey())); } - return values; } /** - * Entirely replaces the logging MDC context with the content of the argument. Logging keys that are not present in - * the input map will be cleared from MDC. + * Entirely replaces the logging MDC context with the content of the argument. Logging keys that are not present in the input map will be cleared + * from MDC. */ static void replace(Map<ContextField, String> values) { - for (ContextField key : ContextField.values()) { updateKey(key, values.get(key)); } @@ -85,27 +77,23 @@ class MDCDelegate { * Push data by multiple data providers on MDC. */ static void put(ContextProvider... dataProviders) { - clear(); - for (ContextProvider provider : dataProviders) { push(provider.values()); } } /** - * Updates the logging MDC context with the content of the argument. Logging keys that are not present in the input - * map will remain "as is", keys with null values will be cleared from MDC. + * Updates the logging MDC context with the content of the argument. Logging keys that are not present in the input map will remain "as is", keys + * with null values will be cleared from MDC. */ private static void push(Map<ContextField, String> values) { - for (Map.Entry<ContextField, String> entry : values.entrySet()) { updateKey(entry.getKey(), entry.getValue()); } } private static void updateKey(ContextField key, String value) { - if (value != null) { MDC.put(key.asKey(), value); } else { @@ -114,7 +102,6 @@ class MDCDelegate { } static void clear() { - for (ContextField field : ContextField.values()) { MDC.remove(field.asKey()); } diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/MDCField.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/MDCField.java index 1096face85..518f911337 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/MDCField.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/MDCField.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.slf4j; /** @@ -25,5 +24,4 @@ package org.openecomp.sdc.logging.slf4j; interface MDCField { String asKey(); - } diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/MDCRunnableWrapper.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/MDCRunnableWrapper.java index 9d93246181..dba96af7af 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/MDCRunnableWrapper.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/MDCRunnableWrapper.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.slf4j; import java.util.Map; @@ -27,7 +26,6 @@ import java.util.Map; class MDCRunnableWrapper implements Runnable { private final Context context = new Context(); - private final Runnable task; MDCRunnableWrapper(Runnable task) { @@ -36,9 +34,7 @@ class MDCRunnableWrapper implements Runnable { @Override public void run() { - Map<ContextField, String> oldContext = context.replace(); - try { task.run(); } finally { diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/Markers.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/Markers.java index 3d9bbcfa53..2225f60a1a 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/Markers.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/Markers.java @@ -4,16 +4,15 @@ * 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. */ - package org.openecomp.sdc.logging.slf4j; import org.onap.logging.ref.slf4j.ONAPLogConstants; @@ -36,15 +35,13 @@ import org.slf4j.MarkerFactory; * </pre> * * @author EVITALIY - * @since 13/09/2016. - * * @see Marker + * @since 13/09/2016. */ public class Markers { public static final Marker ENTRY = MarkerFactory.getMarker(ONAPLogConstants.Markers.ENTRY.getName()); public static final Marker EXIT = MarkerFactory.getMarker(ONAPLogConstants.Markers.EXIT.getName()); - public static final Marker METRICS = MarkerFactory.getMarker("METRICS"); private Markers() { diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/MetricsField.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/MetricsField.java index c4e8e143af..2845e71ffc 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/MetricsField.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/MetricsField.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.slf4j; import org.onap.logging.ref.slf4j.ONAPLogConstants; @@ -25,7 +24,7 @@ import org.onap.logging.ref.slf4j.ONAPLogConstants; * @since 26 Mar 2018 */ public enum MetricsField implements MDCField { - + // @formatter:off BEGIN_TIMESTAMP(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP), END_TIMESTAMP("EndTimestamp"), ELAPSED_TIME("ElapsedTime"), @@ -35,6 +34,7 @@ public enum MetricsField implements MDCField { CLIENT_IP_ADDRESS(ONAPLogConstants.MDCs.CLIENT_IP_ADDRESS), TARGET_VIRTUAL_ENTITY("TargetVirtualEntity"), TARGET_ENTITY(ONAPLogConstants.MDCs.TARGET_ENTITY); + // @formatter:on private final String key; @@ -45,5 +45,4 @@ public enum MetricsField implements MDCField { public String asKey() { return key; } - } diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/RequestContextProvider.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/RequestContextProvider.java index 70e3dd6479..38f691f9ed 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/RequestContextProvider.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/RequestContextProvider.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.slf4j; import java.util.EnumMap; @@ -39,21 +38,16 @@ class RequestContextProvider implements ContextProvider { } static ContextData to(Map<ContextField, String> values) { - return ContextData.builder() - .requestId(values.get(ContextField.REQUEST_ID)) - .serviceName(values.get(ContextField.SERVICE_NAME)) - .partnerName(values.get(ContextField.PARTNER_NAME)).build(); + return ContextData.builder().requestId(values.get(ContextField.REQUEST_ID)).serviceName(values.get(ContextField.SERVICE_NAME)) + .partnerName(values.get(ContextField.PARTNER_NAME)).build(); } @Override public Map<ContextField, String> values() { - Map<ContextField, String> values = new EnumMap<>(ContextField.class); - putIfNotNull(values, ContextField.REQUEST_ID, data.getRequestId()); putIfNotNull(values, ContextField.SERVICE_NAME, data.getServiceName()); putIfNotNull(values, ContextField.PARTNER_NAME, data.getPartnerName()); - return values; } diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/SLF4JLoggerWrapper.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/SLF4JLoggerWrapper.java index 54026098c1..80ca807f2b 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/SLF4JLoggerWrapper.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/SLF4JLoggerWrapper.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.slf4j; import java.text.SimpleDateFormat; @@ -34,7 +33,6 @@ class SLF4JLoggerWrapper implements Logger { //The specified format presents time in UTC formatted per ISO 8601, as required by ONAP logging guidelines private static final String DATE_TIME_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"; - private final org.slf4j.Logger logger; // May cause http://www.slf4j.org/codes.html#loggerNameMismatch @@ -50,6 +48,16 @@ class SLF4JLoggerWrapper implements Logger { this(LoggerFactory.getLogger(className)); } + private static void unsafePutOnMdc(MDCField field, String value) { + MDC.put(field.asKey(), value); + } + + private static void safePutOnMdc(MDCField field, String value) { + if (value != null) { + unsafePutOnMdc(field, value); + } + } + @Override public String getName() { return logger.getName(); @@ -67,11 +75,9 @@ class SLF4JLoggerWrapper implements Logger { @Override public void metrics(MetricsData data) { - if (data == null) { return; // not going to fail because of null } - try { putMetricsOnMdc(data); logger.info(Markers.METRICS, ""); @@ -81,7 +87,6 @@ class SLF4JLoggerWrapper implements Logger { } private void putMetricsOnMdc(MetricsData metrics) { - SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_TIME_PATTERN); unsafePutOnMdc(MetricsField.BEGIN_TIMESTAMP, dateFormat.format(metrics.getStartTime())); unsafePutOnMdc(MetricsField.END_TIMESTAMP, dateFormat.format(metrics.getEndTime())); @@ -91,7 +96,6 @@ class SLF4JLoggerWrapper implements Logger { safePutOnMdc(MetricsField.CLIENT_IP_ADDRESS, metrics.getClientIpAddress()); safePutOnMdc(MetricsField.TARGET_ENTITY, metrics.getTargetEntity()); safePutOnMdc(MetricsField.TARGET_VIRTUAL_ENTITY, metrics.getTargetVirtualEntity()); - if (metrics.getStatusCode() != null) { unsafePutOnMdc(MetricsField.STATUS_CODE, metrics.getStatusCode().name()); } @@ -103,16 +107,6 @@ class SLF4JLoggerWrapper implements Logger { } } - private static void unsafePutOnMdc(MDCField field, String value) { - MDC.put(field.asKey(), value); - } - - private static void safePutOnMdc(MDCField field, String value) { - if (value != null) { - unsafePutOnMdc(field, value); - } - } - @Override public boolean isAuditEnabled() { return logger.isInfoEnabled(Markers.EXIT); @@ -120,11 +114,9 @@ class SLF4JLoggerWrapper implements Logger { @Override public void auditEntry(AuditData data) { - if (data == null) { return; // not failing if null } - try { putAuditOnMdc(data); logger.info(Markers.ENTRY, ""); @@ -133,14 +125,11 @@ class SLF4JLoggerWrapper implements Logger { } } - @Override public void auditExit(AuditData data) { - if (data == null) { return; // not failing if null } - try { putAuditOnMdc(data); logger.info(Markers.EXIT, ""); @@ -150,7 +139,6 @@ class SLF4JLoggerWrapper implements Logger { } private void putAuditOnMdc(AuditData audit) { - SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_TIME_PATTERN); unsafePutOnMdc(AuditField.BEGIN_TIMESTAMP, dateFormat.format(audit.getStartTime())); unsafePutOnMdc(AuditField.END_TIMESTAMP, dateFormat.format(audit.getEndTime())); @@ -159,7 +147,6 @@ class SLF4JLoggerWrapper implements Logger { safePutOnMdc(AuditField.RESPONSE_DESCRIPTION, audit.getResponseDescription()); safePutOnMdc(AuditField.CLIENT_IP_ADDRESS, audit.getClientIpAddress()); unsafePutOnMdc(AuditField.INVOCATION_ID, UUID.randomUUID().toString()); - if (audit.getStatusCode() != null) { unsafePutOnMdc(AuditField.STATUS_CODE, audit.getStatusCode().name()); } diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/SLF4JLoggingServiceProvider.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/SLF4JLoggingServiceProvider.java index 9d4d507ac5..a74f606bc0 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/SLF4JLoggingServiceProvider.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/SLF4JLoggingServiceProvider.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.slf4j; import java.util.Objects; diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-spring/src/main/java/org/openecomp/sdc/logging/servlet/spring/LoggingInterceptor.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-spring/src/main/java/org/openecomp/sdc/logging/servlet/spring/LoggingInterceptor.java index 393a061987..a4eb93beaa 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-spring/src/main/java/org/openecomp/sdc/logging/servlet/spring/LoggingInterceptor.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-spring/src/main/java/org/openecomp/sdc/logging/servlet/spring/LoggingInterceptor.java @@ -13,17 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.servlet.spring; -import static org.onap.logging.ref.slf4j.ONAPLogConstants.ResponseStatus.*; +import static org.onap.logging.ref.slf4j.ONAPLogConstants.ResponseStatus.COMPLETE; +import static org.onap.logging.ref.slf4j.ONAPLogConstants.ResponseStatus.ERROR; import static org.springframework.http.HttpStatus.Series.REDIRECTION; import static org.springframework.http.HttpStatus.Series.SUCCESSFUL; import java.util.Objects; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - import org.onap.logging.ref.slf4j.ONAPLogConstants.ResponseStatus; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; @@ -42,8 +41,8 @@ import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; * <p><b>IMPORTANT</b>: For this interceptor to work, all exceptions must be properly handled before being returned to a * client. Any unexpected, automatically handled exception bypasses the interceptor and will not be logged.</p> * <p>The interceptor must be either registered in Spring configuration XML as a bean, or programmatically as described - * in <a href="https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-config-interceptors"> - * Spring MVC Config: Interceptors</a>.</p> + * in <a href="https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-config-interceptors"> Spring MVC Config: + * Interceptors</a>.</p> * * @author evitaliy * @since 02 Aug 2018 @@ -52,9 +51,7 @@ import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; public class LoggingInterceptor extends HandlerInterceptorAdapter { static final String LOGGING_TRACKER_KEY = "onap.logging.tracker"; - private static final Logger LOGGER = LoggerFactory.getLogger(LoggingInterceptor.class); - private final HttpHeader partnerNameHeader; private final HttpHeader requestIdHeader; @@ -66,34 +63,26 @@ public class LoggingInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { Class<?> resourceClass = getResourceType(handler); - Tracker tracker = new CombinedTracker( - new ContextTracker(partnerNameHeader, requestIdHeader), - new AuditTracker(resourceClass)); + Tracker tracker = new CombinedTracker(new ContextTracker(partnerNameHeader, requestIdHeader), new AuditTracker(resourceClass)); request.setAttribute(LOGGING_TRACKER_KEY, tracker); tracker.preRequest(request); return true; } @Override - public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, - Exception ex) { - + public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { Tracker tracker = (Tracker) request.getAttribute(LOGGING_TRACKER_KEY); - if (tracker == null) { LOGGER.debug("No logging tracker received"); return; } - tracker.postRequest(new ServletResponseResult(response.getStatus())); } private Class<?> getResourceType(Object handler) { - if (handler instanceof HandlerMethod) { return ((HandlerMethod) handler).getMethod().getDeclaringClass(); } - return LoggingInterceptor.class; } @@ -106,7 +95,6 @@ public class LoggingInterceptor extends HandlerInterceptorAdapter { } private StatusInfo init(int status) { - try { return new StatusInfo(HttpStatus.valueOf(status)); } catch (IllegalArgumentException e) { |