aboutsummaryrefslogtreecommitdiffstats
path: root/common-logging/src
diff options
context:
space:
mode:
Diffstat (limited to 'common-logging/src')
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/OnapLoggingContext.java15
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/OnapLoggingUtils.java59
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/eelf/ErrorCodeMap.java57
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventData.java30
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventTrackInfo.java15
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventTrackInfoHandler.java8
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/eelf/MessageCodes.java17
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/eelf/OnapConfigProperties.java14
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/eelf/PolicyLogger.java379
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/DisplayUtils.java18
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/EelfLogger.java80
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/FlexLogger.java181
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/Logger.java33
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/Logger4J.java514
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/LoggerType.java8
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/PropertyUtil.java22
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/SystemOutLogger.java212
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/nsa/LoggingContextFactory.java9
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/nsa/impl/SharedContext.java7
-rw-r--r--common-logging/src/main/resources/org/onap/policy/common/logging/eelf/Resources.properties19
-rw-r--r--common-logging/src/test/java/org/onap/policy/common/logging/eelf/ErrorCodeMapTest.java7
-rw-r--r--common-logging/src/test/java/org/onap/policy/common/logging/eelf/EventDataTest.java26
-rw-r--r--common-logging/src/test/java/org/onap/policy/common/logging/eelf/EventTrackInfoHandlerTest.java7
-rw-r--r--common-logging/src/test/java/org/onap/policy/common/logging/eelf/EventTrackInfoTest.java22
-rw-r--r--common-logging/src/test/java/org/onap/policy/common/logging/eelf/PolicyLoggerTest.java121
-rw-r--r--common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/EelfLoggerTest.java69
-rw-r--r--common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/FlexLoggerTest.java70
-rw-r--r--common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/Logger4JTest.java350
-rw-r--r--common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/PropertyUtilTest.java31
-rw-r--r--common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/SystemOutLoggerTest.java17
30 files changed, 809 insertions, 1608 deletions
diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/OnapLoggingContext.java b/common-logging/src/main/java/org/onap/policy/common/logging/OnapLoggingContext.java
index 0373abfe..e457f5f3 100644
--- a/common-logging/src/main/java/org/onap/policy/common/logging/OnapLoggingContext.java
+++ b/common-logging/src/main/java/org/onap/policy/common/logging/OnapLoggingContext.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2021 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.
@@ -24,7 +24,6 @@ import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.Instant;
import java.util.Date;
-
import org.onap.policy.common.logging.nsa.LoggingContextFactory;
import org.onap.policy.common.logging.nsa.SharedLoggingContext;
import org.slf4j.MDC;
@@ -144,7 +143,7 @@ public class OnapLoggingContext {
* with key "TransactionElapsedTime".
*/
public void transactionEnded() {
- Instant transactionEndTime = Instant.now();
+ var transactionEndTime = Instant.now();
setTransactionEndTimestamp(transactionEndTime);
setTransactionElapsedTime(transactionEndTime);
}
@@ -164,7 +163,7 @@ public class OnapLoggingContext {
* "MetricElapsedTime".
*/
public void metricEnded() {
- Instant metricEndTime = Instant.now();
+ var metricEndTime = Instant.now();
setMetricEndTimestamp(metricEndTime);
setMetricElapsedTime(metricEndTime);
}
@@ -450,7 +449,7 @@ public class OnapLoggingContext {
* @param transactionStartTime transaction start time
*/
public void setTransactionBeginTimestamp(Instant transactionStartTime) {
- SimpleDateFormat sdf = new SimpleDateFormat(TIME_FORMAT);
+ var sdf = new SimpleDateFormat(TIME_FORMAT);
context.put(TRANSACTION_BEGIN_TIME_STAMP, sdf.format(Date.from(transactionStartTime)));
}
@@ -469,7 +468,7 @@ public class OnapLoggingContext {
* @param transactionEndTime transaction end time
*/
public void setTransactionEndTimestamp(Instant transactionEndTime) {
- SimpleDateFormat sdf = new SimpleDateFormat(TIME_FORMAT);
+ var sdf = new SimpleDateFormat(TIME_FORMAT);
context.put(TRANSACTION_END_TIME_STAMP, sdf.format(Date.from(transactionEndTime)));
}
@@ -511,7 +510,7 @@ public class OnapLoggingContext {
* @param metricStartTime metric start time
*/
public void setMetricBeginTimestamp(Instant metricStartTime) {
- SimpleDateFormat sdf = new SimpleDateFormat(TIME_FORMAT);
+ var sdf = new SimpleDateFormat(TIME_FORMAT);
context.put(METRIC_BEGIN_TIME_STAMP, sdf.format(Date.from(metricStartTime)));
}
@@ -530,7 +529,7 @@ public class OnapLoggingContext {
* @param metricEndTime metric end time
*/
public void setMetricEndTimestamp(Instant metricEndTime) {
- SimpleDateFormat sdf = new SimpleDateFormat(TIME_FORMAT);
+ var sdf = new SimpleDateFormat(TIME_FORMAT);
context.put(METRIC_END_TIME_STAMP, sdf.format(Date.from(metricEndTime)));
}
diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/OnapLoggingUtils.java b/common-logging/src/main/java/org/onap/policy/common/logging/OnapLoggingUtils.java
index 6c0879ea..91133d1a 100644
--- a/common-logging/src/main/java/org/onap/policy/common/logging/OnapLoggingUtils.java
+++ b/common-logging/src/main/java/org/onap/policy/common/logging/OnapLoggingUtils.java
@@ -2,7 +2,8 @@
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2023 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,13 +21,16 @@
package org.onap.policy.common.logging;
-import javax.servlet.http.HttpServletRequest;
+import com.google.re2j.Pattern;
+import jakarta.servlet.http.HttpServletRequest;
+import lombok.AccessLevel;
+import lombok.NoArgsConstructor;
-public class OnapLoggingUtils {
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
+public final class OnapLoggingUtils {
- private OnapLoggingUtils() {
- // Private constructor to prevent subclassing
- }
+ private static final Pattern COMMA_PAT = Pattern.compile(",");
+ private static final Pattern CURLS_PAT = Pattern.compile("[{][}]");
/**
* Get the ONAPLoggingContext for a request.
@@ -36,8 +40,8 @@ public class OnapLoggingUtils {
* @return the ONAPLoggingContext
*/
public static OnapLoggingContext getLoggingContextForRequest(HttpServletRequest request,
- OnapLoggingContext baseContext) {
- OnapLoggingContext requestContext = new OnapLoggingContext(baseContext);
+ OnapLoggingContext baseContext) {
+ var requestContext = new OnapLoggingContext(baseContext);
if (request.getLocalAddr() != null) { // may be null in junit tests
requestContext.setServerIpAddress(request.getLocalAddr());
}
@@ -45,7 +49,7 @@ public class OnapLoggingUtils {
// otherwise from remote address in the request
String forwarded = request.getHeader("X-Forwarded-For");
if (forwarded != null && forwarded.trim().length() > 0) {
- forwarded = forwarded.trim().split(",")[0];
+ forwarded = COMMA_PAT.split(forwarded.trim())[0];
requestContext.setClientIpAddress(forwarded);
} else if (request.getRemoteAddr() != null) { // may be null in junit tests
requestContext.setClientIpAddress(request.getRemoteAddr());
@@ -60,4 +64,41 @@ public class OnapLoggingUtils {
return requestContext;
}
+ /**
+ * Create message text replace {} place holder with data
+ * if last argument is throwable/exception, pass it as argument to logger.
+ * @param format message format can contains text and {}
+ * @param arguments output arguments
+ * @return the formatted message as a String
+ */
+ public static String formatMessage(String format, Object...arguments) {
+ if (arguments.length <= 0 || arguments[0] == null) {
+ return format;
+ }
+ int index;
+ var builder = new StringBuilder();
+ String[] token = CURLS_PAT.split(format);
+ for (index = 0; index < arguments.length; index++) {
+ if (index < token.length) {
+ builder.append(token[index]);
+ builder.append(arguments[index]);
+ } else {
+ break;
+ }
+ }
+ for (int index2 = index; index2 < token.length; index2++) {
+ builder.append(token[index2]);
+ }
+
+ return builder.toString();
+ }
+
+ /**
+ * Check object is throwable.
+ * @param obj to verify
+ * @return true if object is throwable or false otherwise
+ */
+ public static boolean isThrowable(Object obj) {
+ return (obj instanceof Throwable);
+ }
}
diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/ErrorCodeMap.java b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/ErrorCodeMap.java
index fab0415b..0eaa06b0 100644
--- a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/ErrorCodeMap.java
+++ b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/ErrorCodeMap.java
@@ -2,7 +2,8 @@
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2018, 2020-2021 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,51 +22,63 @@
package org.onap.policy.common.logging.eelf;
import java.util.EnumMap;
+import lombok.AccessLevel;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
/**
* ErrorCodeMap contains a HashMap of ErrorCodeInfo (error code and error description).
+ * Standard error code:
+ * 100 – permission errors
+ * 200 – availability errors
+ * 300 – data errors
+ * 400 – schema errors
+ * 500 – business process errors
+ * 900 – unknown errors
*/
-public class ErrorCodeMap {
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
+public final class ErrorCodeMap {
private static final EnumMap<MessageCodes, ErrorCodeInfo> hm = new EnumMap<>(MessageCodes.class);
private static final String CHECK_ERROR_MESSAGE = " Please check the error message for detail information";
- private static final String ERROR_PERMISSIONS = "POLICY-100E";
+ private static final String ERROR_PERMISSIONS = "100";
private static final String ERROR_PERMISSIONS_DESCRIPTION = "This is a Permissions Error." + CHECK_ERROR_MESSAGE;
- private static final String ERROR_SCHEMA_INVALID = "POLICY-400E";
+ private static final String ERROR_SCHEMA_INVALID = "400";
private static final String ERROR_SCHEMA_INVALID_DESCRIPTION = "This is an Invalid Schema Error."
+ CHECK_ERROR_MESSAGE;
- private static final String UPDATE_ERROR = "POLICY-502E";
+
+ private static final String UPDATE_ERROR = "300";
private static final String UPDATE_ERROR_DESCRIPTION = "This is an updating error." + CHECK_ERROR_MESSAGE;
- private static final String EXCEPTION_ERROR_CODE = "POLICY-503E";
+ private static final String EXCEPTION_ERROR_CODE = "500";
private static final String EXCEPTION_ERROR_DESCRIPTION = "This is an exception error message during the process."
+ CHECK_ERROR_MESSAGE;
- private static final String MISS_PROPERTY_ERROR = "POLICY-504E";
+ private static final String MISS_PROPERTY_ERROR = "300";
private static final String MISS_PROPERTY_ERROR_DESCRIPTION = "This is an error of missing properties."
+ CHECK_ERROR_MESSAGE;
- private static final String GENERAL_ERROR_CODE = "POLICY-515E";
+ private static final String GENERAL_ERROR_CODE = "500";
private static final String GENERAL_ERROR_DESCRIPTION = "This is a general error message during the process."
+ CHECK_ERROR_MESSAGE;
- private static final String ERROR_SYSTEM_ERROR = "POLICY-516E";
+ private static final String ERROR_SYSTEM_ERROR = "200";
private static final String ERROR_SYSTEM_ERROR_DESCRIPTION = "This is a System Error." + CHECK_ERROR_MESSAGE;
- private static final String ERROR_DATA_ISSUE = "POLICY-517E";
+ private static final String ERROR_DATA_ISSUE = "300";
private static final String ERROR_DATA_ISSUE_DESCRIPTION = "This is a Data Issue Error." + CHECK_ERROR_MESSAGE;
- private static final String ERROR_PROCESS_FLOW = "POLICY-518E";
+ private static final String ERROR_PROCESS_FLOW = "500";
private static final String ERROR_PROCESS_FLOW_DESCRIPTION = "This is a Process Flow Error." + CHECK_ERROR_MESSAGE;
- private static final String ERROR_UNKNOWN = "POLICY-519E";
+ private static final String ERROR_UNKNOWN = "900";
private static final String ERROR_UNKNOWN_DESCRIPTION = "This is an Unknown Error." + CHECK_ERROR_MESSAGE;
- private static final String ERROR_AUDIT = "POLICY-520E";
+ private static final String ERROR_AUDIT = "300";
private static final String ERROR_AUDIT_DESCRIPTION = "This is an audit Error." + CHECK_ERROR_MESSAGE;
static {
@@ -75,7 +88,6 @@ public class ErrorCodeMap {
new ErrorCodeInfo(MISS_PROPERTY_ERROR, MISS_PROPERTY_ERROR_DESCRIPTION));
hm.put(MessageCodes.UPDATE_ERROR, new ErrorCodeInfo(UPDATE_ERROR, UPDATE_ERROR_DESCRIPTION));
hm.put(MessageCodes.ERROR_SYSTEM_ERROR, new ErrorCodeInfo(ERROR_SYSTEM_ERROR, ERROR_SYSTEM_ERROR_DESCRIPTION));
- hm.put(MessageCodes.ERROR_DATA_ISSUE, new ErrorCodeInfo(ERROR_DATA_ISSUE, ERROR_DATA_ISSUE_DESCRIPTION));
hm.put(MessageCodes.ERROR_PERMISSIONS, new ErrorCodeInfo(ERROR_PERMISSIONS, ERROR_PERMISSIONS_DESCRIPTION));
hm.put(MessageCodes.ERROR_DATA_ISSUE, new ErrorCodeInfo(ERROR_DATA_ISSUE, ERROR_DATA_ISSUE_DESCRIPTION));
hm.put(MessageCodes.ERROR_PROCESS_FLOW, new ErrorCodeInfo(ERROR_PROCESS_FLOW, ERROR_PROCESS_FLOW_DESCRIPTION));
@@ -85,32 +97,21 @@ public class ErrorCodeMap {
hm.put(MessageCodes.ERROR_AUDIT, new ErrorCodeInfo(ERROR_AUDIT, ERROR_AUDIT_DESCRIPTION));
}
- private ErrorCodeMap() {
- // Private constructor to prevent subclassing
- }
-
public static ErrorCodeInfo getErrorCodeInfo(MessageCodes messageCode) {
return hm.get(messageCode);
}
+ @Getter
static class ErrorCodeInfo {
- private String errorCode;
- private String errorDesc;
+ private final String errorCode;
+ private final String errorDesc;
public ErrorCodeInfo(String errorCode, String errorDesc) {
this.errorCode = errorCode;
this.errorDesc = errorDesc;
}
- public String getErrorCode() {
- return errorCode;
- }
-
- public String getErrorDesc() {
- return errorDesc;
- }
-
}
}
diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventData.java b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventData.java
index 23be38ba..87a96a19 100644
--- a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventData.java
+++ b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventData.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019, 2021 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.
@@ -21,7 +21,9 @@
package org.onap.policy.common.logging.eelf;
import java.time.Instant;
+import lombok.AllArgsConstructor;
import lombok.Getter;
+import lombok.NoArgsConstructor;
import lombok.Setter;
/**
@@ -29,32 +31,14 @@ import lombok.Setter;
*/
@Getter
@Setter
+@NoArgsConstructor
+@AllArgsConstructor
public class EventData {
private String requestId = null;
private Instant startTime = null;
private Instant endTime = null;
- // Default constructor takes no arguments.
- // Is empty because instance variables are assigned
- // their default values upon declaration.
- public EventData() {
- // See above comments for the reason this constructor is empty
- }
-
- /**
- * Create an instance.
- *
- * @param requestId the request ID
- * @param startTime the start time
- * @param endTime the end time
- */
- public EventData(String requestId, Instant startTime, Instant endTime) {
- this.requestId = requestId;
- this.startTime = startTime;
- this.endTime = endTime;
- }
-
@Override
public String toString() {
return requestId + " Starting Time : " + this.startTime + " Ending Time : " + this.endTime;
@@ -62,8 +46,8 @@ public class EventData {
@Override
public int hashCode() {
- final int prime = 31;
- int result = 1;
+ final var prime = 31;
+ var result = 1;
result = prime * result + ((requestId == null) ? 0 : requestId.hashCode());
return result;
}
diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventTrackInfo.java b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventTrackInfo.java
index 71476c6a..f6f38d0d 100644
--- a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventTrackInfo.java
+++ b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventTrackInfo.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019, 2021 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.
@@ -22,12 +22,14 @@ package org.onap.policy.common.logging.eelf;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
+import lombok.Getter;
/**
* EventTrackInfo contains a ConcurrentHashMap of EventData.
*/
public class EventTrackInfo {
+ @Getter
private final ConcurrentMap<String, EventData> eventInfo;
/**
@@ -66,9 +68,7 @@ public class EventTrackInfo {
return;
}
// in case override the start time, check the original event was already stored or not
- if (!eventInfo.containsKey(id)) {
- eventInfo.put(id, event);
- }
+ eventInfo.putIfAbsent(id, event);
}
}
@@ -82,11 +82,4 @@ public class EventTrackInfo {
eventInfo.remove(eventId);
}
}
-
- /**
- * Returns a ConcurrentHashMap of EventData.
- */
- public ConcurrentMap<String, EventData> getEventInfo() {
- return eventInfo;
- }
}
diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventTrackInfoHandler.java b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventTrackInfoHandler.java
index 4b5c57a8..f5203683 100644
--- a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventTrackInfoHandler.java
+++ b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventTrackInfoHandler.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2021 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.
@@ -23,8 +23,8 @@ package org.onap.policy.common.logging.eelf;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
+import java.util.Map;
import java.util.TimerTask;
-import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
@@ -49,7 +49,7 @@ public class EventTrackInfoHandler extends TimerTask {
*/
private void cleanUp() {
- EventTrackInfo eventTrackInfo = PolicyLogger.getEventTracker();
+ var eventTrackInfo = PolicyLogger.getEventTracker();
if (eventTrackInfo == null) {
return;
}
@@ -63,7 +63,7 @@ public class EventTrackInfoHandler extends TimerTask {
ArrayList<String> expiredEvents = null;
- for (ConcurrentHashMap.Entry<String, EventData> entry : eventInfo.entrySet()) {
+ for (Map.Entry<String, EventData> entry : eventInfo.entrySet()) {
EventData event = entry.getValue();
startTime = event.getStartTime();
ns = Duration.between(startTime, Instant.now()).getSeconds();
diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/MessageCodes.java b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/MessageCodes.java
index ab5712ff..0535b9d7 100644
--- a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/MessageCodes.java
+++ b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/MessageCodes.java
@@ -3,13 +3,14 @@
* ONAP-Logging
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2024 Nordix Foundation.
* ================================================================================
* 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.
@@ -20,13 +21,13 @@
package org.onap.policy.common.logging.eelf;
-import com.att.eelf.i18n.EELFResolvableErrorEnum;
+import com.att.eelf.i18n.EELFResolvableResourceEnum;
import com.att.eelf.i18n.EELFResourceManager;
/**
* MessageCodes contains all the messagge codes for EELF logging messages.
*/
-public enum MessageCodes implements EELFResolvableErrorEnum {
+public enum MessageCodes implements EELFResolvableResourceEnum {
// Below is a list of Error Messages taken from com.att.research.xacml.api XACMLErrorConstants
// found under:
// policy-engine\XACML\src\main\java\com\att\research\xacml\api\XACMLErrorConstants.java
@@ -73,12 +74,6 @@ public enum MessageCodes implements EELFResolvableErrorEnum {
RULE_METRICS_INFO,
- UEB_AUDIT_EXEC_INFO,
-
- UEB_AUDIT_BEGIN_INFO,
-
- UEB_AUDIT_END_INFO,
-
UPDATE_ERROR,
GENERAL_ERROR,
@@ -149,7 +144,7 @@ public enum MessageCodes implements EELFResolvableErrorEnum {
MESSAGE_ERROR_SAMPLE;
- /**
+ /*
* Static initializer to ensure the resource bundles for this class are loaded... Here this
* application loads messages from three bundles.
*/
diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/OnapConfigProperties.java b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/OnapConfigProperties.java
index 8d2031db..cfb14643 100644
--- a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/OnapConfigProperties.java
+++ b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/OnapConfigProperties.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2018, 2020-2021 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.
@@ -20,8 +20,11 @@
package org.onap.policy.common.logging.eelf;
+import lombok.AccessLevel;
+import lombok.NoArgsConstructor;
-public class OnapConfigProperties {
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
+public final class OnapConfigProperties {
/**
* The Date-time of the start of a transaction.
@@ -58,7 +61,7 @@ public class OnapConfigProperties {
public static final String RESPONSE_CODE = "ResponseCode";
/**
- * Human readable description of the application specific response code.
+ * Human-readable description of the application specific response code.
*/
public static final String RESPONSE_DESCRIPTION = "ResponseDescription";
@@ -80,8 +83,5 @@ public class OnapConfigProperties {
public static final String SERVER_NAME = "ServerName";
-
- private OnapConfigProperties() {
- // do nothing
- }
+ public static final String INVOCATION_ID = "InvocationID";
}
diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/PolicyLogger.java b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/PolicyLogger.java
index f1b25d71..662ca764 100644
--- a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/PolicyLogger.java
+++ b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/PolicyLogger.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2021 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.
@@ -34,6 +34,7 @@ import static org.onap.policy.common.logging.eelf.OnapConfigProperties.END_TIME_
import static org.onap.policy.common.logging.eelf.OnapConfigProperties.ERROR_CATEGORY;
import static org.onap.policy.common.logging.eelf.OnapConfigProperties.ERROR_CODE;
import static org.onap.policy.common.logging.eelf.OnapConfigProperties.ERROR_DESCRIPTION;
+import static org.onap.policy.common.logging.eelf.OnapConfigProperties.INVOCATION_ID;
import static org.onap.policy.common.logging.eelf.OnapConfigProperties.PARTNER_NAME;
import static org.onap.policy.common.logging.eelf.OnapConfigProperties.RESPONSE_CODE;
import static org.onap.policy.common.logging.eelf.OnapConfigProperties.RESPONSE_DESCRIPTION;
@@ -57,26 +58,31 @@ import java.util.Date;
import java.util.Iterator;
import java.util.Properties;
import java.util.Timer;
-import java.util.TimerTask;
import java.util.UUID;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Consumer;
+import lombok.AccessLevel;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
+import org.onap.policy.common.logging.OnapLoggingUtils;
import org.onap.policy.common.logging.flexlogger.LoggerType;
import org.slf4j.MDC;
/**
* PolicyLogger contains all the static methods for EELF logging.
*/
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class PolicyLogger {
- private static EELFLogger errorLogger = EELFManager.getInstance().getErrorLogger();
+ private static EELFLogger errorLogger = EELFManager.getErrorLogger();
- private static EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
+ private static EELFLogger metricsLogger = EELFManager.getMetricsLogger();
- private static EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger();
+ private static EELFLogger auditLogger = EELFManager.getAuditLogger();
- private static EELFLogger debugLogger = EELFManager.getInstance().getDebugLogger();
+ private static EELFLogger debugLogger = EELFManager.getDebugLogger();
private static final String POLICY_LOGGER = "PolicyLogger";
@@ -86,7 +92,6 @@ public class PolicyLogger {
private static String hostAddress = null;
private static String component = null;
- private static TimerTask ttrcker = null;
private static boolean isEventTrackerRunning = false;
private static Timer timer = null;
@@ -110,7 +115,9 @@ public class PolicyLogger {
// size drops to this point, stop the Timer
private static int stopCheckPoint = 2500;
- private static boolean isOverrideLogbackLevel = false;
+ @Getter
+ @Setter
+ private static boolean overrideLogbackLevel = false;
private static Level debugLevel = Level.INFO;
private static Level auditLevel = Level.INFO;
@@ -133,10 +140,6 @@ public class PolicyLogger {
}
}
- private PolicyLogger() {
-
- }
-
public static synchronized Level getDebugLevel() {
return debugLevel;
}
@@ -150,7 +153,7 @@ public class PolicyLogger {
*/
public static synchronized void setDebugLevel(String newDebugLevel) {
- if (isOverrideLogbackLevel) {
+ if (overrideLogbackLevel) {
PolicyLogger.debugLevel = Level.valueOf(newDebugLevel);
debugLogger.setLevel(debugLevel);
}
@@ -170,7 +173,7 @@ public class PolicyLogger {
*/
public static synchronized void setAuditLevel(String newAuditLevel) {
- if (isOverrideLogbackLevel) {
+ if (overrideLogbackLevel) {
if ("OFF".equalsIgnoreCase(newAuditLevel)) {
PolicyLogger.auditLevel = Level.OFF;
auditLogger.setLevel(auditLevel);
@@ -195,7 +198,7 @@ public class PolicyLogger {
*/
public static synchronized void setMetricsLevel(String newMetricsLevel) {
- if (isOverrideLogbackLevel) {
+ if (overrideLogbackLevel) {
if ("OFF".equalsIgnoreCase(newMetricsLevel)) {
PolicyLogger.metricsLevel = Level.OFF;
metricsLogger.setLevel(metricsLevel);
@@ -221,7 +224,7 @@ public class PolicyLogger {
*/
public static synchronized void setErrorLevel(String newErrorLevel) {
- if (isOverrideLogbackLevel) {
+ if (overrideLogbackLevel) {
if ("OFF".equalsIgnoreCase(newErrorLevel)) {
PolicyLogger.errorLevel = Level.OFF;
errorLogger.setLevel(errorLevel);
@@ -301,8 +304,8 @@ public class PolicyLogger {
setMdcHostInfo();
- Instant startTime = Instant.now();
- Instant endTime = Instant.now();
+ var startTime = Instant.now();
+ var endTime = Instant.now();
seTimeStamps(startTime, endTime);
@@ -331,12 +334,11 @@ public class PolicyLogger {
* Set Timestamps for start, end and duration of logging a transaction.
*/
private static void seTimeStamps() {
-
MDC.put(MDC_INSTANCE_UUID, "");
MDC.put(MDC_ALERT_SEVERITY, "");
- Instant startTime = Instant.now();
- Instant endTime = Instant.now();
+ var startTime = Instant.now();
+ var endTime = Instant.now();
seTimeStamps(startTime, endTime);
@@ -349,7 +351,7 @@ public class PolicyLogger {
}
private static void seTimeStamps(Instant startTime, Instant endTime) {
- SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
+ var sdf = new SimpleDateFormat(DATE_FORMAT);
String formatedTime = sdf.format(Date.from(startTime));
MDC.put(BEGIN_TIME_STAMP, formatedTime);
@@ -433,18 +435,6 @@ public class PolicyLogger {
}
/**
- * Records only one String message with its class name.
- *
- * @param className the class name
- * @param arg0 the message
- */
- public static void info(String className, String arg0) {
- MDC.put(classNameProp, className);
- debugLogger.info(MessageCodes.GENERAL_INFO, arg0);
- }
-
-
- /**
* Records only one String message.
*
* @param arg0 the message
@@ -483,14 +473,29 @@ public class PolicyLogger {
}
/**
- * Records only one String message with its class name.
+ * Records a message with passed in message text and variable number of arguments.
*
- * @param arg0 log message
- * @param className class name
+ * @param message class name if one argument, otherwise message text
+ * @param arguments variable number of arguments
*/
- public static void warn(String className, String arg0) {
- MDC.put(classNameProp, className);
- debugLogger.warn(MessageCodes.GENERAL_INFO, arg0);
+ public static void info(String message, Object... arguments) {
+ if (!debugLogger.isInfoEnabled()) {
+ return;
+ }
+ if (arguments.length == 1 && !OnapLoggingUtils.isThrowable(arguments[0])) {
+ MDC.put(classNameProp, message);
+ debugLogger.info(MessageCodes.GENERAL_INFO,
+ arguments[0] == null ? "" : arguments[0].toString());
+ return;
+ }
+ if (arguments.length == 1 && OnapLoggingUtils.isThrowable(arguments[0])) {
+ String arguments2 = getNormalizedStackTrace((Throwable) arguments[0], "");
+ debugLogger.info(MessageCodes.GENERAL_INFO, message + arguments2);
+ return;
+ }
+
+ MDC.put(classNameProp, "");
+ debugLogger.info(message, arguments);
}
/**
@@ -553,19 +558,28 @@ public class PolicyLogger {
}
/**
- * Records only one String message with its class name.
+ * Records a message with passed in message text and variable number of arguments.
*
- * @param className class name
- * @param arg0 log message
+ * @param message class name if one argument, otherwise message text
+ * @param arguments variable number of arguments
*/
- public static void error(String className, String arg0) {
- MDC.put(classNameProp, className);
- if (ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR) != null) {
- MDC.put(ERROR_CODE, ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR).getErrorCode());
- MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR).getErrorDesc());
-
+ public static void warn(String message, Object... arguments) {
+ if (!debugLogger.isWarnEnabled()) {
+ return;
}
- errorLogger.error(MessageCodes.GENERAL_ERROR, arg0);
+ if (arguments.length == 1 && !OnapLoggingUtils.isThrowable(arguments[0])) {
+ MDC.put(classNameProp, message);
+ debugLogger.warn(MessageCodes.GENERAL_INFO,
+ arguments[0] == null ? "" : arguments[0].toString());
+ return;
+ }
+ if (arguments.length == 1 && OnapLoggingUtils.isThrowable(arguments[0])) {
+ String arguments2 = getNormalizedStackTrace((Throwable) arguments[0], "");
+ debugLogger.warn(MessageCodes.GENERAL_INFO, message + arguments2);
+ return;
+ }
+ MDC.put(classNameProp, "");
+ debugLogger.warn(message, arguments);
}
/**
@@ -575,13 +589,7 @@ public class PolicyLogger {
*/
public static void error(String arg0) {
MDC.put(classNameProp, "");
- MDC.put(ERROR_CATEGORY, ERROR_CATEGORY_VALUE);
-
- if (ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR) != null) {
- MDC.put(ERROR_CODE, ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR).getErrorCode());
- MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR).getErrorDesc());
-
- }
+ setErrorCode(MessageCodes.GENERAL_ERROR);
errorLogger.error(MessageCodes.GENERAL_ERROR, arg0);
}
@@ -592,13 +600,7 @@ public class PolicyLogger {
*/
public static void error(Object arg0) {
MDC.put(classNameProp, "");
- MDC.put(ERROR_CATEGORY, ERROR_CATEGORY_VALUE);
-
- if (ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR) != null) {
- MDC.put(ERROR_CODE, ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR).getErrorCode());
- MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR).getErrorDesc());
-
- }
+ setErrorCode(MessageCodes.GENERAL_ERROR);
errorLogger.error(MessageCodes.GENERAL_ERROR, "" + arg0);
}
@@ -611,13 +613,7 @@ public class PolicyLogger {
*/
public static void error(MessageCodes msg, Throwable arg0, String... arguments) {
MDC.put(classNameProp, "");
- MDC.put(ERROR_CATEGORY, ERROR_CATEGORY_VALUE);
-
- if (ErrorCodeMap.getErrorCodeInfo(msg) != null) {
- MDC.put(ERROR_CODE, ErrorCodeMap.getErrorCodeInfo(msg).getErrorCode());
- MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.getErrorCodeInfo(msg).getErrorDesc());
-
- }
+ setErrorCode(msg);
String arguments2 = getNormalizedStackTrace(arg0, arguments);
errorLogger.error(msg, arguments2);
}
@@ -633,13 +629,7 @@ public class PolicyLogger {
*/
public static void error(MessageCodes msg, String className, Throwable arg0, String... arguments) {
MDC.put(classNameProp, className);
- MDC.put(ERROR_CATEGORY, ERROR_CATEGORY_VALUE);
-
- if (ErrorCodeMap.getErrorCodeInfo(msg) != null) {
- MDC.put(ERROR_CODE, ErrorCodeMap.getErrorCodeInfo(msg).getErrorCode());
- MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.getErrorCodeInfo(msg).getErrorDesc());
-
- }
+ setErrorCode(msg);
String arguments2 = getNormalizedStackTrace(arg0, arguments);
errorLogger.error(msg, arguments2);
}
@@ -652,14 +642,35 @@ public class PolicyLogger {
*/
public static void error(MessageCodes msg, String... arguments) {
MDC.put(classNameProp, "");
- MDC.put(ERROR_CATEGORY, ERROR_CATEGORY_VALUE);
-
- if (ErrorCodeMap.getErrorCodeInfo(msg) != null) {
- MDC.put(ERROR_CODE, ErrorCodeMap.getErrorCodeInfo(msg).getErrorCode());
- MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.getErrorCodeInfo(msg).getErrorDesc());
+ setErrorCode(msg);
+ errorLogger.error(msg, arguments);
+ }
+ /**
+ * Records a message with passed in message text and variable number of arguments.
+ *
+ * @param message class name if one argument, otherwise message text
+ * @param arguments variable number of arguments
+ */
+ public static void error(String message, Object... arguments) {
+ if (!errorLogger.isErrorEnabled()) {
+ return;
}
- errorLogger.error(msg, arguments);
+ if (arguments.length == 1 && !OnapLoggingUtils.isThrowable(arguments[0])) {
+ MDC.put(classNameProp, message);
+ setErrorCode(MessageCodes.GENERAL_ERROR);
+ errorLogger.error(MessageCodes.GENERAL_ERROR,
+ arguments[0] == null ? "" : arguments[0].toString());
+ return;
+ }
+ if (arguments.length == 1 && OnapLoggingUtils.isThrowable(arguments[0])) {
+ String arguments2 = getNormalizedStackTrace((Throwable) arguments[0], "");
+ errorLogger.error(MessageCodes.GENERAL_ERROR, message + arguments2);
+ return;
+ }
+ MDC.put(classNameProp, "");
+ setErrorCode(MessageCodes.GENERAL_ERROR);
+ errorLogger.error(message, arguments);
}
/**
@@ -674,17 +685,6 @@ public class PolicyLogger {
}
/**
- * Records only one String message with its class name.
- *
- * @param className the class name
- * @param arg0 the message
- */
- public static void debug(String className, String arg0) {
- MDC.put(classNameProp, className);
- debugLogger.debug(MessageCodes.GENERAL_INFO, arg0);
- }
-
- /**
* Records only one String message.
*
* @param arg0 the message
@@ -702,7 +702,7 @@ public class PolicyLogger {
public static void debug(Object arg0) {
MDC.put(classNameProp, "");
- debugLogger.debug("" + arg0);
+ debugLogger.debug("{}", arg0);
}
/**
@@ -734,15 +734,28 @@ public class PolicyLogger {
}
/**
- * Records only one String message with its class name.
+ * Records a message with passed in message text and variable number of arguments.
*
- * @param className the class name
- * @param arg0 the message
+ * @param message class name if one argument, otherwise message text
+ * @param arguments variable number of arguments
*/
- public static void audit(String className, Object arg0) {
- MDC.put(STATUS_CODE, COMPLETE_STATUS);
- MDC.put(classNameProp, className);
- auditLogger.info("" + arg0);
+ public static void debug(String message, Object... arguments) {
+ if (!debugLogger.isDebugEnabled()) {
+ return;
+ }
+ if (arguments.length == 1 && !OnapLoggingUtils.isThrowable(arguments[0])) {
+ MDC.put(classNameProp, message);
+ debugLogger.debug(MessageCodes.GENERAL_INFO,
+ arguments[0] == null ? "" : arguments[0].toString());
+ return;
+ }
+ if (arguments.length == 1 && OnapLoggingUtils.isThrowable(arguments[0])) {
+ String arguments2 = getNormalizedStackTrace((Throwable) arguments[0], "");
+ debugLogger.debug(MessageCodes.GENERAL_INFO, message + arguments2);
+ return;
+ }
+ MDC.put(classNameProp, "");
+ debugLogger.debug(message, arguments);
}
/**
@@ -751,9 +764,34 @@ public class PolicyLogger {
* @param arg0 the message
*/
public static void audit(Object arg0) {
+ MDC.put(INVOCATION_ID, MDC.get(MDC_KEY_REQUEST_ID));
MDC.put(STATUS_CODE, COMPLETE_STATUS);
+ MDC.put(RESPONSE_CODE, "0");
MDC.put(classNameProp, "");
- auditLogger.info("" + arg0);
+ auditLogger.info("{}", arg0);
+ }
+
+ /**
+ * Records a message with passed in message text and variable number of arguments.
+ *
+ * @param message class name if one argument, otherwise message text
+ * @param arguments variable number of arguments
+ */
+ public static void audit(String message, Object... arguments) {
+ if (!auditLogger.isInfoEnabled()) {
+ return;
+ }
+ MDC.put(INVOCATION_ID, postMdcInfoForEvent(null));
+ MDC.put(STATUS_CODE, COMPLETE_STATUS);
+ MDC.put(RESPONSE_CODE, "0");
+ if (arguments.length == 1 && !OnapLoggingUtils.isThrowable(arguments[0])) {
+ MDC.put(classNameProp, message);
+ auditLogger.info("{}", arguments[0] == null ? "" : arguments[0].toString());
+ return;
+ }
+
+ MDC.put(classNameProp, "");
+ auditLogger.info(message, arguments);
}
/**
@@ -823,7 +861,7 @@ public class PolicyLogger {
public static void trace(Object arg0) {
MDC.put(classNameProp, "");
- debugLogger.trace("" + arg0);
+ debugLogger.trace("{}", arg0);
}
/**
@@ -839,18 +877,18 @@ public class PolicyLogger {
if (eventTracker == null) {
eventTracker = new EventTrackInfo();
}
- EventData event = new EventData();
+ var event = new EventData();
event.setRequestId(eventId);
event.setStartTime(Instant.now());
eventTracker.storeEventData(event);
MDC.put(MDC_KEY_REQUEST_ID, eventId);
- debugLogger.info("CONCURRENTHASHMAP_LIMIT : " + concurrentHashMapLimit);
+ debugLogger.info("CONCURRENTHASHMAP_LIMIT : {}", concurrentHashMapLimit);
// --- Tracking the size of the concurrentHashMap, if it is above limit, keep EventTrack
// Timer running
int size = eventTracker.getEventInfo().size();
- debugLogger.info("EventInfo concurrentHashMap Size : " + size + " on " + new Date());
- debugLogger.info("isEventTrackerRunning : " + isEventTrackerRunning);
+ debugLogger.info("EventInfo concurrentHashMap Size : {} on {}", size, new Date());
+ debugLogger.info("isEventTrackerRunning : {}", isEventTrackerRunning);
if (size >= concurrentHashMapLimit) {
@@ -972,7 +1010,7 @@ public class PolicyLogger {
return;
}
- EventData event = eventTracker.getEventDataByRequestId(eventId);
+ var event = eventTracker.getEventDataByRequestId(eventId);
if (event != null) {
Instant endTime = event.getEndTime();
@@ -1000,7 +1038,7 @@ public class PolicyLogger {
return;
}
- EventData event = eventTracker.getEventDataByRequestId(eventId.toString());
+ var event = eventTracker.getEventDataByRequestId(eventId.toString());
if (event != null) {
Instant endTime = event.getEndTime();
@@ -1049,7 +1087,7 @@ public class PolicyLogger {
if (eventTracker != null && eventTracker.getEventDataByRequestId(eventId) != null) {
eventTracker.remove(eventId);
- debugLogger.info("eventTracker.remove(" + eventId + ")");
+ debugLogger.info("eventTracker.remove({})", eventId);
}
}
@@ -1066,6 +1104,7 @@ public class PolicyLogger {
String serviceName = MDC.get(MDC_SERVICE_NAME);
MDC.put(MDC_KEY_REQUEST_ID, eventId);
+ MDC.put(STATUS_CODE, COMPLETE_STATUS);
metricsLogger.info(MessageCodes.RULE_AUDIT_END_INFO, serviceName, arg1);
}
@@ -1084,6 +1123,7 @@ public class PolicyLogger {
MDC.put(classNameProp, className);
String serviceName = MDC.get(MDC_SERVICE_NAME);
MDC.put(MDC_KEY_REQUEST_ID, eventId);
+ MDC.put(STATUS_CODE, COMPLETE_STATUS);
metricsLogger.info(MessageCodes.RULE_AUDIT_END_INFO, serviceName, arg1);
}
@@ -1121,32 +1161,55 @@ public class PolicyLogger {
* @param arg0 the message
*/
public static void metrics(String arg0) {
+ seTimeStamps();
+ MDC.put(INVOCATION_ID, MDC.get(MDC_KEY_REQUEST_ID));
+ MDC.put(RESPONSE_CODE, "0");
String serviceName = MDC.get(MDC_SERVICE_NAME);
metricsLogger.info(MessageCodes.RULE_METRICS_INFO, serviceName, arg0);
}
/**
- * Records the metrics event with a class name and a String message.
+ * Records the metrics event with a String message.
*
* @param arg0 the message
*/
- public static void metrics(String className, Object arg0) {
+ public static void metrics(Object arg0) {
seTimeStamps();
- MDC.put(classNameProp, className);
+ MDC.put(INVOCATION_ID, MDC.get(MDC_KEY_REQUEST_ID));
+ MDC.put(RESPONSE_CODE, "0");
+ MDC.put(classNameProp, "");
String serviceName = MDC.get(MDC_SERVICE_NAME);
metricsLogger.info(MessageCodes.RULE_METRICS_INFO, serviceName, "" + arg0);
}
/**
- * Records the metrics event with a String message.
+ * Records a message with passed in message text and variable number of arguments.
*
- * @param arg0 the message
+ * @param message class name if one argument, otherwise message text
+ * @param arguments variable number of arguments
*/
- public static void metrics(Object arg0) {
+ public static void metrics(String message, Object... arguments) {
+ if (!metricsLogger.isInfoEnabled()) {
+ return;
+ }
seTimeStamps();
+ MDC.put(INVOCATION_ID, MDC.get(MDC_KEY_REQUEST_ID));
+ MDC.put(RESPONSE_CODE, "0");
+ if (arguments.length == 1 && !OnapLoggingUtils.isThrowable(arguments[0])) {
+ MDC.put(classNameProp, message);
+ String serviceName = MDC.get(MDC_SERVICE_NAME);
+ metricsLogger.info(MessageCodes.RULE_METRICS_INFO, serviceName,
+ arguments[0] == null ? "" : arguments[0].toString());
+ return;
+ }
+ if (arguments.length == 1 && OnapLoggingUtils.isThrowable(arguments[0])) {
+ String arguments2 = getNormalizedStackTrace((Throwable) arguments[0], "");
+ metricsLogger.info(MessageCodes.RULE_METRICS_INFO, message + arguments2);
+ return;
+ }
+
MDC.put(classNameProp, "");
- String serviceName = MDC.get(MDC_SERVICE_NAME);
- metricsLogger.info(MessageCodes.RULE_METRICS_INFO, serviceName, "" + arg0);
+ metricsLogger.info(message, arguments);
}
/**
@@ -1166,13 +1229,13 @@ public class PolicyLogger {
* @param arguments the messages
*/
private static String getNormalizedStackTrace(Throwable throwable, String... arguments) {
- StringWriter sw = new StringWriter();
- PrintWriter pw = new PrintWriter(sw);
+ var sw = new StringWriter();
+ var pw = new PrintWriter(sw);
throwable.printStackTrace(pw);
String newStValue = sw.toString().replace('|', '!').replace("\n", " - ");
int curSize = arguments == null ? 0 : arguments.length;
- StringBuilder newArgument = new StringBuilder();
- for (int i = 0; i < curSize; i++) {
+ var newArgument = new StringBuilder();
+ for (var i = 0; i < curSize; i++) {
newArgument.append(arguments[i]);
newArgument.append(":");
}
@@ -1186,12 +1249,12 @@ public class PolicyLogger {
private static void startCleanUp() {
if (!isEventTrackerRunning) {
- ttrcker = new EventTrackInfoHandler();
+ var ttrcker = new EventTrackInfoHandler();
timer = new Timer(true);
timer.scheduleAtFixedRate(ttrcker, timerDelayTime, checkInterval);
- debugLogger.info("EventTrackInfoHandler begins! : " + new Date());
+ debugLogger.info("EventTrackInfoHandler begins! : {}", new Date());
} else {
- debugLogger.info("Timer is still running : " + new Date());
+ debugLogger.info("Timer is still running : {}", new Date());
}
}
@@ -1205,9 +1268,9 @@ public class PolicyLogger {
if (isEventTrackerRunning && timer != null) {
timer.cancel();
timer.purge();
- debugLogger.info("Timer stopped: " + new Date());
+ debugLogger.info("Timer stopped: {}", new Date());
} else {
- debugLogger.info("Timer was already stopped : " + new Date());
+ debugLogger.info("Timer was already stopped : {}", new Date());
}
isEventTrackerRunning = false;
@@ -1219,7 +1282,7 @@ public class PolicyLogger {
*/
public static LoggerType init(Properties properties) {
- Properties loggerProperties = getLoggerProperties(properties);
+ var loggerProperties = getLoggerProperties(properties);
// fetch and verify definitions of some properties
try {
@@ -1241,7 +1304,7 @@ public class PolicyLogger {
stopCheckPoint = getIntProp(loggerProperties, "stop.check.point", stopCheckPoint);
component = loggerProperties.getProperty("policy.component", "DROOLS");
- debugLogger.info("component: " + component);
+ debugLogger.info("component: {}", component);
return detmLoggerType(loggerProperties);
@@ -1261,9 +1324,9 @@ public class PolicyLogger {
}
private static int getIntProp(Properties properties, String propName, int defaultValue) {
- final int propValue = Integer.parseInt(properties.getProperty(propName, String.valueOf(defaultValue)));
+ final var propValue = Integer.parseInt(properties.getProperty(propName, String.valueOf(defaultValue)));
- debugLogger.info(propName + " value: " + propValue);
+ debugLogger.info("{} value: {}", propName, propValue);
if (propValue > 0) {
return propValue;
@@ -1276,7 +1339,7 @@ public class PolicyLogger {
ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR).getErrorDesc());
}
- errorLogger.error("failed to get the " + propName + ", so use its default value: " + defaultValue);
+ errorLogger.error("failed to get the {}, so use its default value: {}", propName, defaultValue);
return defaultValue;
}
}
@@ -1296,7 +1359,7 @@ public class PolicyLogger {
final String propValue = properties.getProperty(propName, defaultValue);
if (!StringUtils.isBlank(propValue)) {
- debugLogger.info(propName + " level: " + propValue);
+ debugLogger.info("{} level: {}", propName, propValue);
}
setter.accept(propValue);
@@ -1306,31 +1369,27 @@ public class PolicyLogger {
final String propValue = properties.getProperty(propName, "ON");
if (Level.OFF.toString().equalsIgnoreCase(propValue)) {
- debugLogger.info(propName + " level: " + propValue);
+ debugLogger.info("{} level: {}", propName, propValue);
}
setter.accept(propValue);
}
private static void setOverrideLogbackLevels(Properties loggerProperties) {
- final String overrideLogbackLevel = loggerProperties.getProperty("override.logback.level.setup");
+ final var overrideLogbackLevelText = loggerProperties.getProperty("override.logback.level.setup");
- if (!StringUtils.isBlank(overrideLogbackLevel)) {
- isOverrideLogbackLevel = "TRUE".equalsIgnoreCase(overrideLogbackLevel);
+ if (!StringUtils.isBlank(overrideLogbackLevelText)) {
+ overrideLogbackLevel = "TRUE".equalsIgnoreCase(overrideLogbackLevelText);
}
}
private static LoggerType detmLoggerType(Properties loggerProperties) {
final String loggerTypeProp = loggerProperties.getProperty("logger.type", LoggerType.EELF.toString());
- debugLogger.info("loggerType value: " + loggerTypeProp);
+ debugLogger.info("loggerType value: {}", loggerTypeProp);
switch (loggerTypeProp.toUpperCase()) {
case "EELF":
return LoggerType.EELF;
-
- case "LOG4J":
- return LoggerType.LOG4J;
-
case "SYSTEMOUT":
return LoggerType.SYSTEMOUT;
@@ -1339,28 +1398,26 @@ public class PolicyLogger {
}
}
-
/**
- * Returns true for overriding logback levels; returns false for not.
- */
- public static boolean isOverrideLogbackLevel() {
-
- return isOverrideLogbackLevel;
- }
-
- /**
- * Sets true for overriding logback levels; sets false for not.
+ * Sets server information to MDC.
*/
- public static void setOverrideLogbackLevel(boolean odl) {
-
- isOverrideLogbackLevel = odl;
-
+ public static void setServerInfo(String serverHost, String serverPort) {
+ MDC.put(SERVER_NAME, serverHost + ":" + serverPort);
}
/**
- * Sets server information to MDC.
+ * Sets error category, code and description.
*/
- public static void setServerInfo(String serverHost, String serverPort) {
- MDC.put(SERVER_NAME, serverHost + ":" + serverPort);
+ private static void setErrorCode(MessageCodes errcode) {
+ MDC.put(ERROR_CATEGORY, ERROR_CATEGORY_VALUE);
+ if (ErrorCodeMap.getErrorCodeInfo(errcode) != null) {
+ MDC.put(ERROR_CODE, ErrorCodeMap.getErrorCodeInfo(errcode).getErrorCode());
+ MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.getErrorCodeInfo(errcode).getErrorDesc());
+ } else {
+ MDC.put(ERROR_CODE,
+ ErrorCodeMap.getErrorCodeInfo(MessageCodes.ERROR_UNKNOWN).getErrorCode());
+ MDC.put(ERROR_DESCRIPTION,
+ ErrorCodeMap.getErrorCodeInfo(MessageCodes.ERROR_UNKNOWN).getErrorDesc());
+ }
}
}
diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/DisplayUtils.java b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/DisplayUtils.java
index dc740440..425c62a4 100644
--- a/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/DisplayUtils.java
+++ b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/DisplayUtils.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-2021 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.
@@ -20,22 +20,28 @@
package org.onap.policy.common.logging.flexlogger;
+import lombok.AccessLevel;
+import lombok.NoArgsConstructor;
+
/**
* Utilities to display messages. These are generally used while logging is being
* configured, or when logging being directed to System.out. As a result, it directly
* writes to System.out rather than to a logger.
*/
+
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class DisplayUtils {
- private DisplayUtils() {
- // do nothing
- }
+ /*
+ * As the comment above says, these purposely write to System.out rather than a
+ * logger, thus sonar is disabled.
+ */
public static void displayMessage(Object message) {
- System.out.println(message);
+ System.out.println(message); // NOSONAR
}
public static void displayErrorMessage(Object msg) {
- System.err.println(msg);
+ System.err.println(msg); // NOSONAR
}
}
diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/EelfLogger.java b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/EelfLogger.java
index a3e5cc8f..0e0ef2bf 100644
--- a/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/EelfLogger.java
+++ b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/EelfLogger.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2021 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.
@@ -21,10 +21,9 @@
package org.onap.policy.common.logging.flexlogger;
import com.att.eelf.configuration.EELFLogger.Level;
-
import java.io.Serializable;
import java.util.UUID;
-
+import lombok.Getter;
import org.onap.policy.common.logging.eelf.MessageCodes;
import org.onap.policy.common.logging.eelf.PolicyLogger;
@@ -36,6 +35,7 @@ public class EelfLogger implements Logger, Serializable {
private static final long serialVersionUID = 5385586713941277192L;
private String className = "";
+ @Getter
private String transId = UUID.randomUUID().toString();
/**
@@ -137,14 +137,6 @@ public class EelfLogger implements Logger, Serializable {
}
/**
- * Returns transaction Id for logging.
- */
- @Override
- public String getTransId() {
- return transId;
- }
-
- /**
* Records a message.
*
* @param message the message
@@ -166,6 +158,17 @@ public class EelfLogger implements Logger, Serializable {
}
/**
+ * Records a message.
+ *
+ * @param message the message
+ * @param arguments the arguments for message
+ */
+ @Override
+ public void debug(String message, Object... arguments) {
+ PolicyLogger.debug(message, arguments);
+ }
+
+ /**
* Records an error message.
*
* @param message the message
@@ -210,6 +213,17 @@ public class EelfLogger implements Logger, Serializable {
}
/**
+ * Records an error message.
+ *
+ * @param message the message
+ * @param arguments the arguments for message
+ */
+ @Override
+ public void error(String message, Object... arguments) {
+ PolicyLogger.error(message, arguments);
+ }
+
+ /**
* Records a message.
*
* @param message the message
@@ -234,6 +248,17 @@ public class EelfLogger implements Logger, Serializable {
* Records a message.
*
* @param message the message
+ * @param arguments the arguments for message
+ */
+ @Override
+ public void info(String message, Object... arguments) {
+ PolicyLogger.info(message, arguments);
+ }
+
+ /**
+ * Records a message.
+ *
+ * @param message the message
*/
@Override
public void warn(Object message) {
@@ -278,6 +303,17 @@ public class EelfLogger implements Logger, Serializable {
* Records a message.
*
* @param message the message
+ * @param arguments the arguments for message
+ */
+ @Override
+ public void warn(String message, Object... arguments) {
+ PolicyLogger.warn(message, arguments);
+ }
+
+ /**
+ * Records a message.
+ *
+ * @param message the message
*/
@Override
public void trace(Object message) {
@@ -387,6 +423,17 @@ public class EelfLogger implements Logger, Serializable {
}
/**
+ * Records a message.
+ *
+ * @param message the message
+ * @param arguments the arguments for message
+ */
+ @Override
+ public void audit(String message, Object... arguments) {
+ PolicyLogger.audit(message, arguments);
+ }
+
+ /**
* Records an audit message.
*
* @param eventId the event ID
@@ -485,6 +532,17 @@ public class EelfLogger implements Logger, Serializable {
}
/**
+ * Records a message.
+ *
+ * @param message the message
+ * @param arguments the arguments for message
+ */
+ @Override
+ public void metrics(String message, Object... arguments) {
+ PolicyLogger.metrics(message, arguments);
+ }
+
+ /**
* Populates MDC Info.
*
* @param transId the transaction ID
diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/FlexLogger.java b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/FlexLogger.java
index 030363dc..6c301712 100644
--- a/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/FlexLogger.java
+++ b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/FlexLogger.java
@@ -2,7 +2,8 @@
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2023 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -29,7 +30,6 @@ import java.util.Date;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
-
import org.onap.policy.common.logging.eelf.PolicyLogger;
import org.onap.policy.common.logging.flexlogger.PropertyUtil.Listener;
@@ -40,13 +40,12 @@ public class FlexLogger extends SecurityManager {
private static final String GET_LOGGER_PREFIX = "FlexLogger:getLogger : loggerType = ";
private static LoggerType loggerType = LoggerType.EELF;
- private static ConcurrentHashMap<String, Logger4J> logger4JMap = new ConcurrentHashMap<>();
private static ConcurrentHashMap<String, EelfLogger> eelfLoggerMap = new ConcurrentHashMap<>();
private static ConcurrentHashMap<String, SystemOutLogger> systemOutMap = new ConcurrentHashMap<>();
// --- init logger first
static {
- loggerType = initlogger();
+ loggerType = initLogger();
}
/**
@@ -55,103 +54,41 @@ public class FlexLogger extends SecurityManager {
* @param clazz the class
*/
public static Logger getLogger(Class<?> clazz) {
- Logger logger = null;
- displayMessage(GET_LOGGER_PREFIX + loggerType);
- switch (loggerType) {
-
- case EELF:
- logger = getEelfLogger(clazz, false);
- break;
- case LOG4J:
- logger = getLog4JLogger();
- break;
- case SYSTEMOUT:
- default:
- logger = getSystemOutLogger();
- break;
- }
-
- return logger;
-
+ return getLogger(clazz, false);
}
/**
* Returns an instance of Logger.
- *
- * @param name the name of the logger
*/
- public static Logger getLogger(String name) {
- Logger logger = null;
- displayMessage(GET_LOGGER_PREFIX + loggerType);
- switch (loggerType) {
-
- case EELF:
- logger = getEelfLogger(null, false);
- break;
- case LOG4J:
- logger = getLog4JLogger(name);
- break;
- case SYSTEMOUT:
- default:
- logger = getSystemOutLogger();
- break;
- }
-
- return logger;
-
+ public static Logger getLogger() {
+ return getLogger(null);
}
/**
* Returns an instance of Logger.
*
- * @param clazz the class
+ * @param clazz the class
* @param isNewTransaction is a new transaction
*/
public static Logger getLogger(Class<?> clazz, boolean isNewTransaction) {
- Logger logger = null;
+ Logger logger;
displayMessage(GET_LOGGER_PREFIX + loggerType);
- switch (loggerType) {
-
- case EELF:
- logger = getEelfLogger(clazz, isNewTransaction);
- break;
- case LOG4J:
- logger = getLog4JLogger();
- break;
- case SYSTEMOUT:
- default:
- logger = getSystemOutLogger();
- break;
+ if (loggerType == LoggerType.EELF) {
+ logger = getEelfLogger(clazz, isNewTransaction);
+ } else {
+ logger = getSystemOutLogger();
}
return logger;
-
}
/**
* Returns an instance of Logger.
*
- * @param name the name of the logger
* @param isNewTransaction is a new transaction
*/
- public static Logger getLogger(String name, boolean isNewTransaction) {
- Logger logger = null;
- displayMessage(GET_LOGGER_PREFIX + loggerType);
- switch (loggerType) {
-
- case EELF:
- logger = getEelfLogger(null, isNewTransaction);
- break;
- case LOG4J:
- logger = getLog4JLogger(name);
- break;
- case SYSTEMOUT:
- default:
- logger = getSystemOutLogger();
- break;
- }
-
- return logger;
+ public static Logger getLogger(boolean isNewTransaction) {
+ return getLogger(null, isNewTransaction);
}
/**
@@ -163,40 +100,9 @@ public class FlexLogger extends SecurityManager {
}
/**
- * Returns an instance of Logger4J.
- */
- private static Logger4J getLog4JLogger() {
- String className = new FlexLogger().getClassName();
-
- if (!logger4JMap.containsKey(className)) {
- // for 1610 release use the default debug.log for log4j
- Logger4J logger = new Logger4J("debugLogger", className);
- logger4JMap.put(className, logger);
- }
-
- return logger4JMap.get(className);
- }
-
- /**
- * Returns an instance of Logger4J.
- *
- * @param name the name of the logger
- */
- private static Logger4J getLog4JLogger(String name) {
- String className = new FlexLogger().getClassName();
-
- if (!logger4JMap.containsKey(className)) {
- Logger4J logger = new Logger4J(name, className);
- logger4JMap.put(className, logger);
- }
-
- return logger4JMap.get(className);
- }
-
- /**
* Returns an instance of EelfLogger.
*
- * @param clazz the class
+ * @param clazz the class
* @param isNewTransaction is a new transaction
*/
private static EelfLogger getEelfLogger(Class<?> clazz, boolean isNewTransaction) {
@@ -209,21 +115,13 @@ public class FlexLogger extends SecurityManager {
className = new FlexLogger().getClassName();
}
- if (!eelfLoggerMap.containsKey(className)) {
- logger = new EelfLogger(clazz, isNewTransaction);
- eelfLoggerMap.put(className, logger);
- } else {
- logger = eelfLoggerMap.get(className);
- if (logger == null) {
- logger = new EelfLogger(clazz, isNewTransaction);
- eelfLoggerMap.put(className, logger);
- }
- // installl already created but it is new transaction
- if (isNewTransaction) {
- String transId = PolicyLogger.postMdcInfoForEvent(null);
- logger.setTransId(transId);
- }
+ logger = eelfLoggerMap.computeIfAbsent(className, key -> new EelfLogger(clazz, isNewTransaction));
+
+ if (isNewTransaction) {
+ String transId = PolicyLogger.postMdcInfoForEvent(null);
+ logger.setTransId(transId);
}
+
displayMessage("eelfLoggerMap size : " + eelfLoggerMap.size() + " class name: " + className);
return logger;
}
@@ -235,37 +133,30 @@ public class FlexLogger extends SecurityManager {
String className = new FlexLogger().getClassName();
- if (!systemOutMap.containsKey(className)) {
- SystemOutLogger logger = new SystemOutLogger(className);
- systemOutMap.put(className, logger);
- }
-
- return systemOutMap.get(className);
+ return systemOutMap.computeIfAbsent(className, SystemOutLogger::new);
}
/**
* loads the logger properties.
*/
- private static LoggerType initlogger() {
- LoggerType loggerType = LoggerType.EELF;
+ private static LoggerType initLogger() {
+ var loggerType = LoggerType.EELF;
Properties properties = null;
try {
properties = PropertyUtil.getProperties("config/policyLogger.properties");
displayMessage("FlexLogger:properties => " + properties);
- if (properties != null) {
- String overrideLogbackLevel = properties.getProperty("override.logback.level.setup");
- displayMessage("FlexLogger:overrideLogbackLevel => " + overrideLogbackLevel);
- String loggerTypeString = properties.getProperty("logger.type");
- if ("EELF".equalsIgnoreCase(loggerTypeString) && "TRUE".equalsIgnoreCase(overrideLogbackLevel)) {
- displayMessage("FlexLogger: start listener.");
- properties = PropertyUtil.getProperties("config/policyLogger.properties",
- new PropertiesCallBack("FlexLogger-CallBack"));
- }
+ String overrideLogbackLevel = properties.getProperty("override.logback.level.setup");
+ displayMessage("FlexLogger:overrideLogbackLevel => " + overrideLogbackLevel);
+ var loggerTypeString = properties.getProperty("logger.type");
+ if ("EELF".equalsIgnoreCase(loggerTypeString) && "TRUE".equalsIgnoreCase(overrideLogbackLevel)) {
+ displayMessage("FlexLogger: start listener.");
+ properties = PropertyUtil.getProperties("config/policyLogger.properties",
+ new PropertiesCallBack("FlexLogger-CallBack"));
}
} catch (IOException e1) {
- displayMessage("initlogger" + e1);
+ displayMessage("initLogger" + e1);
} finally {
// OK to pass no properties (null)
loggerType = PolicyLogger.init(properties);
@@ -295,10 +186,10 @@ public class FlexLogger extends SecurityManager {
String auditLevel = properties.getProperty("audit.level");
String errorLevel = properties.getProperty("error.level");
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+00:00");
- Instant startTime = Instant.now();
- String formatedTime = sdf.format(Date.from(startTime));
- displayMessage("FlexLogger.propertiesChanged : called at time : " + formatedTime);
+ var sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+00:00");
+ var startTime = Instant.now();
+ String formattedTime = sdf.format(Date.from(startTime));
+ displayMessage("FlexLogger.propertiesChanged : called at time : " + formattedTime);
displayMessage("FlexLogger.propertiesChanged : debugLevel : " + debugLevel);
if (changedKeys != null) {
diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/Logger.java b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/Logger.java
index d6f020e0..ad155a4c 100644
--- a/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/Logger.java
+++ b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/Logger.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2020 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.
@@ -21,7 +21,6 @@
package org.onap.policy.common.logging.flexlogger;
import java.util.UUID;
-
import org.onap.policy.common.logging.eelf.MessageCodes;
/**
@@ -41,6 +40,11 @@ public interface Logger {
public void debug(Object message, Throwable throwable);
/**
+ * Prints messages with the level.DEBUG
+ */
+ public void debug(String message, Object... arguments);
+
+ /**
* Prints messages with the level.ERROR
*/
public void error(Object message);
@@ -61,6 +65,11 @@ public interface Logger {
public void error(MessageCodes msg, Throwable arg0, String... arguments);
/**
+ * Prints messages with the level.ERROR
+ */
+ public void error(String message, Object... arguments);
+
+ /**
* Prints messages with the level.INFO
*/
public void info(Object message);
@@ -71,6 +80,11 @@ public interface Logger {
public void info(Object message, Throwable throwable);
/**
+ * Prints messages with the level.INFO
+ */
+ public void info(String message, Object... arguments);
+
+ /**
* Prints messages with the level.WARN
*/
public void warn(Object message);
@@ -91,6 +105,11 @@ public interface Logger {
public void warn(MessageCodes msg, Throwable arg0, String... arguments);
/**
+ * Prints messages with the level.WARN
+ */
+ public void warn(String message, Object... arguments);
+
+ /**
* Prints messages with the level.TRACE
*/
public void trace(Object message);
@@ -111,6 +130,11 @@ public interface Logger {
public void audit(Object arg0, Throwable throwable);
/**
+ * Prints messages in audit log with the level.INFO
+ */
+ public void audit(String message, Object... arguments);
+
+ /**
* Records event Id in audit log with the level.INFO
*/
public void recordAuditEventStart(String eventId);
@@ -157,6 +181,11 @@ public interface Logger {
public void metrics(Object arg0);
/**
+ * Records the Metrics log message.
+ */
+ public void metrics(String message, Object... arguments);
+
+ /**
* Returns a boolean value, true for debug logging enabled, false for not enabled.
*/
public boolean isDebugEnabled();
diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/Logger4J.java b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/Logger4J.java
deleted file mode 100644
index 8802d17e..00000000
--- a/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/Logger4J.java
+++ /dev/null
@@ -1,514 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * ONAP-Logging
- * ================================================================================
- * Copyright (C) 2017-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.policy.common.logging.flexlogger;
-
-import static org.onap.policy.common.logging.flexlogger.DisplayUtils.displayMessage;
-
-import com.att.eelf.configuration.EELFLogger.Level;
-
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.io.Serializable;
-import java.util.Arrays;
-import java.util.UUID;
-
-import org.apache.log4j.Logger;
-import org.apache.log4j.Priority;
-import org.onap.policy.common.logging.eelf.MessageCodes;
-import org.onap.policy.common.logging.eelf.PolicyLogger;
-
-/**
- * Logger4J implements all the methods of interface Logger by calling org.apache.log4j.Logger
- */
-public class Logger4J implements org.onap.policy.common.logging.flexlogger.Logger, Serializable {
-
- private static final long serialVersionUID = 3183729429888828471L;
- private Logger log = null;
- private String methodName = "";
- private String className = "";
- private String transId = UUID.randomUUID().toString();
-
- /**
- * Constructor.
- *
- * @param clazz the class
- */
- public Logger4J(Class<?> clazz) {
- displayMessage("create instance of Logger4J");
- if (clazz != null) {
- log = Logger.getLogger(clazz);
- className = clazz.getName();
- }
- }
-
- /**
- * Constructor.
- *
- * @param name the name of the logger
- * @param className the name of the class
- */
- public Logger4J(String name, String className) {
- displayMessage("create instance of Logger4J");
- if (name != null) {
- log = Logger.getLogger(name);
- }
- this.className = className;
- }
-
- /**
- * Sets transaction Id.
- */
- @Override
- public void setTransId(String transId) {
- log.info(transId);
- this.transId = transId;
- }
-
- /**
- * Returns transaction Id.
- */
- @Override
- public String getTransId() {
- return transId;
- }
-
- /**
- * Records a message.
- *
- * @param message the message
- */
- @Override
- public void debug(Object message) {
- if (isDebugEnabled()) {
- log.debug(transId + "|" + message);
- }
- }
-
- /**
- * Records a message.
- *
- * @param message the message
- * @param throwable the throwable
- */
- @Override
- public void debug(Object message, Throwable throwable) {
- log.debug(message, throwable);
- }
-
- /**
- * Records an error message.
- *
- * @param message the message
- */
- @Override
- public void error(Object message) {
- log.error(transId + "|" + className + "|" + message);
- }
-
- /**
- * Records an error message.
- *
- * @param message the message
- * @param throwable the throwable
- */
- @Override
- public void error(Object message, Throwable throwable) {
- log.error(message, throwable);
- }
-
- /**
- * Records an error message.
- *
- * @param msg the message code
- * @param throwable the throwable
- * @param arguments the messages
- */
- @Override
- public void error(MessageCodes msg, Throwable throwable, String... arguments) {
- log.error(transId + "|" + className + "|" + "MessageCodes :" + msg + Arrays.asList(arguments));
-
- }
-
- /**
- * Records an error message.
- *
- * @param msg the message code
- * @param arguments the messages
- */
- @Override
- public void error(MessageCodes msg, String... arguments) {
- log.error(transId + "|" + className + "|" + "MessageCode:" + msg + Arrays.asList(arguments));
- }
-
- /**
- * Records a message.
- *
- * @param message the message
- */
- @Override
- public void info(Object message) {
- log.info(transId + "|" + className + "|" + message);
- }
-
- /**
- * Records a message.
- *
- * @param message the message
- * @param throwable the throwable
- */
- @Override
- public void info(Object message, Throwable throwable) {
- log.info(message, throwable);
- }
-
- /**
- * Records a message.
- *
- * @param message the message
- */
- @Override
- public void warn(Object message) {
- log.warn(transId + "|" + className + "|" + message);
- }
-
- /**
- * Records a message.
- *
- * @param message the message
- * @param throwable the throwable
- */
- @Override
- public void warn(Object message, Throwable throwable) {
- log.warn(message, throwable);
- }
-
- /**
- * Records a message.
- *
- * @param msg the message code
- * @param arguments the messages
- */
- @Override
- public void warn(MessageCodes msg, String... arguments) {
- log.warn(className + "|" + "MessageCodes:" + msg + Arrays.asList(arguments));
- }
-
- /**
- * Records a message.
- *
- * @param msg the message code
- * @param throwable the throwable
- * @param arguments the messages
- */
- @Override
- public void warn(MessageCodes msg, Throwable throwable, String... arguments) {
- log.warn(className + "|" + "MessageCodes:" + msg + Arrays.asList(arguments));
- }
-
- /**
- * Records a message.
- *
- * @param message the message
- */
- @Override
- public void trace(Object message) {
- log.trace(transId + "|" + className + "|" + message);
- }
-
- /**
- * Records a message.
- *
- * @param message the message
- * @param throwable the throwable
- */
- @Override
- public void trace(Object message, Throwable throwable) {
- log.trace(message, throwable);
- }
-
- /**
- * Returns true for debug enabled, or false for not.
- *
- * @return boolean
- */
- @Override
- public boolean isDebugEnabled() {
- return log.isDebugEnabled();
- }
-
- /**
- * Returns true for error enabled, or false for not.
- *
- * @return boolean
- */
- @SuppressWarnings("deprecation")
- @Override
- public boolean isErrorEnabled() {
- return log.isEnabledFor(Priority.ERROR);
- }
-
- /**
- * Returns true for info enabled, or false for not.
- *
- * @return boolean
- */
- @Override
- public boolean isInfoEnabled() {
- return log.isInfoEnabled();
- }
-
- /**
- * Returns true for warn enabled, or false for not.
- *
- * @return boolean
- */
- @SuppressWarnings("deprecation")
- @Override
- public boolean isWarnEnabled() {
- // return log4j value
- return log.isEnabledFor(Priority.WARN);
- }
-
- /**
- * Returns true for audit enabled, or false for not.
- *
- * @return boolean
- */
- @Override
- public boolean isAuditEnabled() {
- return (PolicyLogger.getAuditLevel() != Level.OFF);
- }
-
- /**
- * Returns true for metrics enabled, or false for not.
- *
- * @return boolean
- */
- @Override
- public boolean isMetricsEnabled() {
- return (PolicyLogger.getMetricsLevel() != Level.OFF);
- }
-
- /**
- * Records an audit message.
- *
- * @param message the message
- */
- @Override
- public void audit(Object message) {
- log.info(className + "|" + message);
- }
-
- /**
- * Records an audit message.
- *
- * @param message the message
- * @param throwable the throwable
- */
-
- @Override
- public void audit(Object message, Throwable throwable) {
- log.info(message, throwable);
- }
-
- /**
- * Records an audit message.
- *
- * @param eventId the event ID
- */
- @Override
- public void recordAuditEventStart(String eventId) {
- log.info(className + "|recordAuditEventStart with eventId " + eventId);
- }
-
- /**
- * Records an audit message.
- *
- * @param eventId the event ID
- */
- @Override
- public void recordAuditEventStart(UUID eventId) {
- if (eventId != null) {
- recordAuditEventStart(eventId.toString());
- }
- }
-
- /**
- * Records an audit message.
- *
- * @param eventId the event ID
- * @param rule the rule
- * @param policyVersion the policy version
- */
- @Override
- public void recordAuditEventEnd(String eventId, String rule, String policyVersion) {
- log.info(className + "|" + eventId + ":" + rule);
- }
-
- /**
- * Records an audit message.
- *
- * @param eventId the event ID
- * @param rule the rule
- * @param policyVersion the policy version
- */
- @Override
- public void recordAuditEventEnd(UUID eventId, String rule, String policyVersion) {
- if (eventId != null) {
- recordAuditEventEnd(eventId.toString(), rule, policyVersion);
- } else {
- recordAuditEventEnd(eventId, rule, policyVersion);
- }
- }
-
- /**
- * Records an audit message.
- *
- * @param eventId the event ID
- * @param rule the rule
- */
- @Override
- public void recordAuditEventEnd(String eventId, String rule) {
- log.info(className + "|" + eventId + ":" + rule);
- }
-
- /**
- * Records an audit message.
- *
- * @param eventId the event ID
- * @param rule the rule
- */
- @Override
- public void recordAuditEventEnd(UUID eventId, String rule) {
- if (eventId != null) {
- recordAuditEventEnd(eventId.toString(), rule);
- } else {
- recordAuditEventEnd(eventId, rule);
- }
- }
-
- /**
- * Records a metrics message.
- *
- * @param eventId the event ID
- * @param message the message
- */
- @Override
- public void recordMetricEvent(String eventId, String message) {
- log.info(className + "|" + eventId + ":" + message);
-
- }
-
- /**
- * Records a metrics message.
- *
- * @param eventId the event ID
- * @param message the message
- */
- @Override
- public void recordMetricEvent(UUID eventId, String message) {
- if (eventId != null) {
- recordMetricEvent(eventId.toString(), message);
- } else {
- recordMetricEvent(eventId, message);
- }
- }
-
- /**
- * Records a metrics message.
- *
- * @param message the message
- */
- @Override
- public void metrics(Object message) {
- log.info(message);
- }
-
- /**
- * Returns transaction Id.
- *
- * @param transId the transaction ID
- */
- @Override
- public String postMdcInfoForEvent(String transId) {
- String transactionId = transId;
- if (transactionId == null || transactionId.isEmpty()) {
- transactionId = UUID.randomUUID().toString();
- }
-
- return transactionId;
- }
-
- /**
- * Records transaction Id.
- *
- * @param message the message
- */
- @Override
- public void postMdcInfoForEvent(Object message) {
- log.info(message);
- }
-
- /**
- * Returns true for trace enabled, or false for not.
- *
- * @return boolean
- */
- @Override
- public boolean isTraceEnabled() {
- return log.isTraceEnabled();
- }
-
- /**
- * Records transaction Id.
- *
- * @param transId the transaction ID
- */
- @Override
- public void postMdcInfoForTriggeredRule(String transId) {
- log.info(transId);
- }
-
- /* ============================================================ */
-
- /*
- * Support for 'Serializable' -- the default rules don't work for the 'log' field
- */
-
- private void writeObject(ObjectOutputStream out) throws IOException {
- // write out 'methodName', 'className', 'transId' strings
- out.writeObject(methodName);
- out.writeObject(className);
- out.writeObject(transId);
- }
-
- private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
-
- // read in 'methodName', 'className', 'transId' strings
- methodName = (String) (in.readObject());
- className = (String) (in.readObject());
- transId = (String) (in.readObject());
-
- // look up associated logger
- log = Logger.getLogger(className);
- }
-}
diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/LoggerType.java b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/LoggerType.java
index 8bf0dd78..f73bc4bc 100644
--- a/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/LoggerType.java
+++ b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/LoggerType.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2020 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.
@@ -24,5 +24,5 @@ package org.onap.policy.common.logging.flexlogger;
* Logger types.
*/
public enum LoggerType {
- EELF, LOG4J, SYSTEMOUT
+ EELF, SYSTEMOUT
}
diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/PropertyUtil.java b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/PropertyUtil.java
index 38759bc2..ef6c2e95 100644
--- a/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/PropertyUtil.java
+++ b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/PropertyUtil.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2021 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.
@@ -32,13 +32,17 @@ import java.util.Properties;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
+import lombok.AccessLevel;
+import lombok.NoArgsConstructor;
/**
* This class provides utilities to read properties from a properties file, and optionally get
* notifications of future changes.
*/
-public class PropertyUtil {
+public final class PropertyUtil {
+
+ @NoArgsConstructor(access = AccessLevel.PRIVATE)
protected static class LazyHolder {
/**
* Timer thread. Will not be allocated by the JVM until it is first referenced.
@@ -60,17 +64,13 @@ public class PropertyUtil {
*/
public static Properties getProperties(File file) throws IOException {
// create an InputStream (may throw a FileNotFoundException)
- FileInputStream fis = new FileInputStream(file);
- try {
+ try (var fis = new FileInputStream(file)) {
// create the properties instance
- Properties rval = new Properties();
+ var rval = new Properties();
// load properties (may throw an IOException)
rval.load(fis);
return rval;
- } finally {
- // close input stream
- fis.close();
}
}
@@ -202,7 +202,7 @@ public class PropertyUtil {
lastModified = timestamp;
// Save old set, and initial set of changed properties.
- Properties oldProperties = properties;
+ var oldProperties = properties;
HashSet<String> changedProperties = new HashSet<>(oldProperties.stringPropertyNames());
// Fetch the list of listeners that we will potentially notify,
@@ -238,7 +238,7 @@ public class PropertyUtil {
for (final Listener notify : listeners) {
// Copy 'properties' and 'changedProperties', so it doesn't
// cause problems if the recipient makes changes.
- final Properties tmpProperties = (Properties) (properties.clone());
+ final var tmpProperties = (Properties) (properties.clone());
final HashSet<String> tmpChangedProperties = new HashSet<>(changedProperties);
// Do the notification in a separate thread, so blocking
@@ -276,7 +276,7 @@ public class PropertyUtil {
// Convert the file to a canonical form in order to avoid the situation
// where different names refer to the same file.
- File tempFile = file.getCanonicalFile();
+ var tempFile = file.getCanonicalFile();
// See if there is an existing registration. The 'synchronized' block
// is needed to handle the case where a new listener is added at about
diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/SystemOutLogger.java b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/SystemOutLogger.java
index f7a68a3d..d16a1d7a 100644
--- a/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/SystemOutLogger.java
+++ b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/SystemOutLogger.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2021 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.
@@ -23,27 +23,28 @@ package org.onap.policy.common.logging.flexlogger;
import static org.onap.policy.common.logging.flexlogger.DisplayUtils.displayMessage;
import com.att.eelf.configuration.EELFLogger.Level;
-
import java.io.Serializable;
import java.util.Arrays;
import java.util.UUID;
-
+import lombok.Getter;
+import org.onap.policy.common.logging.OnapLoggingUtils;
import org.onap.policy.common.logging.eelf.MessageCodes;
import org.onap.policy.common.logging.eelf.PolicyLogger;
/**
* SystemOutLogger implements all the methods of interface Logger by calling System.out.println
*/
+@Getter
public class SystemOutLogger implements Logger, Serializable {
private static final long serialVersionUID = 4956408061058933929L;
private String className = "";
- private boolean isDebugEnabled = true;
- private boolean isInfoEnabled = true;
- private boolean isWarnEnabled = true;
- private boolean isErrorEnabled = true;
- private boolean isAuditEnabled = true;
- private boolean isMetricsEnabled = true;
+ private boolean debugEnabled = true;
+ private boolean infoEnabled = true;
+ private boolean warnEnabled = true;
+ private boolean errorEnabled = true;
+ private boolean auditEnabled = true;
+ private boolean metricsEnabled = true;
private String transId = UUID.randomUUID().toString();
/**
@@ -78,35 +79,35 @@ public class SystemOutLogger implements Logger, Serializable {
private void initLevel() {
if (PolicyLogger.getDebugLevel() == Level.DEBUG) {
- isDebugEnabled = true;
- isInfoEnabled = true;
- isWarnEnabled = true;
+ debugEnabled = true;
+ infoEnabled = true;
+ warnEnabled = true;
} else {
- isDebugEnabled = false;
+ debugEnabled = false;
}
if (PolicyLogger.getDebugLevel() == Level.INFO) {
- isInfoEnabled = true;
- isWarnEnabled = true;
- isDebugEnabled = false;
+ infoEnabled = true;
+ warnEnabled = true;
+ debugEnabled = false;
}
if (PolicyLogger.getDebugLevel() == Level.OFF) {
- isInfoEnabled = false;
- isWarnEnabled = false;
- isDebugEnabled = false;
+ infoEnabled = false;
+ warnEnabled = false;
+ debugEnabled = false;
}
if (PolicyLogger.getErrorLevel() == Level.OFF) {
- isErrorEnabled = false;
+ errorEnabled = false;
}
if (PolicyLogger.getAuditLevel() == Level.OFF) {
- isAuditEnabled = false;
+ auditEnabled = false;
}
if (PolicyLogger.getMetricsLevel() == Level.OFF) {
- isMetricsEnabled = false;
+ metricsEnabled = false;
}
}
@@ -121,15 +122,6 @@ public class SystemOutLogger implements Logger, Serializable {
}
/**
- * Returns transaction Id.
- */
- @Override
- public String getTransId() {
-
- return transId;
- }
-
- /**
* Records a message.
*
* @param message the message
@@ -152,6 +144,21 @@ public class SystemOutLogger implements Logger, Serializable {
}
/**
+ * Records a message.
+ *
+ * @param message the message
+ * @param arguments variable number of arguments
+ */
+ @Override
+ public void debug(String message, Object...arguments) {
+ if (arguments.length == 1 && OnapLoggingUtils.isThrowable(arguments[0])) {
+ displayMessage(transId + "|" + className + " : " + message + ":" + arguments[0]);
+ } else {
+ displayMessage(OnapLoggingUtils.formatMessage(message, arguments));
+ }
+ }
+
+ /**
* Records an error message.
*
* @param message the message
@@ -193,181 +200,177 @@ public class SystemOutLogger implements Logger, Serializable {
*/
@Override
public void error(MessageCodes msg, String... arguments) {
-
displayMessage(transId + "|" + className + " : " + "MessageCode:" + msg + Arrays.asList(arguments));
}
/**
- * Records a message.
+ * Records a error message.
*
* @param message the message
+ * @param arguments variable number of arguments
*/
@Override
- public void info(Object message) {
- displayMessage(transId + "|" + className + " : " + message);
+ public void error(String message, Object...arguments) {
+ if (arguments.length == 1 && OnapLoggingUtils.isThrowable(arguments[0])) {
+ displayMessage(transId + "|" + className + " : " + message + ":" + arguments[0]);
+ } else {
+ displayMessage(OnapLoggingUtils.formatMessage(message, arguments));
+ }
}
/**
* Records a message.
*
* @param message the message
- * @param throwable the throwable
*/
@Override
- public void info(Object message, Throwable throwable) {
- displayMessage(transId + "|" + className + " : " + message + ":" + throwable);
+ public void info(Object message) {
+ displayMessage(transId + "|" + className + " : " + message);
}
/**
* Records a message.
*
* @param message the message
+ * @param throwable the throwable
*/
@Override
- public void warn(Object message) {
- displayMessage(transId + "|" + className + " : " + message);
+ public void info(Object message, Throwable throwable) {
+ displayMessage(transId + "|" + className + " : " + message + ":" + throwable);
}
/**
* Records a message.
*
* @param message the message
- * @param throwable the throwable
+ * @param arguments variable number of arguments
*/
@Override
- public void warn(Object message, Throwable throwable) {
- displayMessage(transId + "|" + className + " : " + message + ":" + throwable);
+ public void info(String message, Object...arguments) {
+ if (arguments.length == 1 && OnapLoggingUtils.isThrowable(arguments[0])) {
+ displayMessage(transId + "|" + className + " : " + message + ":" + arguments[0]);
+ } else {
+ displayMessage(OnapLoggingUtils.formatMessage(message, arguments));
+ }
}
/**
* Records a message.
*
- * @param msg the message code
- * @param arguments the messages
+ * @param message the message
*/
@Override
- public void warn(MessageCodes msg, String... arguments) {
-
- displayMessage(transId + "|" + className + " : " + "MessageCodes:" + msg + Arrays.asList(arguments));
+ public void warn(Object message) {
+ displayMessage(transId + "|" + className + " : " + message);
}
/**
* Records a message.
*
* @param msg the message code
- * @param throwable the throwable
* @param arguments the messages
*/
@Override
- public void warn(MessageCodes msg, Throwable throwable, String... arguments) {
+ public void warn(MessageCodes msg, String... arguments) {
displayMessage(transId + "|" + className + " : " + "MessageCodes:" + msg + Arrays.asList(arguments));
-
}
/**
* Records a message.
*
* @param message the message
+ * @param throwable the throwable
*/
@Override
- public void trace(Object message) {
- displayMessage(transId + "|" + className + " : " + message);
+ public void warn(Object message, Throwable throwable) {
+ displayMessage(transId + "|" + className + " : " + message + ":" + throwable);
}
/**
* Records a message.
*
- * @param message the message
+ * @param msg the message code
* @param throwable the throwable
+ * @param arguments the messages
*/
@Override
- public void trace(Object message, Throwable throwable) {
- displayMessage(transId + "|" + className + " : " + message + ":" + throwable);
- }
+ public void warn(MessageCodes msg, Throwable throwable, String... arguments) {
- /**
- * Returns true for debug enabled, or false for not.
- *
- * @return boolean
- */
- @Override
- public boolean isDebugEnabled() {
- return isDebugEnabled;
- }
+ displayMessage(transId + "|" + className + " : " + "MessageCodes:" + msg + Arrays.asList(arguments));
- /**
- * Returns true for warn enabled, or false for not.
- *
- * @return boolean
- */
- @Override
- public boolean isWarnEnabled() {
- return isWarnEnabled;
}
/**
- * Returns true for info enabled, or false for not.
+ * Records a message.
*
- * @return boolean
+ * @param message the message
+ * @param arguments variable number of arguments
*/
@Override
- public boolean isInfoEnabled() {
- return isInfoEnabled;
+ public void warn(String message, Object...arguments) {
+ if (arguments.length == 1 && OnapLoggingUtils.isThrowable(arguments[0])) {
+ displayMessage(transId + "|" + className + " : " + message + ":" + arguments[0]);
+ } else {
+ displayMessage(OnapLoggingUtils.formatMessage(message, arguments));
+ }
}
/**
- * Returns true for error enabled, or false for not.
+ * Records a message.
*
- * @return boolean
+ * @param message the message
*/
@Override
- public boolean isErrorEnabled() {
- return isErrorEnabled;
+ public void trace(Object message) {
+ displayMessage(transId + "|" + className + " : " + message);
}
/**
- * Returns true for audit enabled, or false for not.
+ * Records a message.
*
- * @return boolean
+ * @param message the message
+ * @param throwable the throwable
*/
@Override
- public boolean isAuditEnabled() {
-
- return isAuditEnabled;
+ public void trace(Object message, Throwable throwable) {
+ displayMessage(transId + "|" + className + " : " + message + ":" + throwable);
}
/**
- * Returns true for metrics enabled, or false for not.
+ * Records an audit message.
*
- * @return boolean
+ * @param message the message
*/
@Override
- public boolean isMetricsEnabled() {
+ public void audit(Object message) {
- return isMetricsEnabled;
+ displayMessage(transId + "|" + className + " : " + message);
}
/**
* Records an audit message.
*
* @param message the message
+ * @param throwable the throwable
*/
@Override
- public void audit(Object message) {
-
- displayMessage(transId + "|" + className + " : " + message);
+ public void audit(Object message, Throwable throwable) {
+ displayMessage(transId + "|" + className + " : " + message + ":" + throwable);
}
/**
* Records an audit message.
*
* @param message the message
- * @param throwable the throwable
*/
@Override
- public void audit(Object message, Throwable throwable) {
- displayMessage(transId + "|" + className + " : " + message + ":" + throwable);
+ public void audit(String message, Object... arguments) {
+ if (arguments.length == 1) {
+ displayMessage(transId + "|" + className + " : " + message + ":" + arguments[0]);
+ } else {
+ displayMessage(OnapLoggingUtils.formatMessage(message, arguments));
+ }
}
/**
@@ -480,6 +483,21 @@ public class SystemOutLogger implements Logger, Serializable {
}
/**
+ * Records a metrics message.
+ *
+ * @param message the message
+ * @param arguments the arguments
+ */
+ @Override
+ public void metrics(String message, Object... arguments) {
+ if (arguments.length == 1) {
+ displayMessage(className + " : " + message + " : " + arguments[0]);
+ } else {
+ displayMessage(OnapLoggingUtils.formatMessage(message, arguments));
+ }
+ }
+
+ /**
* Returns transaction Id.
*
* @param transId the transaction ID
diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/nsa/LoggingContextFactory.java b/common-logging/src/main/java/org/onap/policy/common/logging/nsa/LoggingContextFactory.java
index ee64306f..eb2b318e 100644
--- a/common-logging/src/main/java/org/onap/policy/common/logging/nsa/LoggingContextFactory.java
+++ b/common-logging/src/main/java/org/onap/policy/common/logging/nsa/LoggingContextFactory.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019, 2021 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.
@@ -20,6 +20,8 @@
package org.onap.policy.common.logging.nsa;
+import lombok.AccessLevel;
+import lombok.NoArgsConstructor;
import org.onap.policy.common.logging.nsa.impl.SharedContext;
import org.onap.policy.common.logging.nsa.impl.Slf4jLoggingContext;
@@ -27,6 +29,7 @@ import org.onap.policy.common.logging.nsa.impl.Slf4jLoggingContext;
* A factory for setting up a LoggingContext.
*
*/
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class LoggingContextFactory {
public static class Builder {
@@ -47,8 +50,4 @@ public class LoggingContextFactory {
return forShared ? new SharedContext(baseContext) : new Slf4jLoggingContext(baseContext);
}
}
-
- private LoggingContextFactory() {
- // do nothing
- }
}
diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/nsa/impl/SharedContext.java b/common-logging/src/main/java/org/onap/policy/common/logging/nsa/impl/SharedContext.java
index e5f5e65b..13b38fc0 100644
--- a/common-logging/src/main/java/org/onap/policy/common/logging/nsa/impl/SharedContext.java
+++ b/common-logging/src/main/java/org/onap/policy/common/logging/nsa/impl/SharedContext.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2018, 2020 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.
@@ -22,7 +22,6 @@ package org.onap.policy.common.logging.nsa.impl;
import java.util.HashMap;
import java.util.Map.Entry;
-
import org.onap.policy.common.logging.nsa.LoggingContext;
import org.onap.policy.common.logging.nsa.SharedLoggingContext;
diff --git a/common-logging/src/main/resources/org/onap/policy/common/logging/eelf/Resources.properties b/common-logging/src/main/resources/org/onap/policy/common/logging/eelf/Resources.properties
index 4f2c3f6d..0f9d0f8c 100644
--- a/common-logging/src/main/resources/org/onap/policy/common/logging/eelf/Resources.properties
+++ b/common-logging/src/main/resources/org/onap/policy/common/logging/eelf/Resources.properties
@@ -3,6 +3,7 @@
# ONAP-Logging
# ================================================================================
# Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+# Modifications Copyright (C) 2024 Nordix Foundation.
# ================================================================================
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -111,24 +112,6 @@ RULE_METRICS_INFO=\
No resolution needed|\
Generate information for Metric events
-UEB_AUDIT_EXEC_INFO=\
- POLICY-511I|\
- Service Name: {0}:Executing UEB: {1}|\
- No resolution needed|\
- Executing method
-
-UEB_AUDIT_BEGIN_INFO=\
- POLICY-512I|\
- Service Name: {0}:Entering UEB: {1}|\
- No resolution needed|\
- Entering method
-
-UEB_AUDIT_END_INFO=\
- POLICY-513I|\
- Service Name: {0}:Exiting UEB: {1}|\
- No resolution needed|\
- Exiting method
-
RULE_AUDIT_START_END_INFO=\
diff --git a/common-logging/src/test/java/org/onap/policy/common/logging/eelf/ErrorCodeMapTest.java b/common-logging/src/test/java/org/onap/policy/common/logging/eelf/ErrorCodeMapTest.java
index 781be600..c34d9696 100644
--- a/common-logging/src/test/java/org/onap/policy/common/logging/eelf/ErrorCodeMapTest.java
+++ b/common-logging/src/test/java/org/onap/policy/common/logging/eelf/ErrorCodeMapTest.java
@@ -3,13 +3,14 @@
* ONAP-Logging
* ================================================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 AT&T.
* ================================================================================
* 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.
@@ -47,7 +48,7 @@ public class ErrorCodeMapTest {
@Test
public void testErrorCodeInfoGetErrorCode() {
ErrorCodeInfo errorCodeInfo = ErrorCodeMap.getErrorCodeInfo(MessageCodes.EXCEPTION_ERROR);
- assertEquals("POLICY-503E", errorCodeInfo.getErrorCode());
+ assertEquals("500", errorCodeInfo.getErrorCode());
}
@Test
diff --git a/common-logging/src/test/java/org/onap/policy/common/logging/eelf/EventDataTest.java b/common-logging/src/test/java/org/onap/policy/common/logging/eelf/EventDataTest.java
index 6fe81d27..882cc2cf 100644
--- a/common-logging/src/test/java/org/onap/policy/common/logging/eelf/EventDataTest.java
+++ b/common-logging/src/test/java/org/onap/policy/common/logging/eelf/EventDataTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine - Common Modules
* ================================================================================
- * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2020 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.
@@ -21,13 +21,10 @@
package org.onap.policy.common.logging.eelf;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
import java.time.Instant;
-
import org.junit.Test;
public class EventDataTest {
@@ -142,32 +139,33 @@ public class EventDataTest {
final EventData d3 = new EventData("abc", iend, istart);
// same object
- assertTrue(d1.equals(d1));
+ assertEquals(d1, d1);
// compare with null
- assertFalse(d1.equals(null));
+ assertNotEquals(d1, null);
// compare with request id
- assertTrue(d1.equals("abc"));
- assertFalse(d1.equals("abd"));
+ // note: ignoring sonar because we want to test d1.equals(), not "abc".equals()
+ assertEquals(d1, "abc"); // NOSONAR
+ assertNotEquals(d1, "abd");
// compare with int - different class type
- assertFalse(d1.equals(10));
+ assertNotEquals(d1, 10);
// "this" has null request id
- assertFalse(new EventData().equals(d1));
+ assertNotEquals(new EventData(), d1);
// both null
- assertTrue(new EventData().equals(new EventData()));
+ assertEquals(new EventData(), new EventData());
// this request id is not null, other is null
- assertFalse(d1.equals(new EventData()));
+ assertNotEquals(d1, new EventData());
// neither null, same
- assertTrue(d1.equals(d3));
+ assertEquals(d1, d3);
// neither null, diff
- assertFalse(d1.equals(d2));
+ assertNotEquals(d1, d2);
}
}
diff --git a/common-logging/src/test/java/org/onap/policy/common/logging/eelf/EventTrackInfoHandlerTest.java b/common-logging/src/test/java/org/onap/policy/common/logging/eelf/EventTrackInfoHandlerTest.java
index d1d5983d..2cc1e59e 100644
--- a/common-logging/src/test/java/org/onap/policy/common/logging/eelf/EventTrackInfoHandlerTest.java
+++ b/common-logging/src/test/java/org/onap/policy/common/logging/eelf/EventTrackInfoHandlerTest.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine - Common Modules
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018, 2020 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.
@@ -24,7 +24,6 @@ import static org.junit.Assert.assertEquals;
import java.time.Instant;
import java.util.concurrent.ConcurrentMap;
-
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
diff --git a/common-logging/src/test/java/org/onap/policy/common/logging/eelf/EventTrackInfoTest.java b/common-logging/src/test/java/org/onap/policy/common/logging/eelf/EventTrackInfoTest.java
index e6024682..0ca5feb5 100644
--- a/common-logging/src/test/java/org/onap/policy/common/logging/eelf/EventTrackInfoTest.java
+++ b/common-logging/src/test/java/org/onap/policy/common/logging/eelf/EventTrackInfoTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine - Common Modules
* ================================================================================
- * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2020 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.
@@ -23,10 +23,10 @@ package org.onap.policy.common.logging.eelf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import java.time.Instant;
-
import org.junit.Before;
import org.junit.Test;
@@ -62,8 +62,8 @@ public class EventTrackInfoTest {
info.storeEventData(data1);
info.storeEventData(data2);
- assertTrue(data1 == info.getEventDataByRequestId("abc"));
- assertTrue(data2 == info.getEventDataByRequestId("def"));
+ assertSame(data1, info.getEventDataByRequestId("abc"));
+ assertSame(data2, info.getEventDataByRequestId("def"));
assertNull(info.getEventDataByRequestId("hello"));
}
@@ -86,14 +86,14 @@ public class EventTrackInfoTest {
assertEquals(2, info.getEventInfo().size());
// look-up by request id
- assertTrue(data1 == info.getEventDataByRequestId("abc"));
- assertTrue(data2 == info.getEventDataByRequestId("def"));
+ assertSame(data1, info.getEventDataByRequestId("abc"));
+ assertSame(data2, info.getEventDataByRequestId("def"));
// doesn't replace existing value
info.storeEventData(new EventData("abc", iend, istart));
assertEquals(2, info.getEventInfo().size());
- assertTrue(data1 == info.getEventDataByRequestId("abc"));
- assertTrue(data2 == info.getEventDataByRequestId("def"));
+ assertSame(data1, info.getEventDataByRequestId("abc"));
+ assertSame(data2, info.getEventDataByRequestId("def"));
}
/**
@@ -111,7 +111,7 @@ public class EventTrackInfoTest {
// look-up by request id
assertNull(info.getEventDataByRequestId("abc"));
- assertTrue(data2 == info.getEventDataByRequestId("def"));
+ assertSame(data2, info.getEventDataByRequestId("def"));
}
/**
@@ -123,8 +123,8 @@ public class EventTrackInfoTest {
info.storeEventData(data2);
assertEquals(2, info.getEventInfo().size());
- assertTrue(data1 == info.getEventInfo().get("abc"));
- assertTrue(data2 == info.getEventInfo().get("def"));
+ assertSame(data1, info.getEventInfo().get("abc"));
+ assertSame(data2, info.getEventInfo().get("def"));
}
}
diff --git a/common-logging/src/test/java/org/onap/policy/common/logging/eelf/PolicyLoggerTest.java b/common-logging/src/test/java/org/onap/policy/common/logging/eelf/PolicyLoggerTest.java
index 6af3632a..62fcfaf4 100644
--- a/common-logging/src/test/java/org/onap/policy/common/logging/eelf/PolicyLoggerTest.java
+++ b/common-logging/src/test/java/org/onap/policy/common/logging/eelf/PolicyLoggerTest.java
@@ -3,7 +3,8 @@
* ONAP-Logging
* ================================================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2023 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -30,11 +31,13 @@ import static com.att.eelf.configuration.Configuration.MDC_SERVER_FQDN;
import static com.att.eelf.configuration.Configuration.MDC_SERVER_IP_ADDRESS;
import static com.att.eelf.configuration.Configuration.MDC_SERVICE_INSTANCE_ID;
import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME;
+import static org.assertj.core.api.Assertions.assertThatCode;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.never;
import static org.onap.policy.common.logging.eelf.OnapConfigProperties.PARTNER_NAME;
import static org.onap.policy.common.logging.eelf.OnapConfigProperties.RESPONSE_CODE;
import static org.onap.policy.common.logging.eelf.OnapConfigProperties.RESPONSE_DESCRIPTION;
@@ -43,16 +46,14 @@ import static org.onap.policy.common.logging.eelf.OnapConfigProperties.STATUS_CO
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFLogger.Level;
-
import java.time.Instant;
import java.util.Properties;
import java.util.UUID;
-
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
-import org.powermock.reflect.Whitebox;
import org.slf4j.MDC;
+import org.springframework.test.util.ReflectionTestUtils;
public class PolicyLoggerTest {
@@ -189,7 +190,7 @@ public class PolicyLoggerTest {
@Test
public void testInfoMessageCodesStringStringArray() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
PolicyLogger.info(MessageCodes.ERROR_DATA_ISSUE, "str1", "str2");
Mockito.verify(mockLogger).info(MessageCodes.ERROR_DATA_ISSUE, "str2");
}
@@ -197,7 +198,10 @@ public class PolicyLoggerTest {
@Test
public void testInfoStringString() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
+ PolicyLogger.info("str1", "str2");
+ Mockito.verify(mockLogger, never()).info(Mockito.anyString(), Mockito.anyString());
+ Mockito.when(mockLogger.isInfoEnabled()).thenReturn(true);
PolicyLogger.info("str1", "str2");
Mockito.verify(mockLogger).info(MessageCodes.GENERAL_INFO, "str2");
}
@@ -205,7 +209,7 @@ public class PolicyLoggerTest {
@Test
public void testInfoObject() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
PolicyLogger.info("str1");
Mockito.verify(mockLogger).info(MessageCodes.GENERAL_INFO, "str1");
}
@@ -213,7 +217,7 @@ public class PolicyLoggerTest {
@Test
public void testInfoMessageCodesThrowableStringArray() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
PolicyLogger.info(MessageCodes.ERROR_DATA_ISSUE, new NullPointerException(), "str1", "str2");
Mockito.verify(mockLogger).info((MessageCodes) Mockito.any(),
Mockito.startsWith("str1:str2:java.lang.NullPointerException"));
@@ -222,7 +226,7 @@ public class PolicyLoggerTest {
@Test
public void testInfoMessageCodesStringThrowableStringArray() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
PolicyLogger.info(MessageCodes.ERROR_DATA_ISSUE, "PolicyLoggerTest", new NullPointerException(), "str1",
"str2");
Mockito.verify(mockLogger).info((MessageCodes) Mockito.any(),
@@ -232,7 +236,7 @@ public class PolicyLoggerTest {
@Test
public void testWarnMessageCodesStringStringArray() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
PolicyLogger.warn(MessageCodes.ERROR_DATA_ISSUE, "str1");
Mockito.verify(mockLogger).warn(MessageCodes.ERROR_DATA_ISSUE);
}
@@ -240,7 +244,10 @@ public class PolicyLoggerTest {
@Test
public void testWarnStringString() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
+ PolicyLogger.warn("str1", "str2");
+ Mockito.verify(mockLogger, never()).info(Mockito.anyString(), Mockito.anyString());
+ Mockito.when(mockLogger.isWarnEnabled()).thenReturn(true);
PolicyLogger.warn("str1", "str2");
Mockito.verify(mockLogger).warn(MessageCodes.GENERAL_INFO, "str2");
}
@@ -248,7 +255,7 @@ public class PolicyLoggerTest {
@Test
public void testWarnObject() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
PolicyLogger.warn(1);
Mockito.verify(mockLogger).warn(MessageCodes.GENERAL_WARNING, "1");
}
@@ -256,7 +263,7 @@ public class PolicyLoggerTest {
@Test
public void testWarnMessageCodesThrowableStringArray() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
PolicyLogger.warn(MessageCodes.ERROR_DATA_ISSUE, new NullPointerException(), "str1", "str2");
Mockito.verify(mockLogger).warn((MessageCodes) Mockito.any(),
Mockito.startsWith("str1:str2:java.lang.NullPointerException"));
@@ -265,7 +272,7 @@ public class PolicyLoggerTest {
@Test
public void testWarnMessageCodesStringThrowableStringArray() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
PolicyLogger.warn(MessageCodes.ERROR_DATA_ISSUE, "PolicyLoggerTest", new NullPointerException(), "str1",
"str2");
Mockito.verify(mockLogger).warn((MessageCodes) Mockito.any(),
@@ -275,7 +282,7 @@ public class PolicyLoggerTest {
@Test
public void testWarnString() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
PolicyLogger.warn("str1");
Mockito.verify(mockLogger).warn(MessageCodes.GENERAL_WARNING, "str1");
}
@@ -283,10 +290,13 @@ public class PolicyLoggerTest {
@Test
public void testErrorStringString() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "errorLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "errorLogger", mockLogger);
+ PolicyLogger.error("str1", "str2");
+ Mockito.verify(mockLogger, never()).info(Mockito.anyString(), Mockito.anyString());
+ Mockito.when(mockLogger.isErrorEnabled()).thenReturn(true);
PolicyLogger.error("str1", "str2");
Mockito.verify(mockLogger).error(MessageCodes.GENERAL_ERROR, "str2");
- assertEquals("POLICY-515E", MDC.get("ErrorCode"));
+ assertEquals("500", MDC.get("ErrorCode"));
assertEquals("This is a general error message during the process. Please check the error message for detail "
+ "information", MDC.get("ErrorDescription"));
}
@@ -294,11 +304,11 @@ public class PolicyLoggerTest {
@Test
public void testErrorString() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "errorLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "errorLogger", mockLogger);
PolicyLogger.error("str1");
Mockito.verify(mockLogger).error(MessageCodes.GENERAL_ERROR, "str1");
assertEquals("ERROR", MDC.get("ErrorCategory"));
- assertEquals("POLICY-515E", MDC.get("ErrorCode"));
+ assertEquals("500", MDC.get("ErrorCode"));
assertEquals("This is a general error message during the process. Please check the error message for detail "
+ "information", MDC.get("ErrorDescription"));
}
@@ -306,11 +316,11 @@ public class PolicyLoggerTest {
@Test
public void testErrorObject() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "errorLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "errorLogger", mockLogger);
PolicyLogger.error(1);
Mockito.verify(mockLogger).error(MessageCodes.GENERAL_ERROR, "1");
assertEquals("ERROR", MDC.get("ErrorCategory"));
- assertEquals("POLICY-515E", MDC.get("ErrorCode"));
+ assertEquals("500", MDC.get("ErrorCode"));
assertEquals("This is a general error message during the process. Please check the error message for detail "
+ "information", MDC.get("ErrorDescription"));
}
@@ -318,7 +328,7 @@ public class PolicyLoggerTest {
@Test
public void testErrorMessageCodesThrowableStringArray() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "errorLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "errorLogger", mockLogger);
PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, new NullPointerException(), "str1", "str2");
Mockito.verify(mockLogger).error((MessageCodes) Mockito.any(),
Mockito.startsWith("str1:str2:java.lang.NullPointerException"));
@@ -327,7 +337,7 @@ public class PolicyLoggerTest {
@Test
public void testErrorMessageCodesStringThrowableStringArray() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "errorLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "errorLogger", mockLogger);
PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "PolicyLoggerTest", new NullPointerException(), "str1",
"str2");
Mockito.verify(mockLogger).error((MessageCodes) Mockito.any(),
@@ -337,7 +347,7 @@ public class PolicyLoggerTest {
@Test
public void testErrorMessageCodesStringArray() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "errorLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "errorLogger", mockLogger);
PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "str1", "str2");
Mockito.verify(mockLogger).error(MessageCodes.ERROR_DATA_ISSUE, "str1", "str2");
}
@@ -345,7 +355,7 @@ public class PolicyLoggerTest {
@Test
public void testDebugMessageCodesStringArray() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
PolicyLogger.debug(MessageCodes.ERROR_DATA_ISSUE, "str1", "str2");
Mockito.verify(mockLogger).debug(MessageCodes.ERROR_DATA_ISSUE, "str1", "str2");
}
@@ -353,7 +363,10 @@ public class PolicyLoggerTest {
@Test
public void testDebugStringString() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
+ PolicyLogger.debug("str1", "str2");
+ Mockito.verify(mockLogger, never()).info(Mockito.anyString(), Mockito.anyString());
+ Mockito.when(mockLogger.isDebugEnabled()).thenReturn(true);
PolicyLogger.debug("str1", "str2");
Mockito.verify(mockLogger).debug(MessageCodes.GENERAL_INFO, "str2");
}
@@ -361,7 +374,7 @@ public class PolicyLoggerTest {
@Test
public void testDebugString() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
PolicyLogger.debug("str1");
Mockito.verify(mockLogger).debug("str1");
}
@@ -369,35 +382,38 @@ public class PolicyLoggerTest {
@Test
public void testDebugObject() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
PolicyLogger.debug(1);
- Mockito.verify(mockLogger).debug("1");
+ Mockito.verify(mockLogger).debug("{}", 1);
}
@Test
public void testAuditStringObject() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "auditLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "auditLogger", mockLogger);
+ PolicyLogger.audit("PolicyLoggerTest", 1);
+ Mockito.verify(mockLogger, never()).info(Mockito.anyString(), Mockito.anyString());
+ Mockito.when(mockLogger.isInfoEnabled()).thenReturn(true);
PolicyLogger.audit("PolicyLoggerTest", 1);
assertEquals("PolicyLoggerTest", MDC.get("ClassName"));
assertEquals("COMPLETE", MDC.get("StatusCode"));
- Mockito.verify(mockLogger).info("1");
+ Mockito.verify(mockLogger).info("{}", "1");
}
@Test
public void testAuditObject() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "auditLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "auditLogger", mockLogger);
PolicyLogger.audit(1);
assertEquals("", MDC.get("ClassName"));
assertEquals("COMPLETE", MDC.get("StatusCode"));
- Mockito.verify(mockLogger).info("1");
+ Mockito.verify(mockLogger).info("{}", 1);
}
@Test
public void testDebugMessageCodesThrowableStringArray() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
PolicyLogger.debug(MessageCodes.ERROR_DATA_ISSUE, new NullPointerException(), "str1", "str2");
Mockito.verify(mockLogger).debug((MessageCodes) Mockito.any(),
Mockito.startsWith("str1:str2:java.lang.NullPointerException"));
@@ -406,7 +422,7 @@ public class PolicyLoggerTest {
@Test
public void testDebugMessageCodesStringThrowableStringArray() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
PolicyLogger.debug(MessageCodes.ERROR_DATA_ISSUE, "PolicyLoggerTest", new NullPointerException(), "str1",
"str2");
Mockito.verify(mockLogger).debug((MessageCodes) Mockito.any(),
@@ -416,7 +432,7 @@ public class PolicyLoggerTest {
@Test
public void testIsDebugEnabled() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
Mockito.when(mockLogger.isDebugEnabled()).thenReturn(false).thenReturn(true);
assertFalse(PolicyLogger.isDebugEnabled());
assertTrue(PolicyLogger.isDebugEnabled());
@@ -425,7 +441,7 @@ public class PolicyLoggerTest {
@Test
public void testIsErrorEnabled() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "errorLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "errorLogger", mockLogger);
Mockito.when(mockLogger.isErrorEnabled()).thenReturn(false).thenReturn(true);
assertFalse(PolicyLogger.isErrorEnabled());
assertTrue(PolicyLogger.isErrorEnabled());
@@ -434,7 +450,7 @@ public class PolicyLoggerTest {
@Test
public void testIsWarnEnabled() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
Mockito.when(mockLogger.isWarnEnabled()).thenReturn(false).thenReturn(true);
assertFalse(PolicyLogger.isWarnEnabled());
assertTrue(PolicyLogger.isWarnEnabled());
@@ -443,7 +459,7 @@ public class PolicyLoggerTest {
@Test
public void testIsInfoEnabled1() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
Mockito.when(mockLogger.isInfoEnabled()).thenReturn(false).thenReturn(true);
assertFalse(PolicyLogger.isInfoEnabled1());
assertTrue(PolicyLogger.isInfoEnabled1());
@@ -452,7 +468,7 @@ public class PolicyLoggerTest {
@Test
public void testIsAuditEnabled() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
Mockito.when(mockLogger.isInfoEnabled()).thenReturn(false).thenReturn(true);
assertFalse(PolicyLogger.isAuditEnabled());
assertTrue(PolicyLogger.isAuditEnabled());
@@ -461,7 +477,7 @@ public class PolicyLoggerTest {
@Test
public void testIsInfoEnabled() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
Mockito.when(mockLogger.isInfoEnabled()).thenReturn(false).thenReturn(true);
assertFalse(PolicyLogger.isInfoEnabled());
assertTrue(PolicyLogger.isInfoEnabled());
@@ -470,7 +486,7 @@ public class PolicyLoggerTest {
@Test
public void testTraceStringString() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
PolicyLogger.trace("str1", "str2");
Mockito.verify(mockLogger).trace(MessageCodes.GENERAL_INFO, "str2");
}
@@ -478,9 +494,9 @@ public class PolicyLoggerTest {
@Test
public void testTraceObject() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
PolicyLogger.trace(1);
- Mockito.verify(mockLogger).trace("1");
+ Mockito.verify(mockLogger).trace("{}", 1);
}
@Test
@@ -570,7 +586,7 @@ public class PolicyLoggerTest {
@Test
public void testRecordMetricEventString() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "metricsLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "metricsLogger", mockLogger);
PolicyLogger.recordMetricEvent("eventId");
Mockito.verify(mockLogger).info(Mockito.eq(MessageCodes.RULE_METRICS_INFO), Mockito.anyString(),
Mockito.eq("eventId"));
@@ -579,7 +595,7 @@ public class PolicyLoggerTest {
@Test
public void testMetricsString() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "metricsLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "metricsLogger", mockLogger);
PolicyLogger.metrics("str1");
Mockito.verify(mockLogger).info(Mockito.eq(MessageCodes.RULE_METRICS_INFO), Mockito.anyString(),
Mockito.eq("str1"));
@@ -588,7 +604,10 @@ public class PolicyLoggerTest {
@Test
public void testMetricsStringObject() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "metricsLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "metricsLogger", mockLogger);
+ PolicyLogger.metrics("PolicyLoggerTest", 1);
+ Mockito.verify(mockLogger, never()).info(Mockito.anyString(), Mockito.anyString());
+ Mockito.when(mockLogger.isInfoEnabled()).thenReturn(true);
PolicyLogger.metrics("PolicyLoggerTest", 1);
Mockito.verify(mockLogger).info(Mockito.eq(MessageCodes.RULE_METRICS_INFO), Mockito.anyString(),
Mockito.eq("1"));
@@ -597,7 +616,7 @@ public class PolicyLoggerTest {
@Test
public void testMetricsObject() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "metricsLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "metricsLogger", mockLogger);
PolicyLogger.metrics(1);
Mockito.verify(mockLogger).info(Mockito.eq(MessageCodes.RULE_METRICS_INFO), Mockito.anyString(),
Mockito.eq("1"));
@@ -606,14 +625,14 @@ public class PolicyLoggerTest {
@Test
public void testMetricsPrintln() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "metricsLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "metricsLogger", mockLogger);
PolicyLogger.metricsPrintln("str1");
Mockito.verify(mockLogger).info("str1");
}
@Test
public void testInitNullProperties() {
- PolicyLogger.init(null);
+ assertThatCode(() -> PolicyLogger.init(null)).doesNotThrowAnyException();
}
@Test
@@ -630,7 +649,7 @@ public class PolicyLoggerTest {
properties.setProperty("stop.check.point", "0");
properties.setProperty("logger.property", "LOG4J");
- PolicyLogger.init(properties);
+ assertThatCode(() -> PolicyLogger.init(properties)).doesNotThrowAnyException();
}
@Test
diff --git a/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/EelfLoggerTest.java b/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/EelfLoggerTest.java
index d3c09ee6..1d77451b 100644
--- a/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/EelfLoggerTest.java
+++ b/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/EelfLoggerTest.java
@@ -3,7 +3,8 @@
* ONAP-Logging
* ================================================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2023 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -27,6 +28,7 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.never;
import com.att.eelf.configuration.EELFLogger;
import java.util.UUID;
@@ -34,8 +36,8 @@ import org.junit.Test;
import org.mockito.Mockito;
import org.onap.policy.common.logging.eelf.MessageCodes;
import org.onap.policy.common.logging.eelf.PolicyLogger;
-import org.powermock.reflect.Whitebox;
import org.slf4j.MDC;
+import org.springframework.test.util.ReflectionTestUtils;
public class EelfLoggerTest {
@@ -91,7 +93,10 @@ public class EelfLoggerTest {
@Test
public void testDebugObject() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
+ eelfLogger.debug("message");
+ Mockito.verify(mockLogger, never()).info(Mockito.anyString(), Mockito.anyString());
+ Mockito.when(mockLogger.isDebugEnabled()).thenReturn(true);
eelfLogger.debug("message");
Mockito.verify(mockLogger).debug(MessageCodes.GENERAL_INFO, "message");
}
@@ -99,7 +104,10 @@ public class EelfLoggerTest {
@Test
public void testErrorObject() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "errorLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "errorLogger", mockLogger);
+ eelfLogger.error("message");
+ Mockito.verify(mockLogger, never()).info(Mockito.anyString(), Mockito.anyString());
+ Mockito.when(mockLogger.isErrorEnabled()).thenReturn(true);
eelfLogger.error("message");
Mockito.verify(mockLogger).error(MessageCodes.GENERAL_ERROR, "message");
}
@@ -107,7 +115,10 @@ public class EelfLoggerTest {
@Test
public void testInfoObject() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
+ eelfLogger.info("message");
+ Mockito.verify(mockLogger, never()).info(Mockito.anyString(), Mockito.anyString());
+ Mockito.when(mockLogger.isInfoEnabled()).thenReturn(true);
eelfLogger.info("message");
Mockito.verify(mockLogger).info(MessageCodes.GENERAL_INFO, "message");
}
@@ -115,7 +126,10 @@ public class EelfLoggerTest {
@Test
public void testWarnObject() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
+ eelfLogger.warn("message");
+ Mockito.verify(mockLogger, never()).info(Mockito.anyString(), Mockito.anyString());
+ Mockito.when(mockLogger.isWarnEnabled()).thenReturn(true);
eelfLogger.warn("message");
Mockito.verify(mockLogger).warn(MessageCodes.GENERAL_INFO, "message");
}
@@ -123,7 +137,7 @@ public class EelfLoggerTest {
@Test
public void testTraceObject() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
eelfLogger.trace("message");
Mockito.verify(mockLogger).trace(MessageCodes.GENERAL_INFO, "message");
}
@@ -131,7 +145,7 @@ public class EelfLoggerTest {
@Test
public void testIsDebugEnabled() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
Mockito.when(mockLogger.isDebugEnabled()).thenReturn(false).thenReturn(true);
assertFalse(eelfLogger.isDebugEnabled());
assertTrue(eelfLogger.isDebugEnabled());
@@ -141,7 +155,7 @@ public class EelfLoggerTest {
@Test
public void testIsInfoEnabled() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
Mockito.when(mockLogger.isInfoEnabled()).thenReturn(false).thenReturn(true);
assertFalse(eelfLogger.isInfoEnabled());
assertTrue(eelfLogger.isInfoEnabled());
@@ -150,7 +164,7 @@ public class EelfLoggerTest {
@Test
public void testIsWarnEnabled() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
Mockito.when(mockLogger.isWarnEnabled()).thenReturn(false).thenReturn(true);
assertFalse(eelfLogger.isWarnEnabled());
assertTrue(eelfLogger.isWarnEnabled());
@@ -159,7 +173,7 @@ public class EelfLoggerTest {
@Test
public void testIsErrorEnabled() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "errorLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "errorLogger", mockLogger);
Mockito.when(mockLogger.isErrorEnabled()).thenReturn(false).thenReturn(true);
assertFalse(eelfLogger.isErrorEnabled());
assertTrue(eelfLogger.isErrorEnabled());
@@ -182,7 +196,7 @@ public class EelfLoggerTest {
@Test
public void testIsTraceEnabled() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
Mockito.when(mockLogger.isDebugEnabled()).thenReturn(false).thenReturn(true);
assertFalse(eelfLogger.isTraceEnabled());
assertTrue(eelfLogger.isTraceEnabled());
@@ -198,7 +212,7 @@ public class EelfLoggerTest {
@Test
public void testDebugObjectThrowable() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
eelfLogger.debug("message", new NullPointerException());
Mockito.verify(mockLogger).debug((MessageCodes) Mockito.any(),
Mockito.startsWith("message:java.lang.NullPointerException"));
@@ -207,7 +221,7 @@ public class EelfLoggerTest {
@Test
public void testErrorObjectThrowable() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "errorLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "errorLogger", mockLogger);
eelfLogger.error("message", new NullPointerException());
Mockito.verify(mockLogger).error((MessageCodes) Mockito.any(),
Mockito.startsWith("message:java.lang.NullPointerException"));
@@ -217,8 +231,10 @@ public class EelfLoggerTest {
@Test
public void testInfoObjectThrowable() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
eelfLogger.info("message", new NullPointerException());
+ Mockito.verify(mockLogger, never()).info(Mockito.anyString(), Mockito.anyString());
+ Mockito.when(mockLogger.isInfoEnabled()).thenReturn(true);
Mockito.verify(mockLogger).info((MessageCodes) Mockito.any(),
Mockito.startsWith("message:java.lang.NullPointerException"));
}
@@ -226,7 +242,7 @@ public class EelfLoggerTest {
@Test
public void testWarnObjectThrowable() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
eelfLogger.warn("message", new NullPointerException());
Mockito.verify(mockLogger).warn((MessageCodes) Mockito.any(),
Mockito.startsWith("message:java.lang.NullPointerException"));
@@ -235,17 +251,17 @@ public class EelfLoggerTest {
@Test
public void testTraceObjectThrowable() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
eelfLogger.trace("message", new NullPointerException());
- Mockito.verify(mockLogger).trace("message");
+ Mockito.verify(mockLogger).trace("{}", "message");
}
@Test
public void testAuditObjectThrowable() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "auditLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "auditLogger", mockLogger);
eelfLogger.audit("message", new NullPointerException());
- Mockito.verify(mockLogger).info("message");
+ Mockito.verify(mockLogger).info("{}", "message");
}
@Test
@@ -315,7 +331,10 @@ public class EelfLoggerTest {
@Test
public void testMetrics() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "metricsLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "metricsLogger", mockLogger);
+ eelfLogger.metrics(1);
+ Mockito.verify(mockLogger, never()).info(Mockito.anyString(), Mockito.anyString());
+ Mockito.when(mockLogger.isInfoEnabled()).thenReturn(true);
eelfLogger.metrics(1);
Mockito.verify(mockLogger).info(Mockito.eq(MessageCodes.RULE_METRICS_INFO), Mockito.anyString(),
Mockito.eq("1"));
@@ -324,7 +343,7 @@ public class EelfLoggerTest {
@Test
public void testErrorMessageCodesThrowableStringArray() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "errorLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "errorLogger", mockLogger);
eelfLogger.error(MessageCodes.GENERAL_ERROR, new NullPointerException(), "str1", "str2");
Mockito.verify(mockLogger).error((MessageCodes) Mockito.any(),
Mockito.startsWith("str1:str2:java.lang.NullPointerException"));
@@ -333,7 +352,7 @@ public class EelfLoggerTest {
@Test
public void testErrorMessageCodesStringArray() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "errorLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "errorLogger", mockLogger);
eelfLogger.error(MessageCodes.GENERAL_ERROR, "str1", "str2");
Mockito.verify(mockLogger).error(MessageCodes.GENERAL_ERROR, "str1", "str2");
@@ -348,7 +367,7 @@ public class EelfLoggerTest {
@Test
public void testWarnMessageCodesStringArray() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
eelfLogger.warn(MessageCodes.GENERAL_ERROR, "str1", "str2");
Mockito.verify(mockLogger).warn(MessageCodes.GENERAL_ERROR, "str1", "str2");
}
@@ -356,7 +375,7 @@ public class EelfLoggerTest {
@Test
public void testWarnMessageCodesThrowableStringArray() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
+ ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
eelfLogger.warn(MessageCodes.GENERAL_ERROR, new NullPointerException(), "str1", "str2");
Mockito.verify(mockLogger).warn((MessageCodes) Mockito.any(),
Mockito.startsWith("str1:str2:java.lang.NullPointerException"));
diff --git a/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/FlexLoggerTest.java b/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/FlexLoggerTest.java
index a74dd94d..c0194f2b 100644
--- a/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/FlexLoggerTest.java
+++ b/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/FlexLoggerTest.java
@@ -3,7 +3,8 @@
* ONAP-Logging
* ================================================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2023 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,6 +22,7 @@
package org.onap.policy.common.logging.flexlogger;
+import static org.assertj.core.api.Assertions.assertThatCode;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertSame;
@@ -29,93 +31,65 @@ import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
import org.onap.policy.common.logging.flexlogger.FlexLogger.PropertiesCallBack;
-import org.powermock.reflect.Whitebox;
+import org.springframework.test.util.ReflectionTestUtils;
public class FlexLoggerTest {
@Test
public void testGetLoggerClassOfQEelf() {
- Whitebox.setInternalState(FlexLogger.class, "loggerType", LoggerType.EELF);
+ ReflectionTestUtils.setField(FlexLogger.class, "loggerType", LoggerType.EELF);
Logger logger = FlexLogger.getLogger((Class<?>) null);
assertSame(logger, FlexLogger.getLogger((Class<?>) null));
assertNotEquals(logger, FlexLogger.getLogger(String.class));
}
@Test
- public void testGetLoggerClassOfQLog4j() {
- Whitebox.setInternalState(FlexLogger.class, "loggerType", LoggerType.LOG4J);
- Logger logger = FlexLogger.getLogger(this.getClass());
- assertSame(logger, FlexLogger.getLogger(this.getClass()));
- }
-
- @Test
public void testGetLoggerClassOfQSystemOut() {
- Whitebox.setInternalState(FlexLogger.class, "loggerType", LoggerType.SYSTEMOUT);
+ ReflectionTestUtils.setField(FlexLogger.class, "loggerType", LoggerType.SYSTEMOUT);
Logger logger = FlexLogger.getLogger(this.getClass());
assertSame(logger, FlexLogger.getLogger(this.getClass()));
}
@Test
public void testGetLoggerStringEelf() {
- Whitebox.setInternalState(FlexLogger.class, "loggerType", LoggerType.EELF);
- Logger logger = FlexLogger.getLogger("str1");
- assertSame(logger, FlexLogger.getLogger("str1"));
- }
-
- @Test
- public void testGetLoggerStringLog4j() {
- Whitebox.setInternalState(FlexLogger.class, "loggerType", LoggerType.LOG4J);
- Logger logger = FlexLogger.getLogger("str1");
- assertSame(logger, FlexLogger.getLogger("str1"));
+ ReflectionTestUtils.setField(FlexLogger.class, "loggerType", LoggerType.EELF);
+ Logger logger = FlexLogger.getLogger();
+ assertSame(logger, FlexLogger.getLogger());
}
@Test
public void testGetLoggerStringSystemOut() {
- Whitebox.setInternalState(FlexLogger.class, "loggerType", LoggerType.SYSTEMOUT);
- Logger logger = FlexLogger.getLogger("str1");
- assertSame(logger, FlexLogger.getLogger("str1"));
+ ReflectionTestUtils.setField(FlexLogger.class, "loggerType", LoggerType.SYSTEMOUT);
+ Logger logger = FlexLogger.getLogger();
+ assertSame(logger, FlexLogger.getLogger());
}
@Test
public void testGetLoggerClassOfQBooleanEelf() {
- Whitebox.setInternalState(FlexLogger.class, "loggerType", LoggerType.EELF);
- Logger logger = FlexLogger.getLogger(this.getClass(), true);
- assertSame(logger, FlexLogger.getLogger(this.getClass(), true));
- }
-
- @Test
- public void testGetLoggerClassOfQBooleanLog4j() {
- Whitebox.setInternalState(FlexLogger.class, "loggerType", LoggerType.LOG4J);
+ ReflectionTestUtils.setField(FlexLogger.class, "loggerType", LoggerType.EELF);
Logger logger = FlexLogger.getLogger(this.getClass(), true);
assertSame(logger, FlexLogger.getLogger(this.getClass(), true));
}
@Test
public void testGetLoggerClassOfQBooleanSystemOut() {
- Whitebox.setInternalState(FlexLogger.class, "loggerType", LoggerType.SYSTEMOUT);
+ ReflectionTestUtils.setField(FlexLogger.class, "loggerType", LoggerType.SYSTEMOUT);
Logger logger = FlexLogger.getLogger(this.getClass(), true);
assertSame(logger, FlexLogger.getLogger(this.getClass(), true));
}
@Test
public void testGetLoggerStringBooleanEelf() {
- Whitebox.setInternalState(FlexLogger.class, "loggerType", LoggerType.EELF);
- Logger logger = FlexLogger.getLogger("str1", true);
- assertSame(logger, FlexLogger.getLogger("str1", true));
- }
-
- @Test
- public void testGetLoggerStringBooleanLog4j() {
- Whitebox.setInternalState(FlexLogger.class, "loggerType", LoggerType.LOG4J);
- Logger logger = FlexLogger.getLogger("str1", true);
- assertSame(logger, FlexLogger.getLogger("str1", true));
+ ReflectionTestUtils.setField(FlexLogger.class, "loggerType", LoggerType.EELF);
+ Logger logger = FlexLogger.getLogger(true);
+ assertSame(logger, FlexLogger.getLogger(true));
}
@Test
public void testGetLoggerStringBooleanSystemOut() {
- Whitebox.setInternalState(FlexLogger.class, "loggerType", LoggerType.SYSTEMOUT);
- Logger logger = FlexLogger.getLogger("str1", true);
- assertSame(logger, FlexLogger.getLogger("str1", true));
+ ReflectionTestUtils.setField(FlexLogger.class, "loggerType", LoggerType.SYSTEMOUT);
+ Logger logger = FlexLogger.getLogger(true);
+ assertSame(logger, FlexLogger.getLogger(true));
}
@Test
@@ -131,7 +105,9 @@ public class FlexLoggerTest {
changedKeys.add("error.level");
changedKeys.add("audit.level");
PropertiesCallBack propertiesCallBack = new PropertiesCallBack("name");
- propertiesCallBack.propertiesChanged(PropertyUtil.getProperties("config/policyLogger.properties"), changedKeys);
+ assertThatCode(() -> propertiesCallBack
+ .propertiesChanged(PropertyUtil.getProperties("config/policyLogger.properties"), changedKeys))
+ .doesNotThrowAnyException();
}
}
diff --git a/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/Logger4JTest.java b/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/Logger4JTest.java
deleted file mode 100644
index 99c343c0..00000000
--- a/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/Logger4JTest.java
+++ /dev/null
@@ -1,350 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP-Logging
- * ================================================================================
- * Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications 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.policy.common.logging.flexlogger;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-import java.util.UUID;
-import org.apache.log4j.Level;
-import org.apache.log4j.Logger;
-import org.junit.Test;
-import org.mockito.Mockito;
-import org.onap.policy.common.logging.eelf.MessageCodes;
-import org.powermock.reflect.Whitebox;
-
-public class Logger4JTest {
-
- private Logger4J logger4J = new Logger4J("str1", "Logger4JTest");
-
- @Test
- public void testLogger4JClassOfQ() {
- new Logger4J(this.getClass());
- }
-
- @Test
- public void testSetAndGetTransId() {
- logger4J.setTransId("transactionId");
- assertEquals("transactionId", logger4J.getTransId());
- }
-
- @Test
- public void testDebugObject() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- Mockito.when(logger.isDebugEnabled()).thenReturn(true);
- logger4J.setTransId("transactionId");
- logger4J.debug("message");
- Mockito.verify(logger).debug("transactionId|message");
- }
-
- @Test
- public void testErrorObject() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- logger4J.setTransId("transactionId");
- logger4J.error("message");
- Mockito.verify(logger).error("transactionId|Logger4JTest|message");
- }
-
- @Test
- public void testInfoObject() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- logger4J.setTransId("transactionId");
- logger4J.info("message");
- Mockito.verify(logger).info("transactionId|Logger4JTest|message");
- }
-
- @Test
- public void testWarnObject() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- logger4J.setTransId("transactionId");
- logger4J.warn("message");
- Mockito.verify(logger).warn("transactionId|Logger4JTest|message");
- }
-
- @Test
- public void testTraceObject() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- logger4J.setTransId("transactionId");
- logger4J.trace("message");
- Mockito.verify(logger).trace("transactionId|Logger4JTest|message");
- }
-
- @Test
- public void testIsDebugEnabled() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- Mockito.when(logger.isDebugEnabled()).thenReturn(true).thenReturn(false);
- assertTrue(logger4J.isDebugEnabled());
- assertFalse(logger4J.isDebugEnabled());
- }
-
- @Test
- public void testIsErrorEnabled() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- Mockito.when(logger.isEnabledFor(Level.ERROR)).thenReturn(true).thenReturn(false);
- assertTrue(logger4J.isErrorEnabled());
- assertFalse(logger4J.isErrorEnabled());
- }
-
- @Test
- public void testIsInfoEnabled() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- Mockito.when(logger.isInfoEnabled()).thenReturn(true).thenReturn(false);
- assertTrue(logger4J.isInfoEnabled());
- assertFalse(logger4J.isInfoEnabled());
- }
-
- @Test
- public void testIsWarnEnabled() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- Mockito.when(logger.isEnabledFor(Level.WARN)).thenReturn(true).thenReturn(false);
- assertTrue(logger4J.isWarnEnabled());
- assertFalse(logger4J.isWarnEnabled());
- }
-
- @Test
- public void testAuditObject() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- logger4J.audit("str1");
- Mockito.verify(logger).info("Logger4JTest|str1");
- }
-
- @Test
- public void testRecordAuditEventStartString() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- logger4J.recordAuditEventEnd("eventId", "rule");
- Mockito.verify(logger).info("Logger4JTest|eventId:rule");
- }
-
- @Test
- public void testRecordAuditEventStartUuid() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- UUID uuid = UUID.randomUUID();
- logger4J.recordAuditEventStart(uuid);
- Mockito.verify(logger).info("Logger4JTest|recordAuditEventStart with eventId " + uuid.toString());
- }
-
- @Test
- public void testRecordAuditEventEndStringStringString() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- logger4J.recordAuditEventEnd("eventId", "rule", "policyVersion");
- Mockito.verify(logger).info("Logger4JTest|eventId:rule");
- }
-
- @Test
- public void testRecordAuditEventEndUuidStringString() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- UUID uuid = UUID.randomUUID();
- logger4J.recordAuditEventEnd(uuid, "rule", "policyVersion");
- Mockito.verify(logger).info("Logger4JTest|" + uuid.toString() + ":rule");
- }
-
- @Test
- public void testRecordAuditEventEndStringString() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- logger4J.recordAuditEventEnd("eventId", "rule");
- Mockito.verify(logger).info("Logger4JTest|eventId:rule");
- }
-
- @Test
- public void testRecordAuditEventEndUuidString() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- UUID uuid = UUID.randomUUID();
- logger4J.recordAuditEventEnd(uuid, "rule");
- Mockito.verify(logger).info("Logger4JTest|" + uuid.toString() + ":rule");
- }
-
- @Test
- public void testRecordMetricEventStringString() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- logger4J.recordMetricEvent("eventId", "str1");
- Mockito.verify(logger).info("Logger4JTest|eventId:str1");
- }
-
- @Test
- public void testRecordMetricEventUuidString() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- UUID uuid = UUID.randomUUID();
- logger4J.recordMetricEvent(uuid, "str1");
- Mockito.verify(logger).info("Logger4JTest|" + uuid.toString() + ":str1");
- }
-
- @Test
- public void testMetrics() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- logger4J.metrics("str1");
- Mockito.verify(logger).info("str1");
- }
-
- @Test
- public void testErrorMessageCodesThrowableStringArray() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- logger4J.setTransId("transactionId");
- logger4J.error(MessageCodes.GENERAL_ERROR, new NullPointerException(), "str1", "str2");
- Mockito.verify(logger)
- .error("transactionId|Logger4JTest|MessageCodes :" + MessageCodes.GENERAL_ERROR + "[str1, str2]");
- }
-
- @Test
- public void testErrorMessageCodesStringArray() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- logger4J.setTransId("transactionId");
- logger4J.error(MessageCodes.GENERAL_ERROR, "str1", "str2");
- Mockito.verify(logger)
- .error("transactionId|Logger4JTest|MessageCode:" + MessageCodes.GENERAL_ERROR + "[str1, str2]");
- }
-
- @Test
- public void testPostMdcInfoForEventString() {
- String returnedTransactionId = logger4J.postMdcInfoForEvent("transactionId");
- assertEquals("transactionId", returnedTransactionId);
- }
-
- @Test
- public void testPostMdcInfoForEventEmptyString() {
- String returnedTransactionId = logger4J.postMdcInfoForEvent("");
- assertNotNull("", returnedTransactionId);
- assertNotEquals("", returnedTransactionId);
- }
-
- @Test
- public void testWarnMessageCodesStringArray() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- logger4J.warn(MessageCodes.GENERAL_ERROR, "str1", "str2");
- Mockito.verify(logger).warn("Logger4JTest|MessageCodes:" + MessageCodes.GENERAL_ERROR + "[str1, str2]");
- }
-
- @Test
- public void testWarnMessageCodesThrowableStringArray() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- logger4J.setTransId("transactionId");
- logger4J.warn(MessageCodes.GENERAL_ERROR, new NullPointerException(), "str1", "str2");
- Mockito.verify(logger).warn("Logger4JTest|MessageCodes:" + MessageCodes.GENERAL_ERROR + "[str1, str2]");
- }
-
- @Test
- public void testDebugObjectThrowable() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- logger4J.setTransId("transactionId");
- Exception exception = new NullPointerException();
- logger4J.debug("message", exception);
- Mockito.verify(logger).debug("message", exception);
- }
-
- @Test
- public void testErrorObjectThrowable() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- logger4J.setTransId("transactionId");
- Exception exception = new NullPointerException();
- logger4J.error("message", exception);
- Mockito.verify(logger).error("message", exception);
- }
-
- @Test
- public void testInfoObjectThrowable() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- logger4J.setTransId("transactionId");
- Exception exception = new NullPointerException();
- logger4J.info("message", exception);
- Mockito.verify(logger).info("message", exception);
- }
-
- @Test
- public void testWarnObjectThrowable() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- Exception exception = new NullPointerException();
- logger4J.warn("message", exception);
- Mockito.verify(logger).warn("message", exception);
- }
-
- @Test
- public void testTraceObjectThrowable() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- Exception exception = new NullPointerException();
- logger4J.trace("message", exception);
- Mockito.verify(logger).trace("message", exception);
- }
-
- @Test
- public void testAuditObjectThrowable() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- Exception exception = new NullPointerException();
- logger4J.audit("message", exception);
- Mockito.verify(logger).info("message", exception);
- }
-
- @Test
- public void testIsTraceEnabled() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- logger4J.isTraceEnabled();
- Mockito.verify(logger).isTraceEnabled();
- }
-
- @Test
- public void testPostMdcInfoForTriggeredRule() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- logger4J.postMdcInfoForTriggeredRule("transactionId");
- Mockito.verify(logger).info("transactionId");
- }
-
- @Test
- public void testPostMdcInfoForEventObject() {
- Logger logger = Mockito.mock(Logger.class);
- Whitebox.setInternalState(logger4J, "log", logger);
- logger4J.postMdcInfoForEvent(1);
- Mockito.verify(logger).info(1);
- }
-
-}
diff --git a/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/PropertyUtilTest.java b/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/PropertyUtilTest.java
index bbf77179..13f525c9 100644
--- a/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/PropertyUtilTest.java
+++ b/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/PropertyUtilTest.java
@@ -3,13 +3,14 @@
* ONAP-Logging
* ================================================================================
* Copyright (C) 2018-2020 Ericsson, AT&T. All rights reserved.
+ * Modifications Copyright (C) 2023 Nordix Foundation.
* ================================================================================
* 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.
@@ -43,28 +44,28 @@ import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.onap.policy.common.logging.flexlogger.PropertyUtil.Listener;
-import org.powermock.reflect.Whitebox;
+import org.springframework.test.util.ReflectionTestUtils;
public class PropertyUtilTest {
private static final String TIMER_FIELD = "timer";
private static final File FILE = new File("target/test.properties");
private static Timer saveTimer;
-
+
private TimerTask task;
private Timer timer;
private TestListener testListener;
-
+
@BeforeClass
public static void setUpBeforeClass() {
- saveTimer = Whitebox.getInternalState(PropertyUtil.LazyHolder.class, TIMER_FIELD);
-
+ saveTimer = (Timer) ReflectionTestUtils.getField(PropertyUtil.LazyHolder.class, TIMER_FIELD);
+
}
-
+
@AfterClass
public static void tearDownAfterClass() {
- Whitebox.setInternalState(PropertyUtil.LazyHolder.class, TIMER_FIELD, saveTimer);
-
+ ReflectionTestUtils.setField(PropertyUtil.LazyHolder.class, TIMER_FIELD, saveTimer);
+
}
/**
@@ -74,15 +75,15 @@ public class PropertyUtilTest {
public void setUp() throws IOException {
task = null;
timer = mock(Timer.class);
- Whitebox.setInternalState(PropertyUtil.LazyHolder.class, TIMER_FIELD, timer);
-
+ ReflectionTestUtils.setField(PropertyUtil.LazyHolder.class, TIMER_FIELD, timer);
+
doAnswer(args -> {
task = args.getArgument(0, TimerTask.class);
return null;
}).when(timer).schedule(any(TimerTask.class), anyLong(), anyLong());
-
+
testListener = new TestListener();
-
+
FileOutputStream fileOutputStream = new FileOutputStream(FILE);
Properties properties = new Properties();
properties.put("testProperty", "testValue");
@@ -95,7 +96,7 @@ public class PropertyUtilTest {
PropertyUtil.stopListening(FILE, testListener);
FILE.delete();
}
-
+
@Test
public void testTimer() {
assertNotNull(saveTimer);
diff --git a/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/SystemOutLoggerTest.java b/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/SystemOutLoggerTest.java
index 92df0297..38c9e0d2 100644
--- a/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/SystemOutLoggerTest.java
+++ b/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/SystemOutLoggerTest.java
@@ -3,7 +3,7 @@
* ONAP-Logging
* ================================================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019-2020 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.
@@ -21,16 +21,15 @@
package org.onap.policy.common.logging.flexlogger;
+import static org.assertj.core.api.Assertions.assertThatCode;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import com.att.eelf.configuration.EELFLogger.Level;
-
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.UUID;
-
import org.junit.Test;
import org.onap.policy.common.logging.eelf.MessageCodes;
import org.onap.policy.common.logging.eelf.PolicyLogger;
@@ -41,7 +40,7 @@ public class SystemOutLoggerTest {
@Test
public void testSystemOutLoggerClassOfQ() {
- new SystemOutLogger(SystemOutLoggerTest.class);
+ assertThatCode(() -> new SystemOutLogger(SystemOutLoggerTest.class)).doesNotThrowAnyException();
}
@Test
@@ -426,7 +425,7 @@ public class SystemOutLoggerTest {
try {
System.setOut(ps);
systemOutLogger.setTransId("transactionId");
- systemOutLogger.debug(1, new NullPointerException());
+ systemOutLogger.debug("1", new NullPointerException());
assertTrue(baos.toString(),
baos.toString().contains("transactionId|SystemOutLoggerTest : 1:java.lang.NullPointerException"));
} finally {
@@ -443,7 +442,7 @@ public class SystemOutLoggerTest {
try {
System.setOut(ps);
systemOutLogger.setTransId("transactionId");
- systemOutLogger.error(1, new NullPointerException());
+ systemOutLogger.error("1", new NullPointerException());
assertTrue(baos.toString(),
baos.toString().contains("transactionId|SystemOutLoggerTest : 1:java.lang.NullPointerException"));
} finally {
@@ -460,7 +459,7 @@ public class SystemOutLoggerTest {
try {
System.setOut(ps);
systemOutLogger.setTransId("transactionId");
- systemOutLogger.info(1, new NullPointerException());
+ systemOutLogger.info("1", new NullPointerException());
assertTrue(baos.toString(),
baos.toString().contains("transactionId|SystemOutLoggerTest : 1:java.lang.NullPointerException"));
} finally {
@@ -477,7 +476,7 @@ public class SystemOutLoggerTest {
try {
System.setOut(ps);
systemOutLogger.setTransId("transactionId");
- systemOutLogger.warn(1, new NullPointerException());
+ systemOutLogger.warn("1", new NullPointerException());
assertTrue(baos.toString(),
baos.toString().contains("transactionId|SystemOutLoggerTest : 1:java.lang.NullPointerException"));
} finally {
@@ -511,7 +510,7 @@ public class SystemOutLoggerTest {
try {
System.setOut(ps);
systemOutLogger.setTransId("transactionId");
- systemOutLogger.audit(1, new NullPointerException());
+ systemOutLogger.audit("1", new NullPointerException());
assertTrue(baos.toString(),
baos.toString().contains("transactionId|SystemOutLoggerTest : 1:java.lang.NullPointerException"));
} finally {