+++ /dev/null
-<?xml version="1.0"?>
-<!--
- ============LICENSE_START=======================================================
- Copyright (C) 2018 AT&T Technologies. 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.
-
- SPDX-License-Identifier: Apache-2.0
- ============LICENSE_END=========================================================
--->
-
-<!DOCTYPE suppressions PUBLIC
- "-//Puppy Crawl//DTD Suppressions 1.0//EN"
- "http://www.puppycrawl.com/dtds/suppressions_1_0.dtd">
-
-<suppressions>
- <suppress checks="AbbreviationAsWordInName"
- files="ONAPLoggingUtils.java|ONAPLoggingContext.java|DroolsPDPMDCInfo.java|Logger.java|EventData.java|EventTrackInfo.java|MDCInfo.java|PolicyLogger.java|SystemOutLoggerTest.java|Logger4JTest.java|EelfLoggerTest.java|PolicyLoggerTest.java|DroolsPDPMDCInfoTest.java|EventTrackInfoTest.java|HttpClientTest.java"
- lines="1-9999"/>
-</suppressions>
============LICENSE_START=======================================================
ONAP Policy Engine - Common Modules
================================================================================
- Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ 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.
<packaging>jar</packaging>
<dependencies>
+ <dependency>
+ <groupId>org.projectlombok</groupId>
+ <artifactId>lombok</artifactId>
+ <scope>provided</scope>
+ </dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<groupId>com.att.eelf</groupId>
<artifactId>eelf-core</artifactId>
<version>1.0.1-oss</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<includeTestResources>true</includeTestResources>
<excludes>
</excludes>
- <suppressionsLocation>${project.basedir}/checkstyle-suppressions.xml</suppressionsLocation>
<consoleOutput>true</consoleOutput>
<failsOnViolation>true</failsOnViolation>
<violationSeverity>warning</violationSeverity>
</execution>
</executions>
<dependencies>
- <!-- We need to include the dependency of the project so that its include
+ <!-- We need to include the dependency of the project so that its include
in classpath when running plugin -->
<dependency>
<groupId>org.onap.policy.common</groupId>
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * 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.
* creates). Example: log4j.appender.auditAppender.layout=org.apache.log4j.EnhancedPatternLayout
* log4j.appender.auditAppender.layout.ConversionPattern=%d|%X{requestId}|%X{serviceInstanceId}|...|%m%n
* where "requestId" and "serviceInstanceId" are entries in the MDC hashmap.
- *
+ *
* <p>The notable functionality the SharedLoggingContext adds over MDC is that it maintains its own
* copy of the MDC data items in a hashmap (not in ThreadLocal storage), which allows more control
* of the data. The ONAPLoggingContext constructor that takes another ONAPLoggingContext object as a
* requests, and for each request, create a new logging context with that base context as a
* parameter; this will create a new logging context with those initial values and none of the
* request-specific values from the previous request such as a request ID.
- *
+ *
* <p>The setter methods in this class set corresponding items in the SharedLoggingContext/MDC
* hashmaps. These items correspond to the fields defined in the "ONAP platform application logging
* guidelines" document. In addition, there is a pair of convenience functions, transactionStarted()
* calculate the duration of the transaction and record that value in the "timer" item.
*
*/
-public class ONAPLoggingContext {
+public class OnapLoggingContext {
private static final String REQUEST_ID = "requestId";
private static final String SERVICE_INSTANCE_ID = "serviceInstanceId";
/**
* Create a new ONAPLoggingContext with no base context.
*/
- public ONAPLoggingContext() {
+ public OnapLoggingContext() {
context = (SharedLoggingContext) loggingContextBuilder.forSharing().build();
}
* unchanging and common to all the threads. That constant data can be populated in a base
* context, and then each request handler creates new context passing that base context to
* populate the common data in the new one.
- *
+ *
* @param baseContext onap logging context
*/
- public ONAPLoggingContext(ONAPLoggingContext baseContext) {
+ public OnapLoggingContext(OnapLoggingContext baseContext) {
context = (SharedLoggingContext) loggingContextBuilder.forSharing().build();
// a logging context could be passed into a thread (e.g. one that is servicing a queue)
// that already had a logging context established, so the MDC hashmap could contain
*
* @param id request identifier
*/
- public void setRequestID(String id) {
+ public void setRequestId(String id) {
context.put(REQUEST_ID, id);
}
/**
* Get the value for the data item with key "requestId".
- *
+ *
* @return current value, or empty string if not set
*/
- public String getRequestID() {
+ public String getRequestId() {
return context.get(REQUEST_ID, EMPTY_STRING);
}
*
* @param id service identifier
*/
- public void setServiceInstanceID(String id) {
+ public void setServiceInstanceId(String id) {
context.put(SERVICE_INSTANCE_ID, id);
}
/**
* Get the value for the data item with key "serviceInstanceId".
- *
+ *
* @return current value, or empty string if not set
*/
- public String getServiceInstanceID() {
+ public String getServiceInstanceId() {
return context.get(SERVICE_INSTANCE_ID, EMPTY_STRING);
}
*
* @param id thread identifier
*/
- public void setThreadID(String id) {
+ public void setThreadId(String id) {
context.put(THREAD_ID, id);
}
/**
* Get the value for the data item with key "threadId".
- *
+ *
* @return current value, or empty string if not set
*/
- public String getThreadID() {
+ public String getThreadId() {
return context.get(THREAD_ID, EMPTY_STRING);
}
/**
* Get the value for the data item with key "serverName".
- *
+ *
* @return current value, or empty string if not set
*/
public String getServerName() {
/**
* Get the value for the data item with key "serviceName".
- *
+ *
* @return current value, or empty string if not set
*/
public String getServiceName() {
/**
* Get the value for the data item with key "partnerName".
- *
+ *
* @return current value, or empty string if not set
*/
public String getPartnerName() {
/**
* Get the value for the data item with key "statusCode".
- *
+ *
* @return current value, or empty string if not set
*/
public String getStatusCode() {
/**
* Get the value for the data item with key "targetEntity".
- *
+ *
* @return current value, or empty string if not set
*/
public String getTargetEntity() {
/**
* Get the value for the data item with key "targetServiceName".
- *
+ *
* @return current value, or empty string if not set
*/
public String getTargetServiceName() {
*
* @param uuid instance uuid
*/
- public void setInstanceUUID(String uuid) {
+ public void setInstanceUuid(String uuid) {
context.put(INSTANCE_UUID, uuid);
}
/**
* Get the value for the data item with key "instanceUuid".
- *
+ *
* @return current value, or empty string if not set
*/
- public String getInstanceUUID() {
+ public String getInstanceUuid() {
return context.get(INSTANCE_UUID, EMPTY_STRING);
}
/**
* Get the value for the data item with key "severity".
- *
+ *
* @return current value, or empty string if not set
*/
public String getSeverity() {
/**
* Set the value for the data item with key "serverIp".
*
- * @param serverIP server ip address
+ * @param serverIp server ip address
*/
- public void setServerIPAddress(String serverIP) {
- context.put(SERVER_IP_ADDRESS, serverIP);
+ public void setServerIpAddress(String serverIp) {
+ context.put(SERVER_IP_ADDRESS, serverIp);
}
/**
* Get the value for the data item with key "serverIp".
- *
+ *
* @return current value, or empty string if not set
*/
- public String getServerIPAddress() {
+ public String getServerIpAddress() {
return context.get(SERVER_IP_ADDRESS, EMPTY_STRING);
}
/**
* Get the value for the data item with key "server".
- *
+ *
* @return current value, or empty string if not set
*/
public String getServer() {
/**
* Set the value for the data item with key "clientIp".
*
- * @param clientIP client ip address
+ * @param clientIp client ip address
*/
- public void setClientIPAddress(String clientIP) {
- context.put(CLIENT_IP_ADDRESS, clientIP);
+ public void setClientIpAddress(String clientIp) {
+ context.put(CLIENT_IP_ADDRESS, clientIp);
}
/**
* Get the value for the data item with key "clientIp".
- *
+ *
* @return current value, or empty string if not set
*/
- public String getClientIPAddress() {
+ public String getClientIpAddress() {
return context.get(CLIENT_IP_ADDRESS, EMPTY_STRING);
}
/**
* Get the value for the data item with key "classname".
- *
+ *
* @return current value, or empty string if not set
*/
public String getClassname() {
/**
* Get the value for the data item with key "TransactionBeginTimestamp".
- *
+ *
* @return current value, or 0 if not set
*/
public long getTransactionBeginTimestamp() {
/**
* Get the value for the data item with key "TransactionEndTimestamp".
- *
+ *
* @return current value, or 0 if not set
*/
public long getTransactionEndTimestamp() {
/**
* Get the value for the data item with key "TransactionElapsedTime".
- *
+ *
* @return current value, or 0 if not set
*/
public long getTransactionElapsedTime() {
/**
* Get the value for the data item with key "MetricBeginTimestamp".
- *
+ *
* @return current value, or 0 if not set
*/
public long getMetricBeginTimestamp() {
/**
* Get the value for the data item with key "MetricEndTimestamp".
- *
+ *
* @return current value, or 0 if not set
*/
public long getMetricEndTimestamp() {
/**
* Get the value for the data item with key "MetricElapsedTime".
- *
+ *
* @return current value, or 0 if not set
*/
public long getMetricElapsedTime() {
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * 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.
import javax.servlet.http.HttpServletRequest;
-public class ONAPLoggingUtils {
+public class OnapLoggingUtils {
- private ONAPLoggingUtils() {}
+ private OnapLoggingUtils() {}
/**
* Get the ONAPLoggingContext for a request.
- *
+ *
* @param request the request
* @param baseContext the context to supply to the ONAPLoggingContext
* @return the ONAPLoggingContext
*/
- public static ONAPLoggingContext getLoggingContextForRequest(HttpServletRequest request,
- ONAPLoggingContext baseContext) {
- ONAPLoggingContext requestContext = new ONAPLoggingContext(baseContext);
+ public static OnapLoggingContext getLoggingContextForRequest(HttpServletRequest request,
+ OnapLoggingContext baseContext) {
+ OnapLoggingContext requestContext = new OnapLoggingContext(baseContext);
if (request.getLocalAddr() != null) { // may be null in junit tests
- requestContext.setServerIPAddress(request.getLocalAddr());
+ requestContext.setServerIpAddress(request.getLocalAddr());
}
// get client IP address as leftmost address in X-Forwarded-For header if present,
// 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];
- requestContext.setClientIPAddress(forwarded);
+ requestContext.setClientIpAddress(forwarded);
} else if (request.getRemoteAddr() != null) { // may be null in junit tests
- requestContext.setClientIPAddress(request.getRemoteAddr());
+ requestContext.setClientIpAddress(request.getRemoteAddr());
}
// RequestID
// This needs to be renamed to ONAP when the other components in ONAP
// rename to this.
String requestId = request.getHeader("X-ECOMP-RequestID");
if (requestId != null && requestId.trim().length() > 0) {
- requestContext.setRequestID(requestId);
+ requestContext.setRequestId(requestId);
}
return requestContext;
}
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * 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.
package org.onap.policy.common.logging.eelf;
+import com.att.eelf.configuration.Configuration;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
-public class DroolsPDPMDCInfo implements MDCInfo {
+public class DroolsPdpMdcInfo implements MdcInfo {
private static ConcurrentHashMap<String, String> mdcMap = new ConcurrentHashMap<>();
mdcMap.put(Configuration.MDC_SERVICE_INSTANCE_ID, "Policy.droolsPdp.event");
mdcMap.put(Configuration.MDC_INSTANCE_UUID, "");
mdcMap.put(Configuration.MDC_ALERT_SEVERITY, "");
- mdcMap.put(Configuration.PARTNER_NAME, "N/A");
- mdcMap.put(Configuration.STATUS_CODE, "N/A");
- mdcMap.put(Configuration.RESPONSE_CODE, "N/A");
- mdcMap.put(Configuration.RESPONSE_DESCRIPTION, "N/A");
+ mdcMap.put(OnapConfigProperties.PARTNER_NAME, "N/A");
+ mdcMap.put(OnapConfigProperties.STATUS_CODE, "N/A");
+ mdcMap.put(OnapConfigProperties.RESPONSE_CODE, "N/A");
+ mdcMap.put(OnapConfigProperties.RESPONSE_DESCRIPTION, "N/A");
}
/**
* Get the MMDC Info.
- *
+ *
* @return the instance of ConcurrentHashMap.
*/
@Override
- public ConcurrentMap<String, String> getMDCInfo() {
+ public ConcurrentMap<String, String> getMdcInfo() {
return mdcMap;
}
}
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * 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.
package org.onap.policy.common.logging.eelf;
import java.time.Instant;
+import lombok.Getter;
+import lombok.Setter;
/**
* EventData can be used for logging a rule event.
*/
+@Getter
+@Setter
public class EventData {
private String requestId = null;
/**
* Create an instance.
- *
+ *
* @param requestId the request ID
* @param startTime the start time
* @param endTime the end time
this.endTime = endTime;
}
- public String getRequestID() {
+ public String getRequestId() {
return requestId;
}
- public void setRequestID(String requestId) {
+ public void setRequestId(String requestId) {
this.requestId = requestId;
}
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * 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.
/**
* Returns an instance of EventData associated to this requestID.
- *
- * @param requestID request id
+ *
+ * @param requestId request id
* @return EventData
*/
- public EventData getEventDataByRequestID(String requestID) {
- return eventInfo.get(requestID);
+ public EventData getEventDataByRequestId(String requestId) {
+ return eventInfo.get(requestId);
}
/**
* Stores an EventData object in a ConcurrentHashMap using its requestID as key.
- *
+ *
* @param event event data
*/
public void storeEventData(EventData event) {
if (event != null) {
- String id = event.getRequestID();
+ String id = event.getRequestId();
if (id == null || id.isEmpty()) {
return;
}
/**
* Removes an EventData object from a ConcurrentHashMap using the eventId as key.
- *
+ *
* @param eventId event id
*/
public void remove(String eventId) {
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * 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.
}
expiredEvents.add(entry.getKey());
- PolicyLogger.info(className + " add expired event request ID: " + event.getRequestID());
+ PolicyLogger.info(className + " add expired event request ID: " + event.getRequestId());
}
}
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * 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.
* Interface needs to be implemented by DroolsPDPMDCInfo.
*/
@FunctionalInterface
-public interface MDCInfo {
+public interface MdcInfo {
/**
* Returns MDC info.
- *
+ *
* @return MDC info
*/
- ConcurrentMap<String, String> getMDCInfo();
+ ConcurrentMap<String, String> getMdcInfo();
}
* 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.
package org.onap.policy.common.logging.eelf;
-public interface Configuration extends com.att.eelf.configuration.Configuration {
+public class OnapConfigProperties {
/**
* The Date-time of the start of a transaction.
*/
- String BEGIN_TIME_STAMP = "BeginTimestamp";
+ public static final String BEGIN_TIME_STAMP = "BeginTimestamp";
/**
* The Date-time of the end of transaction.
*/
- String END_TIME_STAMP = "EndTimestamp";
+ public static final String END_TIME_STAMP = "EndTimestamp";
/**
* Externally advertised API invoked by clients of this component.
*/
- String SERVICE_NAME = "ServiceName";
+ public static final String SERVICE_NAME = "ServiceName";
/**
* Client or user invoking the API.
*/
- String PARTNER_NAME = "PartnerName";
+ public static final String PARTNER_NAME = "PartnerName";
- String TARGET_ENTITY = "TargetEntity";
+ public static final String TARGET_ENTITY = "TargetEntity";
- String TARGET_SERVICE_NAME = "TargetServiceName";
+ public static final String TARGET_SERVICE_NAME = "TargetServiceName";
/**
* High level success or failure (COMPLETE or ERROR).
*/
- String STATUS_CODE = "StatusCode";
+ public static final String STATUS_CODE = "StatusCode";
/**
* Application specific response code.
*/
- String RESPONSE_CODE = "ResponseCode";
+ public static final String RESPONSE_CODE = "ResponseCode";
/**
* Human readable description of the application specific response code.
*/
- String RESPONSE_DESCRIPTION = "ResponseDescription";
+ public static final String RESPONSE_DESCRIPTION = "ResponseDescription";
/**
* Externally advertised API invoked by clients of this component.
*/
- String ELAPSED_TIME = "ElapsedTime";
+ public static final String ELAPSED_TIME = "ElapsedTime";
/**
* High level failure (ERROR).
*/
- String ERROR_CATEGORY = "ErrorCategory";
+ public static final String ERROR_CATEGORY = "ErrorCategory";
- String ERROR_CODE = "ErrorCode";
+ public static final String ERROR_CODE = "ErrorCode";
- String ERROR_DESCRIPTION = "ErrorDescription";
+ public static final String ERROR_DESCRIPTION = "ErrorDescription";
- String CLASS_NAME = "ClassName";
+ public static final String CLASS_NAME = "ClassName";
- String SERVER_NAME = "ServerName";
+ public static final String SERVER_NAME = "ServerName";
+
+
+ private OnapConfigProperties() {
+ // do nothing
+ }
}
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.onap.policy.common.logging.eelf.Configuration.BEGIN_TIME_STAMP;
-import static org.onap.policy.common.logging.eelf.Configuration.ELAPSED_TIME;
-import static org.onap.policy.common.logging.eelf.Configuration.END_TIME_STAMP;
-import static org.onap.policy.common.logging.eelf.Configuration.ERROR_CATEGORY;
-import static org.onap.policy.common.logging.eelf.Configuration.ERROR_CODE;
-import static org.onap.policy.common.logging.eelf.Configuration.ERROR_DESCRIPTION;
-import static org.onap.policy.common.logging.eelf.Configuration.PARTNER_NAME;
-import static org.onap.policy.common.logging.eelf.Configuration.RESPONSE_CODE;
-import static org.onap.policy.common.logging.eelf.Configuration.RESPONSE_DESCRIPTION;
-import static org.onap.policy.common.logging.eelf.Configuration.SERVER_NAME;
-import static org.onap.policy.common.logging.eelf.Configuration.STATUS_CODE;
-import static org.onap.policy.common.logging.eelf.Configuration.TARGET_ENTITY;
-import static org.onap.policy.common.logging.eelf.Configuration.TARGET_SERVICE_NAME;
+import static org.onap.policy.common.logging.eelf.OnapConfigProperties.BEGIN_TIME_STAMP;
+import static org.onap.policy.common.logging.eelf.OnapConfigProperties.ELAPSED_TIME;
+import static org.onap.policy.common.logging.eelf.OnapConfigProperties.END_TIME_STAMP;
+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.PARTNER_NAME;
+import static org.onap.policy.common.logging.eelf.OnapConfigProperties.RESPONSE_CODE;
+import static org.onap.policy.common.logging.eelf.OnapConfigProperties.RESPONSE_DESCRIPTION;
+import static org.onap.policy.common.logging.eelf.OnapConfigProperties.SERVER_NAME;
+import static org.onap.policy.common.logging.eelf.OnapConfigProperties.STATUS_CODE;
+import static org.onap.policy.common.logging.eelf.OnapConfigProperties.TARGET_ENTITY;
+import static org.onap.policy.common.logging.eelf.OnapConfigProperties.TARGET_SERVICE_NAME;
+import static org.onap.policy.common.logging.flexlogger.DisplayUtils.displayErrorMessage;
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFLogger.Level;
import com.att.eelf.configuration.EELFManager;
-
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.InetAddress;
import java.util.TimerTask;
import java.util.UUID;
import java.util.concurrent.ConcurrentMap;
-
+import java.util.function.Consumer;
+import org.apache.commons.lang3.StringUtils;
import org.onap.policy.common.logging.flexlogger.LoggerType;
import org.slf4j.MDC;
* @param transId the transaction ID
* @return String
*/
- public static String postMDCInfoForEvent(String transId) {
+ public static String postMdcInfoForEvent(String transId) {
MDC.clear();
String transactionId = transId;
if ("DROOLS".equalsIgnoreCase(component)) {
MDC.put(TARGET_ENTITY, "POLICY");
MDC.put(TARGET_SERVICE_NAME, "drools evaluate rule");
- return postMDCInfoForEvent(transactionId, new DroolsPDPMDCInfo());
+ return postMdcInfoForEvent(transactionId, new DroolsPdpMdcInfo());
} else {
// For Xacml
MDC.put(TARGET_ENTITY, "POLICY");
MDC.put(MDC_KEY_REQUEST_ID, transactionId);
MDC.put(MDC_SERVICE_NAME, "Policy.xacmlPdp");
MDC.put(MDC_SERVICE_INSTANCE_ID, "Policy.xacmlPdp.event");
- try {
- MDC.put(MDC_SERVER_FQDN, hostName);
- MDC.put(MDC_SERVER_IP_ADDRESS, hostAddress);
- } catch (Exception e) {
- errorLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICY_LOGGER);
- }
-
- MDC.put(MDC_INSTANCE_UUID, "");
- MDC.put(MDC_ALERT_SEVERITY, "");
-
- SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
-
- Instant startTime = Instant.now();
- Instant endTime = Instant.now();
-
- String formatedTime = sdf.format(Date.from(startTime));
- MDC.put(BEGIN_TIME_STAMP, formatedTime);
-
- // set default values for these required fields below, they can be overridden
- formatedTime = sdf.format(Date.from(endTime));
- MDC.put(END_TIME_STAMP, formatedTime);
- MDC.put(ELAPSED_TIME, Long.toString(Duration.between(startTime, endTime).toMillis()));
-
- MDC.put(PARTNER_NAME, "N/A");
-
- MDC.put(STATUS_CODE, COMPLETE_STATUS);
- MDC.put(RESPONSE_CODE, "N/A");
- MDC.put(RESPONSE_DESCRIPTION, "N/A");
+ setMdcHostInfo();
+ seTimeStamps();
return transactionId;
-
}
/**
* @param mdcInfo the MDC info
* @return String
*/
- private static String postMDCInfoForEvent(String transId, MDCInfo mdcInfo) {
+ private static String postMdcInfoForEvent(String transId, MdcInfo mdcInfo) {
MDC.put(MDC_KEY_REQUEST_ID, transId);
- if (mdcInfo != null && mdcInfo.getMDCInfo() != null && !mdcInfo.getMDCInfo().isEmpty()) {
+ if (mdcInfo != null && mdcInfo.getMdcInfo() != null && !mdcInfo.getMdcInfo().isEmpty()) {
- ConcurrentMap<String, String> mdcMap = mdcInfo.getMDCInfo();
+ ConcurrentMap<String, String> mdcMap = mdcInfo.getMdcInfo();
Iterator<String> keyIterator = mdcMap.keySet().iterator();
String key;
}
}
- try {
- MDC.put(MDC_SERVER_FQDN, hostName);
- MDC.put(MDC_SERVER_IP_ADDRESS, hostAddress);
- } catch (Exception e) {
- errorLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICY_LOGGER);
- }
+ setMdcHostInfo();
+
Instant startTime = Instant.now();
Instant endTime = Instant.now();
- SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
-
- String formatedTime = sdf.format(Date.from(startTime));
- MDC.put(BEGIN_TIME_STAMP, formatedTime);
-
- // set default values for these required fields below, they can be overridden
- formatedTime = sdf.format(Date.from(endTime));
- MDC.put(END_TIME_STAMP, formatedTime);
- MDC.put(ELAPSED_TIME, Long.toString(Duration.between(startTime, endTime).toMillis()));
+ seTimeStamps(startTime, endTime);
return transId;
}
*
* @param eventObject event object
*/
- public static void postMDCInfoForEvent(Object eventObject) {
- postMDCInfoForEvent("" + eventObject);
+ public static void postMdcInfoForEvent(Object eventObject) {
+ postMdcInfoForEvent("" + eventObject);
+ }
+
+ private static void setMdcHostInfo() {
+ try {
+ MDC.put(MDC_SERVER_FQDN, hostName);
+ MDC.put(MDC_SERVER_IP_ADDRESS, hostAddress);
+ } catch (Exception e) {
+ errorLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICY_LOGGER);
+ }
}
/**
MDC.put(MDC_INSTANCE_UUID, "");
MDC.put(MDC_ALERT_SEVERITY, "");
- SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
-
Instant startTime = Instant.now();
Instant endTime = Instant.now();
- String formatedTime = sdf.format(Date.from(startTime));
- MDC.put(BEGIN_TIME_STAMP, formatedTime);
-
- // set default values for these required fields below, they can be overridden
- formatedTime = sdf.format(Date.from(endTime));
- MDC.put(END_TIME_STAMP, formatedTime);
- MDC.put(ELAPSED_TIME, Long.toString(Duration.between(startTime, endTime).toMillis()));
+ seTimeStamps(startTime, endTime);
MDC.put(PARTNER_NAME, "N/A");
}
+ private static void seTimeStamps(Instant startTime, Instant endTime) {
+ SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
+
+ String formatedTime = sdf.format(Date.from(startTime));
+ MDC.put(BEGIN_TIME_STAMP, formatedTime);
+
+ // set default values for these required fields below, they can be overridden
+ formatedTime = sdf.format(Date.from(endTime));
+ MDC.put(END_TIME_STAMP, formatedTime);
+ MDC.put(ELAPSED_TIME, Long.toString(Duration.between(startTime, endTime).toMillis()));
+ }
+
/**
* Sets transaction Id to MDC.
*
* @param transId the transaction ID
* @return String
*/
- public static String postMDCInfoForTriggeredRule(String transId) {
+ public static String postMdcInfoForTriggeredRule(String transId) {
String transactionId = transId;
MDC.put(MDC_KEY_REQUEST_ID, transactionId);
MDC.put(MDC_SERVICE_NAME, "Policy.droolsPdp");
MDC.put(MDC_SERVICE_INSTANCE_ID, "");
- try {
- MDC.put(MDC_SERVER_FQDN, hostName);
- MDC.put(MDC_SERVER_IP_ADDRESS, hostAddress);
- } catch (Exception e) {
- errorLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICY_LOGGER);
- }
+ setMdcHostInfo();
MDC.put(MDC_INSTANCE_UUID, "");
MDC.put(MDC_ALERT_SEVERITY, "");
MDC.put(STATUS_CODE, COMPLETE_STATUS);
*
* @param obj object
*/
- public static void postMDCUUIDForTriggeredRule(Object obj) {
+ public static void postMdcUuidForTriggeredRule(Object obj) {
- postMDCInfoForTriggeredRule("" + obj);
+ postMdcInfoForTriggeredRule("" + obj);
}
public static void recordAuditEventStart(String eventId) {
MDC.put(STATUS_CODE, COMPLETE_STATUS);
- postMDCInfoForEvent(eventId);
+ postMdcInfoForEvent(eventId);
if (eventTracker == null) {
eventTracker = new EventTrackInfo();
}
EventData event = new EventData();
- event.setRequestID(eventId);
+ event.setRequestId(eventId);
event.setStartTime(Instant.now());
eventTracker.storeEventData(event);
MDC.put(MDC_KEY_REQUEST_ID, eventId);
return;
}
- EventData event = eventTracker.getEventDataByRequestID(eventId);
+ EventData event = eventTracker.getEventDataByRequestId(eventId);
if (event != null) {
Instant endTime = event.getEndTime();
return;
}
- EventData event = eventTracker.getEventDataByRequestID(eventId.toString());
+ EventData event = eventTracker.getEventDataByRequestId(eventId.toString());
if (event != null) {
Instant endTime = event.getEndTime();
MDC.put(MDC_KEY_REQUEST_ID, eventId);
}
- SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
-
- String formatedTime = sdf.format(Date.from(startTime));
- MDC.put(BEGIN_TIME_STAMP, formatedTime);
-
- // set default values for these required fields below, they can be overridden
- formatedTime = sdf.format(Date.from(endTime));
- MDC.put(END_TIME_STAMP, formatedTime);
+ seTimeStamps(startTime, endTime);
MDC.put(RESPONSE_CODE, "N/A");
MDC.put(RESPONSE_DESCRIPTION, "N/A");
long ns = Duration.between(startTime, endTime).toMillis();
- MDC.put(ELAPSED_TIME, Long.toString(ns));
-
auditLogger.info(MessageCodes.RULE_AUDIT_START_END_INFO, MDC.get(MDC_SERVICE_NAME), rule, startTime.toString(),
endTime.toString(), Long.toString(ns), policyVersion);
// --- remove the record from the concurrentHashMap
- if (eventTracker != null && eventTracker.getEventDataByRequestID(eventId) != null) {
+ if (eventTracker != null && eventTracker.getEventDataByRequestId(eventId) != null) {
eventTracker.remove(eventId);
debugLogger.info("eventTracker.remove(" + eventId + ")");
*/
public static LoggerType init(Properties properties) {
- Properties loggerProperties;
- if (properties != null) {
- loggerProperties = properties;
- } else {
- System.err.println("PolicyLogger cannot find its configuration - continue");
- loggerProperties = new Properties();
- }
-
- LoggerType loggerType = LoggerType.EELF;
+ Properties loggerProperties = getLoggerProperties(properties);
// fetch and verify definitions of some properties
try {
+ setOverrideLogbackLevels(loggerProperties);
- final int timerDelayTimeProp =
- Integer.parseInt(loggerProperties.getProperty("timer.delay.time", Integer.toString(1000)));
- final int checkIntervalProp =
- Integer.parseInt(loggerProperties.getProperty("check.interval", Integer.toString(30000)));
- final int expiredDateProp =
- Integer.parseInt(loggerProperties.getProperty("event.expired.time", Integer.toString(86400)));
- final int concurrentHashMapLimitProp =
- Integer.parseInt(loggerProperties.getProperty("concurrentHashMap.limit", Integer.toString(5000)));
- final int stopCheckPointProp =
- Integer.parseInt(loggerProperties.getProperty("stop.check.point", Integer.toString(2500)));
- final String loggerTypeProp = loggerProperties.getProperty("logger.type", loggerType.toString());
-
- final String debugLevelProp = loggerProperties.getProperty("debugLogger.level", "INFO");
- final String metricsLevelProp = loggerProperties.getProperty("metricsLogger.level", "ON");
- final String auditLevelProp = loggerProperties.getProperty("audit.level", "ON");
- final String errorLevelProp = loggerProperties.getProperty("error.level", "ON");
- component = loggerProperties.getProperty("policy.component", "DROOLS");
- final String overrideLogbackLevel = loggerProperties.getProperty("override.logback.level.setup");
-
- if (overrideLogbackLevel != null && !overrideLogbackLevel.isEmpty()) {
- if ("TRUE".equalsIgnoreCase(overrideLogbackLevel)) {
- isOverrideLogbackLevel = true;
- } else {
- isOverrideLogbackLevel = false;
- }
- }
-
-
- if (debugLevelProp != null && !debugLevelProp.isEmpty()) {
-
- PolicyLogger.setDebugLevel(Level.valueOf(debugLevelProp));
+ setLoggerLevel(loggerProperties, "debugLogger.level", "INFO", PolicyLogger::setDebugLevel);
- }
- // Only check if it is to turn off or not
- if (errorLevelProp != null && errorLevelProp.equalsIgnoreCase(Level.OFF.toString())) {
-
- PolicyLogger.setErrorLevel(Level.valueOf(errorLevelProp));
+ // Only check if it is to turn on or off
+ setLoggerOnOff(loggerProperties, "metricsLogger.level", PolicyLogger::setMetricsLevel);
+ setLoggerOnOff(loggerProperties, "audit.level", PolicyLogger::setAuditLevel);
+ setLoggerOnOff(loggerProperties, "error.level", PolicyLogger::setErrorLevel);
- }
- // Only check if it is to turn off or not
- if (metricsLevelProp != null && metricsLevelProp.equalsIgnoreCase(Level.OFF.toString())) {
-
- PolicyLogger.setMetricsLevel(Level.valueOf(metricsLevelProp));
-
- }
- // Only check if it is to turn off or not
- if (auditLevelProp != null && auditLevelProp.equalsIgnoreCase(Level.OFF.toString())) {
-
- PolicyLogger.setAuditLevel(Level.valueOf(auditLevelProp));
-
- }
-
- if (isOverrideLogbackLevel) {
-
- debugLogger.setLevel(debugLevel);
- metricsLogger.setLevel(metricsLevel);
- auditLogger.setLevel(auditLevel);
- errorLogger.setLevel(errorLevel);
-
- }
isEventTrackerRunning = false;
- debugLogger.info("timerDelayTime value: " + timerDelayTimeProp);
-
- debugLogger.info("checkInterval value: " + checkIntervalProp);
-
- debugLogger.info("expiredDate value: " + expiredDateProp);
-
- debugLogger.info("concurrentHashMapLimit value: " + concurrentHashMapLimitProp);
-
- debugLogger.info("loggerType value: " + loggerTypeProp);
-
- debugLogger.info("debugLogger level: " + debugLevelProp);
+ timerDelayTime = getIntProp(loggerProperties, "timer.delay.time", timerDelayTime);
+ checkInterval = getIntProp(loggerProperties, "check.interval", checkInterval);
+ expiredTime = getIntProp(loggerProperties, "event.expired.time", expiredTime);
+ concurrentHashMapLimit = getIntProp(loggerProperties, "concurrentHashMap.limit", concurrentHashMapLimit);
+ stopCheckPoint = getIntProp(loggerProperties, "stop.check.point", stopCheckPoint);
+ component = loggerProperties.getProperty("policy.component", "DROOLS");
debugLogger.info("component: " + component);
- if (timerDelayTimeProp > 0) {
-
- timerDelayTime = timerDelayTimeProp;
-
- } else {
- 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());
-
- }
- errorLogger.error("failed to get the timer.delay.time, so use its default value: " + timerDelayTime);
- }
+ return detmLoggerType(loggerProperties);
- if (checkIntervalProp > 0) {
+ } catch (Exception e) {
+ MDC.put(ERROR_CATEGORY, ERROR_CATEGORY_VALUE);
- checkInterval = checkIntervalProp;
+ 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());
- } else {
- 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());
-
- }
- errorLogger.error("failed to get the check.interval, so use its default value: " + checkInterval);
}
+ errorLogger.error("failed to get the policyLogger.properties, so use their default values", e);
- if (expiredDateProp > 0) {
-
- expiredTime = expiredDateProp;
-
- } else {
- 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());
-
- }
- errorLogger.error("failed to get the event.expired.time, so use its default value: " + expiredTime);
- }
+ return LoggerType.EELF;
+ }
- if (concurrentHashMapLimitProp > 0) {
+ }
- concurrentHashMapLimit = concurrentHashMapLimitProp;
+ private static int getIntProp(Properties properties, String propName, int defaultValue) {
+ final int propValue = Integer.parseInt(properties.getProperty(propName, String.valueOf(defaultValue)));
- } else {
- 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());
-
- }
- errorLogger.error("failed to get the concurrentHashMap.limit, so use its default value: "
- + concurrentHashMapLimit);
- }
+ debugLogger.info(propName + " value: " + propValue);
- if (stopCheckPointProp > 0) {
+ if (propValue > 0) {
+ return propValue;
- stopCheckPoint = stopCheckPointProp;
+ } else {
+ 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());
- } else {
- 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());
-
- }
- errorLogger.error("failed to get the stop.check.point, so use its default value: " + stopCheckPoint);
}
+ errorLogger.error("failed to get the " + propName + ", so use its default value: " + defaultValue);
+ return defaultValue;
+ }
+ }
- if (loggerTypeProp != null) {
-
- if ("EELF".equalsIgnoreCase(loggerTypeProp)) {
-
- loggerType = LoggerType.EELF;
-
- } else if ("LOG4J".equalsIgnoreCase(loggerTypeProp)) {
-
- loggerType = LoggerType.LOG4J;
-
- } else if ("SYSTEMOUT".equalsIgnoreCase(loggerTypeProp)) {
-
- loggerType = LoggerType.SYSTEMOUT;
+ private static Properties getLoggerProperties(Properties properties) {
+ if (properties != null) {
+ return properties;
+ } else {
+ displayErrorMessage("PolicyLogger cannot find its configuration - continue");
+ return new Properties();
+ }
+ }
- }
+ private static void setLoggerLevel(Properties properties, String propName, String defaultValue,
+ Consumer<String> setter) {
- }
+ final String propValue = properties.getProperty(propName, defaultValue);
- if (debugLevelProp != null && !debugLevelProp.isEmpty()) {
+ if (!StringUtils.isBlank(propValue)) {
+ debugLogger.info(propName + " level: " + propValue);
+ }
- debugLevel = Level.valueOf(debugLevelProp);
+ setter.accept(propValue);
+ }
- }
- // Only check if it is to turn off or not
- if (errorLevelProp != null && errorLevelProp.equalsIgnoreCase(Level.OFF.toString())) {
+ private static void setLoggerOnOff(Properties properties, String propName, Consumer<String> setter) {
+ final String propValue = properties.getProperty(propName, "ON");
- errorLevel = Level.valueOf(errorLevelProp);
+ if (Level.OFF.toString().equalsIgnoreCase(propValue)) {
+ debugLogger.info(propName + " level: " + propValue);
+ }
- }
- // Only check if it is to turn off or not
- if (metricsLevelProp != null && metricsLevelProp.equalsIgnoreCase(Level.OFF.toString())) {
+ setter.accept(propValue);
+ }
- metricsLevel = Level.valueOf(metricsLevelProp);
+ private static void setOverrideLogbackLevels(Properties loggerProperties) {
+ final String overrideLogbackLevel = loggerProperties.getProperty("override.logback.level.setup");
- }
- // Only check if it is to turn off or not
- if (auditLevelProp != null && auditLevelProp.equalsIgnoreCase(Level.OFF.toString())) {
+ if (!StringUtils.isBlank(overrideLogbackLevel)) {
+ isOverrideLogbackLevel = "TRUE".equalsIgnoreCase(overrideLogbackLevel);
+ }
+ }
- auditLevel = Level.valueOf(auditLevelProp);
+ private static LoggerType detmLoggerType(Properties loggerProperties) {
+ final String loggerTypeProp = loggerProperties.getProperty("logger.type", LoggerType.EELF.toString());
+ debugLogger.info("loggerType value: " + loggerTypeProp);
- }
+ switch (loggerTypeProp.toUpperCase()) {
+ case "EELF":
+ return LoggerType.EELF;
- } catch (Exception e) {
- MDC.put(ERROR_CATEGORY, ERROR_CATEGORY_VALUE);
+ case "LOG4J":
+ return LoggerType.LOG4J;
- 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());
+ case "SYSTEMOUT":
+ return LoggerType.SYSTEMOUT;
- }
- errorLogger.error("failed to get the policyLogger.properties, so use their default values", e);
+ default:
+ return LoggerType.EELF;
}
-
- return loggerType;
-
}
public static void setServerInfo(String serverHost, String serverPort) {
MDC.put(SERVER_NAME, serverHost + ":" + serverPort);
}
-
}
--- /dev/null
+/*
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * 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;
+
+/**
+ * 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.
+ */
+public class DisplayUtils {
+
+ private DisplayUtils() {
+ // do nothing
+ }
+
+ public static void displayMessage(Object message) {
+ System.out.println(message);
+ }
+
+ public static void displayErrorMessage(Object msg) {
+ System.err.println(msg);
+ }
+}
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * 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.
/**
* Constructor.
- *
+ *
* @param clazz the class
*/
public EelfLogger(Class<?> clazz) {
if (clazz != null) {
className = clazz.getName();
}
- PolicyLogger.postMDCInfoForEvent(null);
+ PolicyLogger.postMdcInfoForEvent(null);
}
/**
* Constructor.
- *
+ *
* @param className the class name
*/
public EelfLogger(String className) {
if (className != null) {
this.className = className;
}
- PolicyLogger.postMDCInfoForEvent(null);
+ PolicyLogger.postMdcInfoForEvent(null);
}
/**
* Constructor.
- *
+ *
* @param clazz the class
* @param isNewTransaction is a new transaction
*/
className = clazz.getName();
}
if (isNewTransaction) {
- transId = PolicyLogger.postMDCInfoForEvent(null);
+ transId = PolicyLogger.postMdcInfoForEvent(null);
} else {
transId = PolicyLogger.getTransId();
}
/**
* Constructor.
- *
+ *
* @param className the class name
* @param isNewTransaction is a new transaction
*/
this.className = className;
}
if (isNewTransaction) {
- transId = PolicyLogger.postMDCInfoForEvent(null);
+ transId = PolicyLogger.postMdcInfoForEvent(null);
} else {
transId = PolicyLogger.getTransId();
}
/**
* Constructor.
- *
+ *
* @param clazz the class
* @param transId the transaction ID
*/
if (clazz != null) {
className = clazz.getName();
}
- PolicyLogger.postMDCInfoForEvent(transId);
+ PolicyLogger.postMdcInfoForEvent(transId);
this.transId = transId;
}
/**
* Constructor.
- *
+ *
* @param className the class name
* @param transId the transaction ID
*/
if (className != null) {
this.className = className;
}
- PolicyLogger.postMDCInfoForEvent(transId);
+ PolicyLogger.postMdcInfoForEvent(transId);
this.transId = transId;
}
/**
* Sets transaction Id for logging.
- *
+ *
* @param transId the transaction ID
*/
@Override
/**
* Records a message.
- *
+ *
* @param message the message
*/
@Override
/**
* Records a message.
- *
+ *
* @param message the message
* @param throwable the throwable
*/
/**
* Records an error message.
- *
+ *
* @param message the message
*/
@Override
/**
* Records an error message.
- *
+ *
* @param message the message
* @param throwable the throwable
*/
/**
* Records an error message.
- *
+ *
* @param msg the message code
* @param throwable the throwable
* @param arguments the messages
/**
* Records an error message.
- *
+ *
* @param msg the message code
* @param arguments the messages
*/
/**
* Records a message.
- *
+ *
* @param message the message
*/
@Override
/**
* Records a message.
- *
+ *
* @param message the message
* @param throwable the throwable
*/
/**
* Records a message.
- *
+ *
* @param message the message
*/
@Override
/**
* Records a message.
- *
+ *
* @param message the message
* @param throwable the throwable
*/
/**
* Records a message.
- *
+ *
* @param msg the message codes
* @param arguments the messages
*/
/**
* Records a message.
- *
+ *
* @param msg the message
* @param throwable the throwable
* @param arguments the messages
/**
* Records a message.
- *
+ *
* @param message the message
*/
@Override
/**
* Records a message.
- *
+ *
* @param message the message
* @param throwable the throwable
*/
/**
* Returns true for debug enabled, or false for not.
- *
+ *
* @return boolean
*/
@Override
/**
* Returns true for info enabled, or false for not.
- *
+ *
* @return boolean
*/
@Override
/**
* Returns true for warn enabled, or false for not.
- *
+ *
* @return boolean
*/
@Override
/**
* Returns true for error enabled, or false for not.
- *
+ *
* @return boolean
*/
@Override
/**
* Returns true for audit enabled, or false for not.
- *
+ *
* @return boolean
*/
@Override
/**
* Returns true for metrics enabled, or false for not.
- *
+ *
* @return boolean
*/
@Override
/**
* Returns true for trace enabled, or false for not.
- *
+ *
* @return boolean
*/
@Override
/**
* Records an audit message.
- *
+ *
* @param arg0 the message
*/
@Override
/**
* Records an audit message.
- *
+ *
* @param message the message
* @param throwable the throwable
*/
/**
* Records an audit message.
- *
+ *
* @param eventId the event ID
*/
@Override
/**
* Records an audit message.
- *
+ *
* @param eventId the event ID
*/
@Override
/**
* Records an audit message.
- *
+ *
* @param eventId the event ID
* @param rule the rule
* @param policyVersion the policy cersion
/**
* Records an audit message.
- *
+ *
* @param eventId the event ID
* @param rule the rule
* @param policyVersion the policy version
/**
* Records an audit message.
- *
+ *
* @param eventId the event ID
* @param rule the rule
*/
/**
* Records an audit message.
- *
+ *
* @param eventId the event ID
* @param rule the rule
*/
/**
* Records a metrics message.
- *
+ *
* @param eventId the event ID
* @param message the message
*/
/**
* Records a metrics message.
- *
+ *
* @param eventId the event ID
* @param message the message
*/
/**
* Records a metrics message.
- *
+ *
* @param message the message
*/
@Override
/**
* Populates MDC Info.
- *
+ *
* @param transId the transaction ID
*/
@Override
- public String postMDCInfoForEvent(String transId) {
- return PolicyLogger.postMDCInfoForEvent(transId);
+ public String postMdcInfoForEvent(String transId) {
+ return PolicyLogger.postMdcInfoForEvent(transId);
}
/**
* Populates MDC Info.
- *
+ *
* @param obj the object
*/
@Override
- public void postMDCInfoForEvent(Object obj) {
- PolicyLogger.postMDCInfoForEvent(obj);
+ public void postMdcInfoForEvent(Object obj) {
+ PolicyLogger.postMdcInfoForEvent(obj);
}
/**
* Populates MDC Info for the rule triggered.
- *
+ *
* @param transId the transaction ID
*/
@Override
- public void postMDCInfoForTriggeredRule(String transId) {
- PolicyLogger.postMDCInfoForTriggeredRule(transId);
+ public void postMdcInfoForTriggeredRule(String transId) {
+ PolicyLogger.postMdcInfoForTriggeredRule(transId);
}
}
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * 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.
package org.onap.policy.common.logging.flexlogger;
+import static org.onap.policy.common.logging.flexlogger.DisplayUtils.displayMessage;
+
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Instant;
/**
* Returns an instance of Logger.
- *
+ *
* @param clazz the class
*/
public static Logger getLogger(Class<?> clazz) {
Logger logger = null;
- System.out.println(GET_LOGGER_PREFIX + loggerType);
+ displayMessage(GET_LOGGER_PREFIX + loggerType);
switch (loggerType) {
case EELF:
/**
* Returns an instance of Logger.
- *
+ *
* @param name the name of the logger
*/
public static Logger getLogger(String name) {
Logger logger = null;
- System.out.println(GET_LOGGER_PREFIX + loggerType);
+ displayMessage(GET_LOGGER_PREFIX + loggerType);
switch (loggerType) {
case EELF:
/**
* Returns an instance of Logger.
- *
+ *
* @param clazz the class
* @param isNewTransaction is a new transaction
*/
public static Logger getLogger(Class<?> clazz, boolean isNewTransaction) {
Logger logger = null;
- System.out.println(GET_LOGGER_PREFIX + loggerType);
+ displayMessage(GET_LOGGER_PREFIX + loggerType);
switch (loggerType) {
case EELF:
/**
* 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;
- System.out.println(GET_LOGGER_PREFIX + loggerType);
+ displayMessage(GET_LOGGER_PREFIX + loggerType);
switch (loggerType) {
case EELF:
* Returns the calling class name.
*/
public String getClassName() {
- System.out.println("getClassContext()[3].getName() " + getClassContext()[3].getName());
+ displayMessage("getClassContext()[3].getName() " + getClassContext()[3].getName());
return getClassContext()[3].getName();
}
/**
* Returns an instance of Logger4J.
- *
+ *
* @param name the name of the logger
*/
private static Logger4J getLog4JLogger(String name) {
/**
* Returns an instance of EelfLogger.
- *
+ *
* @param clazz the class
* @param isNewTransaction is a new transaction
*/
}
// installl already created but it is new transaction
if (isNewTransaction) {
- String transId = PolicyLogger.postMDCInfoForEvent(null);
+ String transId = PolicyLogger.postMdcInfoForEvent(null);
logger.setTransId(transId);
}
}
- System.out.println("eelfLoggerMap size : " + eelfLoggerMap.size() + " class name: " + className);
+ displayMessage("eelfLoggerMap size : " + eelfLoggerMap.size() + " class name: " + className);
return logger;
}
*/
private static LoggerType initlogger() {
LoggerType loggerType = LoggerType.EELF;
- String overrideLogbackLevel = "FALSE";
- String loggerTypeString = "";
Properties properties = null;
try {
properties = PropertyUtil.getProperties("config/policyLogger.properties");
- System.out.println("FlexLogger:properties => " + properties);
+ displayMessage("FlexLogger:properties => " + properties);
if (properties != null) {
- overrideLogbackLevel = properties.getProperty("override.logback.level.setup");
- System.out.println("FlexLogger:overrideLogbackLevel => " + overrideLogbackLevel);
- loggerTypeString = properties.getProperty("logger.type");
- if (loggerTypeString != null) {
- if ("EELF".equalsIgnoreCase(loggerTypeString)) {
- loggerType = LoggerType.EELF;
- if ("TRUE".equalsIgnoreCase(overrideLogbackLevel)) {
- System.out.println("FlexLogger: start listener.");
- properties = PropertyUtil.getProperties("config/policyLogger.properties",
- new PropertiesCallBack("FlexLogger-CallBack"));
- }
- } else if ("LOG4J".equalsIgnoreCase(loggerTypeString)) {
- loggerType = LoggerType.LOG4J;
- } else if ("SYSTEMOUT".equalsIgnoreCase(loggerTypeString)) {
- loggerType = LoggerType.SYSTEMOUT;
- }
-
- System.out.println("FlexLogger.logger_Type value: " + loggerTypeString);
+ 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"));
}
}
} catch (IOException e1) {
- System.out.println("initlogger" + e1);
+ displayMessage("initlogger" + e1);
} finally {
// OK to pass no properties (null)
loggerType = PolicyLogger.init(properties);
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));
- System.out.println("FlexLogger.propertiesChanged : called at time : " + formatedTime);
- System.out.println("FlexLogger.propertiesChanged : debugLevel : " + debugLevel);
+ displayMessage("FlexLogger.propertiesChanged : called at time : " + formatedTime);
+ displayMessage("FlexLogger.propertiesChanged : debugLevel : " + debugLevel);
if (changedKeys != null) {
}
}
}
-
}
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * 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.
/**
* Populates MDC info.
*/
- public String postMDCInfoForEvent(String transId);
+ public String postMdcInfoForEvent(String transId);
/**
* Populates MDC Info.
*/
- public void postMDCInfoForEvent(Object obj);
+ public void postMdcInfoForEvent(Object obj);
/**
* Sets transaction Id.
/**
* Populates MDC Info for the rule triggered.
*/
- public void postMDCInfoForTriggeredRule(String transId);
+ public void postMdcInfoForTriggeredRule(String transId);
}
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * 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.
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;
/**
* Constructor.
- *
+ *
* @param clazz the class
*/
public Logger4J(Class<?> clazz) {
- System.out.println("create instance of Logger4J");
+ 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) {
- System.out.println("create instance of Logger4J");
+ displayMessage("create instance of Logger4J");
if (name != null) {
log = Logger.getLogger(name);
}
/**
* Records a message.
- *
+ *
* @param message the message
*/
@Override
/**
* Records a message.
- *
+ *
* @param message the message
* @param throwable the throwable
*/
/**
* Records an error message.
- *
+ *
* @param message the message
*/
@Override
/**
* Records an error message.
- *
+ *
* @param message the message
* @param throwable the throwable
*/
/**
* Records an error message.
- *
+ *
* @param msg the message code
* @param throwable the throwable
* @param arguments the messages
/**
* Records an error message.
- *
+ *
* @param msg the message code
* @param arguments the messages
*/
/**
* Records a message.
- *
+ *
* @param message the message
*/
@Override
/**
* Records a message.
- *
+ *
* @param message the message
* @param throwable the throwable
*/
/**
* Records a message.
- *
+ *
* @param message the message
*/
@Override
/**
* Records a message.
- *
+ *
* @param message the message
* @param throwable the throwable
*/
/**
* Records a message.
- *
+ *
* @param msg the message code
* @param arguments the messages
*/
/**
* Records a message.
- *
+ *
* @param msg the message code
* @param throwable the throwable
* @param arguments the messages
/**
* Records a message.
- *
+ *
* @param message the message
*/
@Override
/**
* Records a message.
- *
+ *
* @param message the message
* @param throwable the throwable
*/
/**
* Returns true for debug enabled, or false for not.
- *
+ *
* @return boolean
*/
@Override
/**
* Returns true for error enabled, or false for not.
- *
+ *
* @return boolean
*/
@SuppressWarnings("deprecation")
/**
* Returns true for info enabled, or false for not.
- *
+ *
* @return boolean
*/
@Override
/**
* Returns true for warn enabled, or false for not.
- *
+ *
* @return boolean
*/
@SuppressWarnings("deprecation")
/**
* Returns true for audit enabled, or false for not.
- *
+ *
* @return boolean
*/
@Override
/**
* Returns true for metrics enabled, or false for not.
- *
+ *
* @return boolean
*/
@Override
/**
* Records an audit message.
- *
+ *
* @param message the message
*/
@Override
/**
* Records an audit message.
- *
+ *
* @param message the message
* @param throwable the throwable
*/
/**
* Records an audit message.
- *
+ *
* @param eventId the event ID
*/
@Override
/**
* Records an audit message.
- *
+ *
* @param eventId the event ID
*/
@Override
/**
* Records an audit message.
- *
+ *
* @param eventId the event ID
* @param rule the rule
* @param policyVersion the policy version
/**
* Records an audit message.
- *
+ *
* @param eventId the event ID
* @param rule the rule
* @param policyVersion the policy version
/**
* Records an audit message.
- *
+ *
* @param eventId the event ID
* @param rule the rule
*/
/**
* Records an audit message.
- *
+ *
* @param eventId the event ID
* @param rule the rule
*/
/**
* Records a metrics message.
- *
+ *
* @param eventId the event ID
* @param message the message
*/
/**
* Records a metrics message.
- *
+ *
* @param eventId the event ID
* @param message the message
*/
/**
* Records a metrics message.
- *
+ *
* @param message the message
*/
@Override
/**
* Returns transaction Id.
- *
+ *
* @param transId the transaction ID
*/
@Override
- public String postMDCInfoForEvent(String transId) {
+ public String postMdcInfoForEvent(String transId) {
String transactionId = transId;
if (transactionId == null || transactionId.isEmpty()) {
transactionId = UUID.randomUUID().toString();
/**
* Records transaction Id.
- *
+ *
* @param message the message
*/
@Override
- public void postMDCInfoForEvent(Object message) {
+ public void postMdcInfoForEvent(Object message) {
log.info(message);
}
/**
* Returns true for trace enabled, or false for not.
- *
+ *
* @return boolean
*/
@Override
/**
* Records transaction Id.
- *
+ *
* @param transId the transaction ID
*/
@Override
- public void postMDCInfoForTriggeredRule(String transId) {
+ public void postMdcInfoForTriggeredRule(String transId) {
log.info(transId);
}
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * 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.
package org.onap.policy.common.logging.flexlogger;
+import static org.onap.policy.common.logging.flexlogger.DisplayUtils.displayErrorMessage;
+
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
* notifications of future changes.
*/
public class PropertyUtil {
-
+
protected static class LazyHolder {
/**
* Timer thread. Will not be allocated by the JVM until it is first referenced.
/**
* Read in a properties file.
- *
+ *
* @param file the properties file
* @return a Properties object, containing the associated properties
* @throws IOException - subclass 'FileNotFoundException' if the file does not exist or can't be
/**
* Read in a properties file.
- *
+ *
* @param fileName the properties file
* @return a Properties object, containing the associated properties
* @throws IOException - subclass 'FileNotFoundException' if the file does not exist or can't be
public interface Listener {
/**
* Notification of a properties file change.
- *
+ *
* @param properties the new properties
* @param changedKeys the set of property names that have changed, including additions and
* removals
try {
poll();
} catch (Exception e) {
- System.err.println(e);
+ displayErrorMessage(e);
}
}
};
/**
* Add a listener to the notification list.
- *
+ *
* @param listener this is the listener to add to the list
* @return the properties at the moment the listener was added to the list
*/
/**
* Remove a listener from the notification list.
- *
+ *
* @param listener this is the listener to remove
*/
synchronized void removeListener(Listener listener) {
/**
* This method is periodically called to check for property list updates.
- *
+ *
* @throws IOException if there is an error in reading the properties file
*/
synchronized void poll() throws IOException {
/**
* Stop listenening for updates.
- *
+ *
* @param file the properties file
* @param listener notify if not null, this is a callback interface that was used for
* notifications of changes
/**
* Stop listenening for updates.
- *
+ *
* @param fileName the properties file
* @param listener notify if not null, this is a callback interface that was used for
* notifications of changes
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * 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.
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;
/**
* Constructor.
- *
+ *
* @param clazz the class
*/
public SystemOutLogger(Class<?> clazz) {
- System.out.println("create instance of SystemOutLogger");
+ displayMessage("create instance of SystemOutLogger");
if (clazz != null) {
className = clazz.getName();
}
/**
* Constructor.
- *
+ *
* @param className the class name
*/
public SystemOutLogger(String className) {
- System.out.println("create instance of SystemOutLogger");
+ displayMessage("create instance of SystemOutLogger");
if (className != null) {
this.className = className;
}
@Override
public void setTransId(String transId) {
- System.out.println(transId);
+ displayMessage(transId);
this.transId = transId;
}
/**
* Records a message.
- *
+ *
* @param message the message
*/
@Override
public void debug(Object message) {
- System.out.println(transId + "|" + className + " : " + message);
+ displayMessage(transId + "|" + className + " : " + message);
}
/**
* Records a message.
- *
+ *
* @param message the message
* @param throwable the throwable
*/
@Override
public void debug(Object message, Throwable throwable) {
- System.out.println(transId + "|" + className + " : " + message + ":" + throwable);
+ displayMessage(transId + "|" + className + " : " + message + ":" + throwable);
}
/**
* Records an error message.
- *
+ *
* @param message the message
*/
@Override
public void error(Object message) {
- System.out.println(transId + "|" + className + " : " + message);
+ displayMessage(transId + "|" + className + " : " + message);
}
/**
* Records an error message.
- *
+ *
* @param message the message
* @param throwable the throwable
*/
@Override
public void error(Object message, Throwable throwable) {
- System.out.println(transId + "|" + className + " : " + message + ":" + throwable);
+ displayMessage(transId + "|" + className + " : " + 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) {
- System.out.println(className + " : " + "MessageCodes :" + msg + Arrays.asList(arguments));
+ displayMessage(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) {
- System.out.println(transId + "|" + className + " : " + "MessageCode:" + msg + Arrays.asList(arguments));
+ displayMessage(transId + "|" + className + " : " + "MessageCode:" + msg + Arrays.asList(arguments));
}
/**
* Records a message.
- *
+ *
* @param message the message
*/
@Override
public void info(Object message) {
- System.out.println(transId + "|" + className + " : " + message);
+ displayMessage(transId + "|" + className + " : " + message);
}
/**
* Records a message.
- *
+ *
* @param message the message
* @param throwable the throwable
*/
@Override
public void info(Object message, Throwable throwable) {
- System.out.println(transId + "|" + className + " : " + message + ":" + throwable);
+ displayMessage(transId + "|" + className + " : " + message + ":" + throwable);
}
/**
* Records a message.
- *
+ *
* @param message the message
*/
@Override
public void warn(Object message) {
- System.out.println(transId + "|" + className + " : " + message);
+ displayMessage(transId + "|" + className + " : " + message);
}
/**
* Records a message.
- *
+ *
* @param message the message
* @param throwable the throwable
*/
@Override
public void warn(Object message, Throwable throwable) {
- System.out.println(transId + "|" + className + " : " + message + ":" + throwable);
+ displayMessage(transId + "|" + className + " : " + message + ":" + throwable);
}
/**
* Records a message.
- *
+ *
* @param msg the message code
* @param arguments the messages
*/
@Override
public void warn(MessageCodes msg, String... arguments) {
- System.out.println(transId + "|" + className + " : " + "MessageCodes:" + msg + Arrays.asList(arguments));
+ displayMessage(transId + "|" + 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) {
- System.out.println(transId + "|" + className + " : " + "MessageCodes:" + msg + Arrays.asList(arguments));
+ displayMessage(transId + "|" + className + " : " + "MessageCodes:" + msg + Arrays.asList(arguments));
}
/**
* Records a message.
- *
+ *
* @param message the message
*/
@Override
public void trace(Object message) {
- System.out.println(transId + "|" + className + " : " + message);
+ displayMessage(transId + "|" + className + " : " + message);
}
/**
* Records a message.
- *
+ *
* @param message the message
* @param throwable the throwable
*/
@Override
public void trace(Object message, Throwable throwable) {
- System.out.println(transId + "|" + className + " : " + message + ":" + throwable);
+ displayMessage(transId + "|" + className + " : " + message + ":" + throwable);
}
/**
* Returns true for debug enabled, or false for not.
- *
+ *
* @return boolean
*/
@Override
/**
* Returns true for warn enabled, or false for not.
- *
+ *
* @return boolean
*/
@Override
/**
* Returns true for info enabled, or false for not.
- *
+ *
* @return boolean
*/
@Override
/**
* Returns true for error enabled, or false for not.
- *
+ *
* @return boolean
*/
@Override
/**
* Returns true for audit enabled, or false for not.
- *
+ *
* @return boolean
*/
@Override
/**
* Returns true for metrics enabled, or false for not.
- *
+ *
* @return boolean
*/
@Override
/**
* Records an audit message.
- *
+ *
* @param message the message
*/
@Override
public void audit(Object message) {
- System.out.println(transId + "|" + className + " : " + message);
+ displayMessage(transId + "|" + className + " : " + message);
}
/**
* Records an audit message.
- *
+ *
* @param message the message
* @param throwable the throwable
*/
@Override
public void audit(Object message, Throwable throwable) {
- System.out.println(transId + "|" + className + " : " + message + ":" + throwable);
+ displayMessage(transId + "|" + className + " : " + message + ":" + throwable);
}
/**
* Records an audit message.
- *
+ *
* @param eventId the event ID
*/
@Override
public void recordAuditEventStart(String eventId) {
- System.out.println(transId + "|" + className + " : " + eventId);
+ displayMessage(transId + "|" + className + " : " + eventId);
}
/**
* Records an audit message.
- *
+ *
* @param eventId the event ID
*/
@Override
public void recordAuditEventStart(UUID eventId) {
- System.out.println(eventId);
+ displayMessage(eventId);
}
/**
* 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) {
- System.out.println(className + " : " + eventId + ":" + rule + ":" + policyVersion);
+ displayMessage(className + " : " + eventId + ":" + rule + ":" + policyVersion);
}
/**
* 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) {
- System.out.println(className + " : " + eventId + ":" + rule + ":" + policyVersion);
+ displayMessage(className + " : " + eventId + ":" + rule + ":" + policyVersion);
}
/**
* Records an audit message.
- *
+ *
* @param eventId the event ID
* @param rule the rule
*/
@Override
public void recordAuditEventEnd(String eventId, String rule) {
- System.out.println(className + " : " + eventId + ":" + rule);
+ displayMessage(className + " : " + eventId + ":" + rule);
}
/**
* Records an audit message.
- *
+ *
* @param eventId the event ID
* @param rule the rule
*/
@Override
public void recordAuditEventEnd(UUID eventId, String rule) {
- System.out.println(className + " : " + eventId + ":" + rule);
+ displayMessage(className + " : " + eventId + ":" + rule);
}
/**
* Records a metrics message.
- *
+ *
* @param eventId the event ID
* @param message the message
*/
@Override
public void recordMetricEvent(String eventId, String message) {
- System.out.println(className + " : " + "eventId:" + eventId + "message:" + message);
+ displayMessage(className + " : " + "eventId:" + eventId + "message:" + message);
}
/**
* Records a metrics message.
- *
+ *
* @param eventId the event ID
* @param message the message
*/
@Override
public void recordMetricEvent(UUID eventId, String message) {
- System.out.println(className + " : " + eventId + ":" + message);
+ displayMessage(className + " : " + eventId + ":" + message);
}
/**
* Records a metrics message.
- *
+ *
* @param message the message
*/
@Override
public void metrics(Object message) {
- System.out.println(className + " : " + message);
+ displayMessage(className + " : " + message);
}
/**
* Returns transaction Id.
- *
+ *
* @param transId the transaction ID
*/
@Override
- public String postMDCInfoForEvent(String transId) {
+ public String postMdcInfoForEvent(String transId) {
String transactionId = transId;
if (transactionId == null || transactionId.isEmpty()) {
/**
* Records transaction Id.
- *
+ *
* @param message the message
*/
@Override
- public void postMDCInfoForEvent(Object message) {
- System.out.println(message);
+ public void postMdcInfoForEvent(Object message) {
+ displayMessage(message);
}
/**
* Returns true for trace enabled, or false for not.
- *
+ *
* @return boolean
*/
@Override
/**
* Records transaction Id.
- *
+ *
* @param transId the transaction ID
*/
@Override
- public void postMDCInfoForTriggeredRule(String transId) {
+ public void postMdcInfoForTriggeredRule(String transId) {
- System.out.println(transId);
+ displayMessage(transId);
}
-
}
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * 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.
/**
* A factory for setting up a LoggingContext.
- *
+ *
*/
public class LoggingContextFactory {
public static class Builder {
return forShared ? new SharedContext(baseContext) : new Slf4jLoggingContext(baseContext);
}
}
+
+ private LoggingContextFactory() {
+ // do nothing
+ }
}
* ============LICENSE_START=======================================================
* ONAP Policy Engine - Common Modules
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-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.
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
+import com.att.eelf.configuration.Configuration;
import org.junit.Test;
-public class DroolsPDPMDCInfoTest {
+public class DroolsPdpMdcInfoTest {
/**
- * Test method for {@link org.onap.policy.common.logging.eelf.DroolsPDPMDCInfo#getMDCInfo()}.
+ * Test method for {@link org.onap.policy.common.logging.eelf.DroolsPdpMdcInfo#getMdcInfo()}.
*/
@Test
- public void testGetMDCInfo() {
- DroolsPDPMDCInfo di = new DroolsPDPMDCInfo();
+ public void testGetMdcInfo() {
+ DroolsPdpMdcInfo di = new DroolsPdpMdcInfo();
- assertNotNull(di.getMDCInfo());
- assertEquals("Policy.droolsPdp", di.getMDCInfo().get(Configuration.MDC_SERVICE_NAME));
+ assertNotNull(di.getMdcInfo());
+ assertEquals("Policy.droolsPdp", di.getMdcInfo().get(Configuration.MDC_SERVICE_NAME));
}
}
* ============LICENSE_START=======================================================
* ONAP Policy Engine - Common Modules
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-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.
EventData eventData = new EventData();
assertNull(eventData.getEndTime());
- assertNull(eventData.getRequestID());
+ assertNull(eventData.getRequestId());
assertNull(eventData.getStartTime());
}
public void testEventDataStringInstantInstant() {
EventData eventData = new EventData("myreq", istart, iend);
- assertEquals("myreq", eventData.getRequestID());
+ assertEquals("myreq", eventData.getRequestId());
assertEquals(istart, eventData.getStartTime());
assertEquals(iend, eventData.getEndTime());
}
/**
- * Test method for {@link EventData#getRequestID()} and {@link EventData#setRequestID(String)}.
+ * Test method for {@link EventData#getRequestId()} and {@link EventData#setRequestId(String)}.
*/
@Test
public void testGetSetRequestId() {
EventData eventData = new EventData();
- assertNull(eventData.getRequestID());
+ assertNull(eventData.getRequestId());
- eventData.setRequestID("abc");
- assertEquals("abc", eventData.getRequestID());
+ eventData.setRequestId("abc");
+ assertEquals("abc", eventData.getRequestId());
- eventData.setRequestID("def");
- assertEquals("def", eventData.getRequestID());
+ eventData.setRequestId("def");
+ assertEquals("def", eventData.getRequestId());
}
/**
* ============LICENSE_START=======================================================
* ONAP Policy Engine - Common Modules
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-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.
}
/**
- * Test method for {@link EventTrackInfo#getEventDataByRequestID(String)}.
+ * Test method for {@link EventTrackInfo#getEventDataByRequestId(String)}.
*/
@Test
- public void testGetEventDataByRequestID() {
+ public void testGetEventDataByRequestId() {
info.storeEventData(data1);
info.storeEventData(data2);
- assertTrue(data1 == info.getEventDataByRequestID("abc"));
- assertTrue(data2 == info.getEventDataByRequestID("def"));
- assertNull(info.getEventDataByRequestID("hello"));
+ assertTrue(data1 == info.getEventDataByRequestId("abc"));
+ assertTrue(data2 == info.getEventDataByRequestId("def"));
+ assertNull(info.getEventDataByRequestId("hello"));
}
/**
assertEquals(2, info.getEventInfo().size());
// look-up by request id
- assertTrue(data1 == info.getEventDataByRequestID("abc"));
- assertTrue(data2 == info.getEventDataByRequestID("def"));
+ assertTrue(data1 == info.getEventDataByRequestId("abc"));
+ assertTrue(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"));
+ assertTrue(data1 == info.getEventDataByRequestId("abc"));
+ assertTrue(data2 == info.getEventDataByRequestId("def"));
}
/**
assertEquals(1, info.getEventInfo().size());
// look-up by request id
- assertNull(info.getEventDataByRequestID("abc"));
- assertTrue(data2 == info.getEventDataByRequestID("def"));
+ assertNull(info.getEventDataByRequestId("abc"));
+ assertTrue(data2 == info.getEventDataByRequestId("def"));
}
/**
* 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.
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
-import static org.onap.policy.common.logging.eelf.Configuration.PARTNER_NAME;
-import static org.onap.policy.common.logging.eelf.Configuration.RESPONSE_CODE;
-import static org.onap.policy.common.logging.eelf.Configuration.RESPONSE_DESCRIPTION;
-import static org.onap.policy.common.logging.eelf.Configuration.SERVER_NAME;
-import static org.onap.policy.common.logging.eelf.Configuration.STATUS_CODE;
-import static org.onap.policy.common.logging.util.TestUtils.overrideStaticField;
+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;
+import static org.onap.policy.common.logging.eelf.OnapConfigProperties.SERVER_NAME;
+import static org.onap.policy.common.logging.eelf.OnapConfigProperties.STATUS_CODE;
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFLogger.Level;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
+import org.powermock.reflect.Whitebox;
import org.slf4j.MDC;
public class PolicyLoggerTest {
}
@Test
- public void testPostMDCInfoForEventString() {
- PolicyLogger.postMDCInfoForEvent("transactionId");
+ public void testPostMdcInfoForEventString() {
+ PolicyLogger.postMdcInfoForEvent("transactionId");
assertEquals("", MDC.get(MDC_REMOTE_HOST));
assertEquals("transactionId", MDC.get(MDC_KEY_REQUEST_ID));
}
@Test
- public void testPostMDCInfoForEventStringDrools() {
+ public void testPostMdcInfoForEventStringDrools() {
Properties properties = new Properties();
properties.setProperty("policy.component", "DROOLS");
PolicyLogger.init(properties);
- PolicyLogger.postMDCInfoForEvent("transactionId");
+ PolicyLogger.postMdcInfoForEvent("transactionId");
assertEquals("transactionId", MDC.get(MDC_KEY_REQUEST_ID));
assertEquals("Policy.droolsPdp", MDC.get(MDC_SERVICE_NAME));
}
@Test
- public void testPostMDCInfoForEventObject() {
- PolicyLogger.postMDCInfoForEvent(1);
+ public void testPostMdcInfoForEventObject() {
+ PolicyLogger.postMdcInfoForEvent(1);
assertEquals("", MDC.get(MDC_REMOTE_HOST));
assertEquals("1", MDC.get(MDC_KEY_REQUEST_ID));
}
@Test
- public void testPostMDCInfoForTriggeredRule() {
- PolicyLogger.postMDCInfoForTriggeredRule("transactionId");
+ public void testPostMdcInfoForTriggeredRule() {
+ PolicyLogger.postMdcInfoForTriggeredRule("transactionId");
assertEquals("", MDC.get(MDC_REMOTE_HOST));
assertEquals("transactionId", MDC.get(MDC_KEY_REQUEST_ID));
}
@Test
- public void testPostMDCUUIDForTriggeredRule() {
- PolicyLogger.postMDCUUIDForTriggeredRule(1);
+ public void testPostMdcUuidForTriggeredRule() {
+ PolicyLogger.postMdcUuidForTriggeredRule(1);
assertEquals("", MDC.get(MDC_REMOTE_HOST));
assertEquals("1", MDC.get(MDC_KEY_REQUEST_ID));
@Test
public void testInfoMessageCodesStringStringArray() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
PolicyLogger.info(MessageCodes.ERROR_DATA_ISSUE, "str1", "str2");
Mockito.verify(mockLogger).info(MessageCodes.ERROR_DATA_ISSUE, "str2");
}
@Test
public void testInfoStringString() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
PolicyLogger.info("str1", "str2");
Mockito.verify(mockLogger).info(MessageCodes.GENERAL_INFO, "str2");
}
@Test
public void testInfoObject() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
PolicyLogger.info("str1");
Mockito.verify(mockLogger).info(MessageCodes.GENERAL_INFO, "str1");
}
@Test
public void testInfoMessageCodesThrowableStringArray() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger);
+ Whitebox.setInternalState(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"));
@Test
public void testInfoMessageCodesStringThrowableStringArray() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
PolicyLogger.info(MessageCodes.ERROR_DATA_ISSUE, "PolicyLoggerTest", new NullPointerException(), "str1",
"str2");
Mockito.verify(mockLogger).info((MessageCodes) Mockito.any(),
@Test
public void testWarnMessageCodesStringStringArray() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
PolicyLogger.warn(MessageCodes.ERROR_DATA_ISSUE, "str1");
Mockito.verify(mockLogger).warn(MessageCodes.ERROR_DATA_ISSUE);
}
@Test
public void testWarnStringString() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
PolicyLogger.warn("str1", "str2");
Mockito.verify(mockLogger).warn(MessageCodes.GENERAL_INFO, "str2");
}
@Test
public void testWarnObject() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
PolicyLogger.warn(1);
Mockito.verify(mockLogger).warn(MessageCodes.GENERAL_WARNING, "1");
}
@Test
public void testWarnMessageCodesThrowableStringArray() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger);
+ Whitebox.setInternalState(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"));
@Test
public void testWarnMessageCodesStringThrowableStringArray() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
PolicyLogger.warn(MessageCodes.ERROR_DATA_ISSUE, "PolicyLoggerTest", new NullPointerException(), "str1",
"str2");
Mockito.verify(mockLogger).warn((MessageCodes) Mockito.any(),
@Test
public void testWarnString() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
PolicyLogger.warn("str1");
Mockito.verify(mockLogger).warn(MessageCodes.GENERAL_WARNING, "str1");
}
@Test
public void testErrorStringString() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "errorLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "errorLogger", mockLogger);
PolicyLogger.error("str1", "str2");
Mockito.verify(mockLogger).error(MessageCodes.GENERAL_ERROR, "str2");
assertEquals("POLICY-515E", MDC.get("ErrorCode"));
@Test
public void testErrorString() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "errorLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "errorLogger", mockLogger);
PolicyLogger.error("str1");
Mockito.verify(mockLogger).error(MessageCodes.GENERAL_ERROR, "str1");
assertEquals("ERROR", MDC.get("ErrorCategory"));
@Test
public void testErrorObject() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "errorLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "errorLogger", mockLogger);
PolicyLogger.error(1);
Mockito.verify(mockLogger).error(MessageCodes.GENERAL_ERROR, "1");
assertEquals("ERROR", MDC.get("ErrorCategory"));
@Test
public void testErrorMessageCodesThrowableStringArray() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "errorLogger", mockLogger);
+ Whitebox.setInternalState(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"));
@Test
public void testErrorMessageCodesStringThrowableStringArray() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "errorLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "errorLogger", mockLogger);
PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "PolicyLoggerTest", new NullPointerException(), "str1",
"str2");
Mockito.verify(mockLogger).error((MessageCodes) Mockito.any(),
@Test
public void testErrorMessageCodesStringArray() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "errorLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "errorLogger", mockLogger);
PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "str1", "str2");
Mockito.verify(mockLogger).error(MessageCodes.ERROR_DATA_ISSUE, "str1", "str2");
}
@Test
public void testDebugMessageCodesStringArray() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
PolicyLogger.debug(MessageCodes.ERROR_DATA_ISSUE, "str1", "str2");
Mockito.verify(mockLogger).debug(MessageCodes.ERROR_DATA_ISSUE, "str1", "str2");
}
@Test
public void testDebugStringString() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
PolicyLogger.debug("str1", "str2");
Mockito.verify(mockLogger).debug(MessageCodes.GENERAL_INFO, "str2");
}
@Test
public void testDebugString() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
PolicyLogger.debug("str1");
Mockito.verify(mockLogger).debug("str1");
}
@Test
public void testDebugObject() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
PolicyLogger.debug(1);
Mockito.verify(mockLogger).debug("1");
}
@Test
public void testAuditStringObject() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "auditLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "auditLogger", mockLogger);
PolicyLogger.audit("PolicyLoggerTest", 1);
assertEquals("PolicyLoggerTest", MDC.get("ClassName"));
assertEquals("COMPLETE", MDC.get("StatusCode"));
@Test
public void testAuditObject() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "auditLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "auditLogger", mockLogger);
PolicyLogger.audit(1);
assertEquals("", MDC.get("ClassName"));
assertEquals("COMPLETE", MDC.get("StatusCode"));
@Test
public void testDebugMessageCodesThrowableStringArray() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger);
+ Whitebox.setInternalState(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"));
@Test
public void testDebugMessageCodesStringThrowableStringArray() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
PolicyLogger.debug(MessageCodes.ERROR_DATA_ISSUE, "PolicyLoggerTest", new NullPointerException(), "str1",
"str2");
Mockito.verify(mockLogger).debug((MessageCodes) Mockito.any(),
@Test
public void testIsDebugEnabled() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
Mockito.when(mockLogger.isDebugEnabled()).thenReturn(false).thenReturn(true);
assertFalse(PolicyLogger.isDebugEnabled());
assertTrue(PolicyLogger.isDebugEnabled());
@Test
public void testIsErrorEnabled() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "errorLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "errorLogger", mockLogger);
Mockito.when(mockLogger.isErrorEnabled()).thenReturn(false).thenReturn(true);
assertFalse(PolicyLogger.isErrorEnabled());
assertTrue(PolicyLogger.isErrorEnabled());
@Test
public void testIsWarnEnabled() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
Mockito.when(mockLogger.isWarnEnabled()).thenReturn(false).thenReturn(true);
assertFalse(PolicyLogger.isWarnEnabled());
assertTrue(PolicyLogger.isWarnEnabled());
@Test
public void testIsInfoEnabled1() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
Mockito.when(mockLogger.isInfoEnabled()).thenReturn(false).thenReturn(true);
assertFalse(PolicyLogger.isInfoEnabled1());
assertTrue(PolicyLogger.isInfoEnabled1());
@Test
public void testIsAuditEnabled() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
Mockito.when(mockLogger.isInfoEnabled()).thenReturn(false).thenReturn(true);
assertFalse(PolicyLogger.isAuditEnabled());
assertTrue(PolicyLogger.isAuditEnabled());
@Test
public void testIsInfoEnabled() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
Mockito.when(mockLogger.isInfoEnabled()).thenReturn(false).thenReturn(true);
assertFalse(PolicyLogger.isInfoEnabled());
assertTrue(PolicyLogger.isInfoEnabled());
@Test
public void testTraceStringString() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
PolicyLogger.trace("str1", "str2");
Mockito.verify(mockLogger).trace(MessageCodes.GENERAL_INFO, "str2");
}
@Test
public void testTraceObject() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
PolicyLogger.trace(1);
Mockito.verify(mockLogger).trace("1");
}
}
@Test
- public void testRecordAuditEventStartAndEndUUID() {
+ public void testRecordAuditEventStartAndEndUuid() {
UUID uuid = UUID.randomUUID();
PolicyLogger.recordAuditEventStart(uuid);;
assertNotNull(PolicyLogger.getEventTracker().getEventInfo().get(uuid.toString()));
}
@Test
- public void testRecordAuditEventEndUUIDStringString() {
+ public void testRecordAuditEventEndUuidStringString() {
UUID uuid = UUID.randomUUID();
PolicyLogger.recordAuditEventStart(uuid);;
assertNotNull(PolicyLogger.getEventTracker().getEventInfo().get(uuid.toString()));
}
@Test
- public void testCreatAuditEventTrackingRecordUUIDString() {
+ public void testCreatAuditEventTrackingRecordUuidString() {
UUID uuid = UUID.randomUUID();
PolicyLogger.recordAuditEventStart(uuid);;
assertNotNull(PolicyLogger.getEventTracker().getEventInfo().get(uuid.toString()));
}
@Test
- public void testRecordMetricEventUUIDString() {
+ public void testRecordMetricEventUuidString() {
UUID uuid = UUID.randomUUID();
PolicyLogger.recordMetricEvent(uuid, "str1");
assertEquals(uuid.toString(), MDC.get(MDC_KEY_REQUEST_ID));
@Test
public void testRecordMetricEventString() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "metricsLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "metricsLogger", mockLogger);
PolicyLogger.recordMetricEvent("eventId");
Mockito.verify(mockLogger).info(Mockito.eq(MessageCodes.RULE_METRICS_INFO), Mockito.anyString(),
Mockito.eq("eventId"));
@Test
public void testMetricsString() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "metricsLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "metricsLogger", mockLogger);
PolicyLogger.metrics("str1");
Mockito.verify(mockLogger).info(Mockito.eq(MessageCodes.RULE_METRICS_INFO), Mockito.anyString(),
Mockito.eq("str1"));
@Test
public void testMetricsStringObject() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "metricsLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "metricsLogger", mockLogger);
PolicyLogger.metrics("PolicyLoggerTest", 1);
Mockito.verify(mockLogger).info(Mockito.eq(MessageCodes.RULE_METRICS_INFO), Mockito.anyString(),
Mockito.eq("1"));
@Test
public void testMetricsObject() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "metricsLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "metricsLogger", mockLogger);
PolicyLogger.metrics(1);
Mockito.verify(mockLogger).info(Mockito.eq(MessageCodes.RULE_METRICS_INFO), Mockito.anyString(),
Mockito.eq("1"));
@Test
public void testMetricsPrintln() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "metricsLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "metricsLogger", mockLogger);
PolicyLogger.metricsPrintln("str1");
Mockito.verify(mockLogger).info("str1");
}
* 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.
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
-import static org.onap.policy.common.logging.util.TestUtils.overrideStaticField;
import com.att.eelf.configuration.EELFLogger;
-
import java.util.UUID;
-
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;
public class EelfLoggerTest {
@Test
public void testDebugObject() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
eelfLogger.debug("message");
Mockito.verify(mockLogger).debug(MessageCodes.GENERAL_INFO, "message");
}
@Test
public void testErrorObject() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "errorLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "errorLogger", mockLogger);
eelfLogger.error("message");
Mockito.verify(mockLogger).error(MessageCodes.GENERAL_ERROR, "message");
}
@Test
public void testInfoObject() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
eelfLogger.info("message");
Mockito.verify(mockLogger).info(MessageCodes.GENERAL_INFO, "message");
}
@Test
public void testWarnObject() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
eelfLogger.warn("message");
Mockito.verify(mockLogger).warn(MessageCodes.GENERAL_INFO, "message");
}
@Test
public void testTraceObject() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
eelfLogger.trace("message");
Mockito.verify(mockLogger).trace(MessageCodes.GENERAL_INFO, "message");
}
@Test
public void testIsDebugEnabled() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
Mockito.when(mockLogger.isDebugEnabled()).thenReturn(false).thenReturn(true);
assertFalse(eelfLogger.isDebugEnabled());
assertTrue(eelfLogger.isDebugEnabled());
@Test
public void testIsInfoEnabled() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
Mockito.when(mockLogger.isInfoEnabled()).thenReturn(false).thenReturn(true);
assertFalse(eelfLogger.isInfoEnabled());
assertTrue(eelfLogger.isInfoEnabled());
@Test
public void testIsWarnEnabled() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
Mockito.when(mockLogger.isWarnEnabled()).thenReturn(false).thenReturn(true);
assertFalse(eelfLogger.isWarnEnabled());
assertTrue(eelfLogger.isWarnEnabled());
@Test
public void testIsErrorEnabled() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "errorLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "errorLogger", mockLogger);
Mockito.when(mockLogger.isErrorEnabled()).thenReturn(false).thenReturn(true);
assertFalse(eelfLogger.isErrorEnabled());
assertTrue(eelfLogger.isErrorEnabled());
@Test
public void testIsTraceEnabled() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
Mockito.when(mockLogger.isDebugEnabled()).thenReturn(false).thenReturn(true);
assertFalse(eelfLogger.isTraceEnabled());
assertTrue(eelfLogger.isTraceEnabled());
@Test
public void testDebugObjectThrowable() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
eelfLogger.debug("message", new NullPointerException());
Mockito.verify(mockLogger).debug((MessageCodes) Mockito.any(),
Mockito.startsWith("message:java.lang.NullPointerException"));
@Test
public void testErrorObjectThrowable() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "errorLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "errorLogger", mockLogger);
eelfLogger.error("message", new NullPointerException());
Mockito.verify(mockLogger).error((MessageCodes) Mockito.any(),
Mockito.startsWith("message:java.lang.NullPointerException"));
@Test
public void testInfoObjectThrowable() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
eelfLogger.info("message", new NullPointerException());
Mockito.verify(mockLogger).info((MessageCodes) Mockito.any(),
Mockito.startsWith("message:java.lang.NullPointerException"));
@Test
public void testWarnObjectThrowable() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
eelfLogger.warn("message", new NullPointerException());
Mockito.verify(mockLogger).warn((MessageCodes) Mockito.any(),
Mockito.startsWith("message:java.lang.NullPointerException"));
@Test
public void testTraceObjectThrowable() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
eelfLogger.trace("message", new NullPointerException());
Mockito.verify(mockLogger).trace("message");
}
@Test
public void testAuditObjectThrowable() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "auditLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "auditLogger", mockLogger);
eelfLogger.audit("message", new NullPointerException());
Mockito.verify(mockLogger).info("message");
}
}
@Test
- public void testRecordAuditEventStartUUID() {
+ public void testRecordAuditEventStartUuid() {
UUID uuid = UUID.randomUUID();
eelfLogger.recordAuditEventStart(uuid);
assertNotNull(PolicyLogger.getEventTracker().getEventInfo().get(uuid.toString()));
}
@Test
- public void testRecordAuditEventEndUUIDStringString() {
+ public void testRecordAuditEventEndUuidStringString() {
UUID uuid = UUID.randomUUID();
eelfLogger.recordAuditEventStart(uuid);;
assertNotNull(PolicyLogger.getEventTracker().getEventInfo().get(uuid.toString()));
}
@Test
- public void testRecordAuditEventEndUUIDString() {
+ public void testRecordAuditEventEndUuidString() {
UUID uuid = UUID.randomUUID();
eelfLogger.recordAuditEventStart(uuid);;
assertNotNull(PolicyLogger.getEventTracker().getEventInfo().get(uuid.toString()));
}
@Test
- public void testRecordMetricEventUUIDString() {
+ public void testRecordMetricEventUuidString() {
UUID uuid = UUID.randomUUID();
eelfLogger.recordMetricEvent(uuid, "str2");
assertEquals(uuid.toString(), MDC.get(MDC_KEY_REQUEST_ID));
@Test
public void testMetrics() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "metricsLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "metricsLogger", mockLogger);
eelfLogger.metrics(1);
Mockito.verify(mockLogger).info(Mockito.eq(MessageCodes.RULE_METRICS_INFO), Mockito.anyString(),
Mockito.eq("1"));
@Test
public void testErrorMessageCodesThrowableStringArray() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "errorLogger", mockLogger);
+ Whitebox.setInternalState(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"));
@Test
public void testErrorMessageCodesStringArray() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "errorLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "errorLogger", mockLogger);
eelfLogger.error(MessageCodes.GENERAL_ERROR, "str1", "str2");
Mockito.verify(mockLogger).error(MessageCodes.GENERAL_ERROR, "str1", "str2");
}
@Test
- public void testPostMDCInfoForEventString() {
- eelfLogger.postMDCInfoForEvent("transactionId");
+ public void testPostMdcInfoForEventString() {
+ eelfLogger.postMdcInfoForEvent("transactionId");
assertEquals("transactionId", MDC.get(MDC_KEY_REQUEST_ID));
}
@Test
public void testWarnMessageCodesStringArray() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger);
+ Whitebox.setInternalState(PolicyLogger.class, "debugLogger", mockLogger);
eelfLogger.warn(MessageCodes.GENERAL_ERROR, "str1", "str2");
Mockito.verify(mockLogger).warn(MessageCodes.GENERAL_ERROR, "str1", "str2");
}
@Test
public void testWarnMessageCodesThrowableStringArray() {
EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- overrideStaticField(PolicyLogger.class, "debugLogger", mockLogger);
+ Whitebox.setInternalState(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"));
}
@Test
- public void testPostMDCInfoForTriggeredRule() {
- eelfLogger.postMDCInfoForTriggeredRule("transactionId");
+ public void testPostMdcInfoForTriggeredRule() {
+ eelfLogger.postMdcInfoForTriggeredRule("transactionId");
assertEquals("transactionId", MDC.get(MDC_KEY_REQUEST_ID));
}
@Test
- public void testPostMDCInfoForEventObject() {
- eelfLogger.postMDCInfoForEvent(1);
+ public void testPostMDdcInfoForEventObject() {
+ eelfLogger.postMdcInfoForEvent(1);
assertEquals("1", MDC.get(MDC_KEY_REQUEST_ID));
}
* 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.
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertSame;
-import static org.onap.policy.common.logging.util.TestUtils.overrideStaticField;
import java.io.IOException;
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;
public class FlexLoggerTest {
@Test
public void testGetLoggerClassOfQEelf() {
- overrideStaticField(FlexLogger.class, "loggerType", LoggerType.EELF);
+ Whitebox.setInternalState(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() {
- overrideStaticField(FlexLogger.class, "loggerType", LoggerType.LOG4J);
+ Whitebox.setInternalState(FlexLogger.class, "loggerType", LoggerType.LOG4J);
Logger logger = FlexLogger.getLogger(this.getClass());
assertSame(logger, FlexLogger.getLogger(this.getClass()));
}
@Test
public void testGetLoggerClassOfQSystemOut() {
- overrideStaticField(FlexLogger.class, "loggerType", LoggerType.SYSTEMOUT);
+ Whitebox.setInternalState(FlexLogger.class, "loggerType", LoggerType.SYSTEMOUT);
Logger logger = FlexLogger.getLogger(this.getClass());
assertSame(logger, FlexLogger.getLogger(this.getClass()));
}
@Test
public void testGetLoggerStringEelf() {
- overrideStaticField(FlexLogger.class, "loggerType", LoggerType.EELF);
+ Whitebox.setInternalState(FlexLogger.class, "loggerType", LoggerType.EELF);
Logger logger = FlexLogger.getLogger("str1");
assertSame(logger, FlexLogger.getLogger("str1"));
}
@Test
public void testGetLoggerStringLog4j() {
- overrideStaticField(FlexLogger.class, "loggerType", LoggerType.LOG4J);
+ Whitebox.setInternalState(FlexLogger.class, "loggerType", LoggerType.LOG4J);
Logger logger = FlexLogger.getLogger("str1");
assertSame(logger, FlexLogger.getLogger("str1"));
}
@Test
public void testGetLoggerStringSystemOut() {
- overrideStaticField(FlexLogger.class, "loggerType", LoggerType.SYSTEMOUT);
+ Whitebox.setInternalState(FlexLogger.class, "loggerType", LoggerType.SYSTEMOUT);
Logger logger = FlexLogger.getLogger("str1");
assertSame(logger, FlexLogger.getLogger("str1"));
}
@Test
public void testGetLoggerClassOfQBooleanEelf() {
- overrideStaticField(FlexLogger.class, "loggerType", LoggerType.EELF);
+ 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() {
- overrideStaticField(FlexLogger.class, "loggerType", LoggerType.LOG4J);
+ Whitebox.setInternalState(FlexLogger.class, "loggerType", LoggerType.LOG4J);
Logger logger = FlexLogger.getLogger(this.getClass(), true);
assertSame(logger, FlexLogger.getLogger(this.getClass(), true));
}
@Test
public void testGetLoggerClassOfQBooleanSystemOut() {
- overrideStaticField(FlexLogger.class, "loggerType", LoggerType.SYSTEMOUT);
+ Whitebox.setInternalState(FlexLogger.class, "loggerType", LoggerType.SYSTEMOUT);
Logger logger = FlexLogger.getLogger(this.getClass(), true);
assertSame(logger, FlexLogger.getLogger(this.getClass(), true));
}
@Test
public void testGetLoggerStringBooleanEelf() {
- overrideStaticField(FlexLogger.class, "loggerType", LoggerType.EELF);
+ Whitebox.setInternalState(FlexLogger.class, "loggerType", LoggerType.EELF);
Logger logger = FlexLogger.getLogger("str1", true);
assertSame(logger, FlexLogger.getLogger("str1", true));
}
@Test
public void testGetLoggerStringBooleanLog4j() {
- overrideStaticField(FlexLogger.class, "loggerType", LoggerType.LOG4J);
+ Whitebox.setInternalState(FlexLogger.class, "loggerType", LoggerType.LOG4J);
Logger logger = FlexLogger.getLogger("str1", true);
assertSame(logger, FlexLogger.getLogger("str1", true));
}
@Test
public void testGetLoggerStringBooleanSystemOut() {
- overrideStaticField(FlexLogger.class, "loggerType", LoggerType.SYSTEMOUT);
+ Whitebox.setInternalState(FlexLogger.class, "loggerType", LoggerType.SYSTEMOUT);
Logger logger = FlexLogger.getLogger("str1", true);
assertSame(logger, FlexLogger.getLogger("str1", true));
}
* 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.
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.onap.policy.common.logging.util.TestUtils;
+import org.powermock.reflect.Whitebox;
public class Logger4JTest {
@Test
public void testDebugObject() {
Logger logger = Mockito.mock(Logger.class);
- TestUtils.overrideField(Logger4J.class, logger4J, "log", logger);
+ Whitebox.setInternalState(logger4J, "log", logger);
Mockito.when(logger.isDebugEnabled()).thenReturn(true);
logger4J.setTransId("transactionId");
logger4J.debug("message");
@Test
public void testErrorObject() {
Logger logger = Mockito.mock(Logger.class);
- TestUtils.overrideField(Logger4J.class, logger4J, "log", logger);
+ 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);
- TestUtils.overrideField(Logger4J.class, logger4J, "log", logger);
+ 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);
- TestUtils.overrideField(Logger4J.class, logger4J, "log", logger);
+ 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);
- TestUtils.overrideField(Logger4J.class, logger4J, "log", logger);
+ 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);
- TestUtils.overrideField(Logger4J.class, logger4J, "log", logger);
+ 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);
- TestUtils.overrideField(Logger4J.class, logger4J, "log", logger);
+ 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);
- TestUtils.overrideField(Logger4J.class, logger4J, "log", logger);
+ 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);
- TestUtils.overrideField(Logger4J.class, logger4J, "log", logger);
+ 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);
- TestUtils.overrideField(Logger4J.class, logger4J, "log", logger);
+ Whitebox.setInternalState(logger4J, "log", logger);
logger4J.audit("str1");
Mockito.verify(logger).info("Logger4JTest|str1");
}
@Test
public void testRecordAuditEventStartString() {
Logger logger = Mockito.mock(Logger.class);
- TestUtils.overrideField(Logger4J.class, logger4J, "log", logger);
+ Whitebox.setInternalState(logger4J, "log", logger);
logger4J.recordAuditEventEnd("eventId", "rule");
Mockito.verify(logger).info("Logger4JTest|eventId:rule");
}
@Test
- public void testRecordAuditEventStartUUID() {
+ public void testRecordAuditEventStartUuid() {
Logger logger = Mockito.mock(Logger.class);
- TestUtils.overrideField(Logger4J.class, logger4J, "log", logger);
+ 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);
- TestUtils.overrideField(Logger4J.class, logger4J, "log", logger);
+ Whitebox.setInternalState(logger4J, "log", logger);
logger4J.recordAuditEventEnd("eventId", "rule", "policyVersion");
Mockito.verify(logger).info("Logger4JTest|eventId:rule");
}
@Test
- public void testRecordAuditEventEndUUIDStringString() {
+ public void testRecordAuditEventEndUuidStringString() {
Logger logger = Mockito.mock(Logger.class);
- TestUtils.overrideField(Logger4J.class, logger4J, "log", logger);
+ 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);
- TestUtils.overrideField(Logger4J.class, logger4J, "log", logger);
+ Whitebox.setInternalState(logger4J, "log", logger);
logger4J.recordAuditEventEnd("eventId", "rule");
Mockito.verify(logger).info("Logger4JTest|eventId:rule");
}
@Test
- public void testRecordAuditEventEndUUIDString() {
+ public void testRecordAuditEventEndUuidString() {
Logger logger = Mockito.mock(Logger.class);
- TestUtils.overrideField(Logger4J.class, logger4J, "log", logger);
+ 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);
- TestUtils.overrideField(Logger4J.class, logger4J, "log", logger);
+ Whitebox.setInternalState(logger4J, "log", logger);
logger4J.recordMetricEvent("eventId", "str1");
Mockito.verify(logger).info("Logger4JTest|eventId:str1");
}
@Test
- public void testRecordMetricEventUUIDString() {
+ public void testRecordMetricEventUuidString() {
Logger logger = Mockito.mock(Logger.class);
- TestUtils.overrideField(Logger4J.class, logger4J, "log", logger);
+ 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);
- TestUtils.overrideField(Logger4J.class, logger4J, "log", logger);
+ Whitebox.setInternalState(logger4J, "log", logger);
logger4J.metrics("str1");
Mockito.verify(logger).info("str1");
}
@Test
public void testErrorMessageCodesThrowableStringArray() {
Logger logger = Mockito.mock(Logger.class);
- TestUtils.overrideField(Logger4J.class, logger4J, "log", logger);
+ Whitebox.setInternalState(logger4J, "log", logger);
logger4J.setTransId("transactionId");
logger4J.error(MessageCodes.GENERAL_ERROR, new NullPointerException(), "str1", "str2");
Mockito.verify(logger)
@Test
public void testErrorMessageCodesStringArray() {
Logger logger = Mockito.mock(Logger.class);
- TestUtils.overrideField(Logger4J.class, logger4J, "log", logger);
+ Whitebox.setInternalState(logger4J, "log", logger);
logger4J.setTransId("transactionId");
logger4J.error(MessageCodes.GENERAL_ERROR, "str1", "str2");
Mockito.verify(logger)
}
@Test
- public void testPostMDCInfoForEventString() {
- String returnedTransactionId = logger4J.postMDCInfoForEvent("transactionId");
+ public void testPostMdcInfoForEventString() {
+ String returnedTransactionId = logger4J.postMdcInfoForEvent("transactionId");
assertEquals("transactionId", returnedTransactionId);
}
@Test
- public void testPostMDCInfoForEventEmptyString() {
- String returnedTransactionId = logger4J.postMDCInfoForEvent("");
+ public void testPostMdcInfoForEventEmptyString() {
+ String returnedTransactionId = logger4J.postMdcInfoForEvent("");
assertNotNull("", returnedTransactionId);
assertNotEquals("", returnedTransactionId);
}
@Test
public void testWarnMessageCodesStringArray() {
Logger logger = Mockito.mock(Logger.class);
- TestUtils.overrideField(Logger4J.class, logger4J, "log", logger);
+ 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);
- TestUtils.overrideField(Logger4J.class, logger4J, "log", logger);
+ 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);
- TestUtils.overrideField(Logger4J.class, logger4J, "log", logger);
+ Whitebox.setInternalState(logger4J, "log", logger);
logger4J.setTransId("transactionId");
Exception exception = new NullPointerException();
logger4J.debug("message", exception);
@Test
public void testErrorObjectThrowable() {
Logger logger = Mockito.mock(Logger.class);
- TestUtils.overrideField(Logger4J.class, logger4J, "log", logger);
+ Whitebox.setInternalState(logger4J, "log", logger);
logger4J.setTransId("transactionId");
Exception exception = new NullPointerException();
logger4J.error("message", exception);
@Test
public void testInfoObjectThrowable() {
Logger logger = Mockito.mock(Logger.class);
- TestUtils.overrideField(Logger4J.class, logger4J, "log", logger);
+ Whitebox.setInternalState(logger4J, "log", logger);
logger4J.setTransId("transactionId");
Exception exception = new NullPointerException();
logger4J.info("message", exception);
@Test
public void testWarnObjectThrowable() {
Logger logger = Mockito.mock(Logger.class);
- TestUtils.overrideField(Logger4J.class, logger4J, "log", logger);
+ 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);
- TestUtils.overrideField(Logger4J.class, logger4J, "log", logger);
+ 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);
- TestUtils.overrideField(Logger4J.class, logger4J, "log", logger);
+ 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);
- TestUtils.overrideField(Logger4J.class, logger4J, "log", logger);
+ Whitebox.setInternalState(logger4J, "log", logger);
logger4J.isTraceEnabled();
Mockito.verify(logger).isTraceEnabled();
}
@Test
- public void testPostMDCInfoForTriggeredRule() {
+ public void testPostMdcInfoForTriggeredRule() {
Logger logger = Mockito.mock(Logger.class);
- TestUtils.overrideField(Logger4J.class, logger4J, "log", logger);
- logger4J.postMDCInfoForTriggeredRule("transactionId");
+ Whitebox.setInternalState(logger4J, "log", logger);
+ logger4J.postMdcInfoForTriggeredRule("transactionId");
Mockito.verify(logger).info("transactionId");
}
@Test
- public void testPostMDCInfoForEventObject() {
+ public void testPostMdcInfoForEventObject() {
Logger logger = Mockito.mock(Logger.class);
- TestUtils.overrideField(Logger4J.class, logger4J, "log", logger);
- logger4J.postMDCInfoForEvent(1);
+ Whitebox.setInternalState(logger4J, "log", logger);
+ logger4J.postMdcInfoForEvent(1);
Mockito.verify(logger).info(1);
}
* 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.
}
@Test
- public void testRecordAuditEventStartUUID() {
+ public void testRecordAuditEventStartUuid() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
PrintStream old = System.out;
}
@Test
- public void testRecordAuditEventEndUUIDStringString() {
+ public void testRecordAuditEventEndUuidStringString() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
PrintStream old = System.out;
}
@Test
- public void testRecordAuditEventEndUUIDString() {
+ public void testRecordAuditEventEndUuidString() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
PrintStream old = System.out;
}
@Test
- public void testRecordMetricEventUUIDString() {
+ public void testRecordMetricEventUuidString() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
PrintStream old = System.out;
}
@Test
- public void testPostMDCInfoForEventString() {
- assertEquals("transactionId", systemOutLogger.postMDCInfoForEvent("transactionId"));
+ public void testPostMdcInfoForEventString() {
+ assertEquals("transactionId", systemOutLogger.postMdcInfoForEvent("transactionId"));
}
@Test
}
@Test
- public void testPostMDCInfoForTriggeredRule() {
+ public void testPostMdcInfoForTriggeredRule() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
PrintStream old = System.out;
try {
System.setOut(ps);
- systemOutLogger.postMDCInfoForTriggeredRule("transactionId");
+ systemOutLogger.postMdcInfoForTriggeredRule("transactionId");
assertTrue(baos.toString(), baos.toString().contains("transactionId"));
} finally {
System.out.flush();
}
@Test
- public void testPostMDCInfoForEventObject() {
+ public void testPostMdcInfoForEventObject() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
PrintStream old = System.out;
try {
System.setOut(ps);
- systemOutLogger.postMDCInfoForEvent(1);
+ systemOutLogger.postMdcInfoForEvent(1);
assertTrue(baos.toString(), baos.toString().contains("1"));
} finally {
System.out.flush();
+++ /dev/null
-/*-
- * ============LICENSE_START=======================================================
- * ONAP-Logging
- * ================================================================================
- * Copyright (C) 2018 Ericsson. 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.util;
-
-import static org.junit.Assert.fail;
-
-import java.lang.reflect.Field;
-import java.lang.reflect.Modifier;
-
-public class TestUtils {
-
- /**
- * Override a field.
- *
- * @param clazz the class the field belongs to
- * @param object the instance of the class
- * @param fieldName the name of the field
- * @param newValue the value to set the field to
- */
- public static void overrideField(@SuppressWarnings("rawtypes") final Class clazz, final Object object,
- final String fieldName, final Object newValue) {
- try {
- final Field field = clazz.getDeclaredField(fieldName);
- field.setAccessible(true);
-
- final Field modifiersField = Field.class.getDeclaredField("modifiers");
- modifiersField.setAccessible(true);
-
- field.set(object, newValue);
- } catch (final Exception e) {
- fail(e.toString());
- }
- }
-
- /**
- * Override a static field.
- *
- * @param clazz the class the field belongs to
- * @param fieldName the name of the field
- * @param newValue the value to set the field to
- */
- public static void overrideStaticField(@SuppressWarnings("rawtypes") final Class clazz, final String fieldName,
- final Object newValue) {
- try {
- final Field field = clazz.getDeclaredField(fieldName);
- field.setAccessible(true);
-
- final Field modifiersField = Field.class.getDeclaredField("modifiers");
- modifiersField.setAccessible(true);
- modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
-
- field.set(null, newValue);
- } catch (final Exception e) {
- fail(e.toString());
- }
- }
-
-}