From 00fd66d0e738d6396527ae8c0eb1d8a8fe5c88a4 Mon Sep 17 00:00:00 2001 From: xg353y Date: Fri, 10 Aug 2018 09:28:01 +0200 Subject: Update Logging Specifications Update logging related parameters basedon the ONAP logging specification v1.2 Issue-ID: CLAMP-203, CLAMP-204, CLAMP-205 Change-Id: Ide7608e289f647862be8db6eb3d7bf11b6e7218a Signed-off-by: xg353y --- .../clds/client/DcaeHttpConnectionManager.java | 4 + .../clds/client/req/sdc/SdcCatalogServices.java | 21 ++- .../org/onap/clamp/clds/service/CldsService.java | 70 ++++--- .../clamp/clds/service/CldsTemplateService.java | 31 ++- .../org/onap/clamp/clds/util/LoggingUtils.java | 210 +++++++++++++++++++-- 5 files changed, 279 insertions(+), 57 deletions(-) (limited to 'src/main/java/org') diff --git a/src/main/java/org/onap/clamp/clds/client/DcaeHttpConnectionManager.java b/src/main/java/org/onap/clamp/clds/client/DcaeHttpConnectionManager.java index 918a267d4..bebb6703d 100644 --- a/src/main/java/org/onap/clamp/clds/client/DcaeHttpConnectionManager.java +++ b/src/main/java/org/onap/clamp/clds/client/DcaeHttpConnectionManager.java @@ -88,8 +88,10 @@ public class DcaeHttpConnectionManager { private static String doHttpQuery(URL url, String requestMethod, String payload, String contentType) throws IOException { + LoggingUtils utils = new LoggingUtils (logger); logger.info("Using HTTP URL to contact DCAE:" + url); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection = utils.invoke(connection,"DCAE", requestMethod); connection.setRequestMethod(requestMethod); connection.setRequestProperty("X-ECOMP-RequestID", LoggingUtils.getRequestId()); if (payload != null && contentType != null) { @@ -106,6 +108,7 @@ public class DcaeHttpConnectionManager { try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { String responseStr = IOUtils.toString(reader); logger.info("Response Content: " + responseStr); + utils.invokeReturn(); return responseStr; } } else { @@ -114,6 +117,7 @@ public class DcaeHttpConnectionManager { try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()))) { String responseStr = IOUtils.toString(reader); logger.error(DCAE_REQUEST_FAILED_LOG + responseStr); + utils.invokeReturn(); throw new BadRequestException(responseStr); } } diff --git a/src/main/java/org/onap/clamp/clds/client/req/sdc/SdcCatalogServices.java b/src/main/java/org/onap/clamp/clds/client/req/sdc/SdcCatalogServices.java index 240094e61..4422c92fe 100644 --- a/src/main/java/org/onap/clamp/clds/client/req/sdc/SdcCatalogServices.java +++ b/src/main/java/org/onap/clamp/clds/client/req/sdc/SdcCatalogServices.java @@ -97,6 +97,7 @@ public class SdcCatalogServices { private static final String SDC_SERVICE_URL_PROPERTY_NAME = "sdc.serviceUrl"; private static final String SDC_INSTANCE_ID_CLAMP = "CLAMP-Tool"; private static final String RESOURCE_URL_PREFIX = "resources"; + private static final LoggingUtils utils = new LoggingUtils (logger); @Autowired private ClampProperties refProp; @@ -134,7 +135,6 @@ public class SdcCatalogServices { Date startTime = new Date(); String baseUrl = refProp.getStringValue(SDC_SERVICE_URL_PROPERTY_NAME); String basicAuth = getSdcBasicAuth(); - LoggingUtils.setTargetContext("SDC", "getSdcServicesInformation"); try { String url = baseUrl; if (uuid != null && !uuid.isEmpty()) { @@ -142,6 +142,7 @@ public class SdcCatalogServices { } URL urlObj = new URL(url); HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection(); + conn = utils.invoke(conn,"SDC", "getSdcServicesInformation"); conn.setRequestProperty(refProp.getStringValue(SDC_INSTANCE_ID_PROPERTY_NAME), SDC_INSTANCE_ID_CLAMP); conn.setRequestProperty(HttpHeaders.AUTHORIZATION, basicAuth); conn.setRequestProperty(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8"); @@ -149,8 +150,7 @@ public class SdcCatalogServices { conn.setRequestMethod("GET"); String resp = getResponse(conn); logger.debug("Services list received from SDC:" + resp); - // metrics log - LoggingUtils.setResponseContext("0", "Get sdc services success", this.getClass().getName()); + utils.invokeReturn(); return resp; } catch (IOException e) { LoggingUtils.setResponseContext("900", "Get sdc services failed", this.getClass().getName()); @@ -160,6 +160,7 @@ public class SdcCatalogServices { LoggingUtils.setTimeContext(startTime, new Date()); metricsLogger.info("getSdcServicesInformation complete"); } + utils.invokeReturn(); return ""; } @@ -346,6 +347,7 @@ public class SdcCatalogServices { byte[] postData = formattedSdcReq.getBytes(StandardCharsets.UTF_8); int postDataLength = postData.length; HttpURLConnection conn = getSdcHttpUrlConnection(userid, postDataLength, url, formattedSdcReq); + conn = utils.invoke(conn,"SDC", "uploadArtifact"); try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) { wr.write(postData); } @@ -358,11 +360,14 @@ public class SdcCatalogServices { String responseStr = getResponse(conn); if (responseStr != null && requestFailed) { logger.error("requestFailed - responseStr=" + responseStr); + utils.invokeReturn(); throw new BadRequestException(responseStr); } + utils.invokeReturn(); return responseStr; } catch (IOException e) { logger.error("Exception when attempting to communicate with SDC", e); + utils.invokeReturn(); throw new SdcCommunicationException("Exception when attempting to communicate with SDC", e); } } @@ -797,6 +802,7 @@ public class SdcCatalogServices { String urlReworked = removeUnwantedBracesFromString(url); URL urlObj = new URL(urlReworked); HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection(); + conn = utils.invoke(conn,"SDC", "getSdcResources"); String basicAuth = getSdcBasicAuth(); conn.setRequestProperty(refProp.getStringValue(SDC_INSTANCE_ID_PROPERTY_NAME), SDC_INSTANCE_ID_CLAMP); conn.setRequestProperty(HttpHeaders.AUTHORIZATION, basicAuth); @@ -807,27 +813,24 @@ public class SdcCatalogServices { logger.info("Sdc resource url - " + urlReworked + " , responseCode=" + responseCode); try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) { String response = IOUtils.toString(in); - LoggingUtils.setResponseContext("0", "Get sdc resources success", this.getClass().getName()); return response; } } catch (IOException e) { - LoggingUtils.setResponseContext("900", "Get sdc resources failed", this.getClass().getName()); LoggingUtils.setErrorContext("900", "Get sdc resources error"); logger.error("Exception occurred during query to SDC", e); return ""; } catch (DecoderException e) { - LoggingUtils.setResponseContext("900", "Get sdc resources failed", this.getClass().getName()); LoggingUtils.setErrorContext("900", "Get sdc resources error"); logger.error("Exception when attempting to decode the Hex string", e); throw new SdcCommunicationException("Exception when attempting to decode the Hex string", e); } catch (GeneralSecurityException e) { - LoggingUtils.setResponseContext("900", "Get sdc resources failed", this.getClass().getName()); LoggingUtils.setErrorContext("900", "Get sdc resources error"); logger.error("Exception when attempting to decrypt the encrypted password", e); throw new SdcCommunicationException("Exception when attempting to decrypt the encrypted password", e); } finally { LoggingUtils.setTimeContext(startTime, new Date()); metricsLogger.info("getCldsServicesOrResourcesBasedOnURL completed"); + utils.invokeReturn(); } } @@ -1275,6 +1278,7 @@ public class SdcCatalogServices { url = url + "/" + uploadedArtifactUuid; URL urlObj = new URL(url); HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection(); + conn = utils.invoke(conn,"SDC", "deleteArtifact"); conn.setDoOutput(true); conn.setRequestProperty(refProp.getStringValue(SDC_INSTANCE_ID_PROPERTY_NAME), sdcXonapInstanceId); conn.setRequestProperty(HttpHeaders.AUTHORIZATION, basicAuth); @@ -1293,12 +1297,15 @@ public class SdcCatalogServices { responseStr = getResponse(conn); if (responseStr != null && requestFailed) { logger.error("requestFailed - responseStr=" + responseStr); + utils.invokeReturn(); throw new BadRequestException(responseStr); } } + utils.invokeReturn(); return responseStr; } catch (IOException | DecoderException | GeneralSecurityException e) { logger.error("Exception when attempting to communicate with SDC", e); + utils.invokeReturn(); throw new SdcCommunicationException("Exception when attempting to communicate with SDC", e); } } diff --git a/src/main/java/org/onap/clamp/clds/service/CldsService.java b/src/main/java/org/onap/clamp/clds/service/CldsService.java index 74c78aeed..2139b3d39 100644 --- a/src/main/java/org/onap/clamp/clds/service/CldsService.java +++ b/src/main/java/org/onap/clamp/clds/service/CldsService.java @@ -37,6 +37,7 @@ import java.util.List; import java.util.Optional; import java.util.UUID; +import javax.servlet.http.HttpServletRequest; import javax.ws.rs.BadRequestException; import javax.ws.rs.NotAuthorizedException; import javax.xml.transform.TransformerException; @@ -73,6 +74,8 @@ import org.onap.clamp.clds.sdc.controller.installer.CsarInstallerImpl; import org.onap.clamp.clds.transform.XslTransformer; import org.onap.clamp.clds.util.JacksonUtils; import org.onap.clamp.clds.util.LoggingUtils; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.slf4j.event.Level; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; @@ -89,6 +92,7 @@ public class CldsService extends SecureServiceBase { @Produce(uri = "direct:processSubmit") private CamelProxy camelProxy; protected static final EELFLogger securityLogger = EELFManager.getInstance().getSecurityLogger(); + protected static final EELFLogger logger = EELFManager.getInstance().getLogger(CldsService.class); public static final String GLOBAL_PROPERTIES_KEY = "files.globalProperties"; private final String cldsPersmissionTypeCl; @@ -108,7 +112,10 @@ public class CldsService extends SecureServiceBase { private final SdcCatalogServices sdcCatalogServices; private final DcaeDispatcherServices dcaeDispatcherServices; private final DcaeInventoryServices dcaeInventoryServices; + private LoggingUtils util = new LoggingUtils(logger); + @Autowired + private HttpServletRequest request; @Autowired public CldsService(CldsDao cldsDao, XslTransformer cldsBpmnTransformer, ClampProperties refProp, SdcCatalogServices sdcCatalogServices, DcaeDispatcherServices dcaeDispatcherServices, @@ -150,13 +157,13 @@ public class CldsService extends SecureServiceBase { * ClosedLoop in CLDS application. */ public List getCLDSDetails() { + util.entering(request, "CldsService: GET model details"); Date startTime = new Date(); - LoggingUtils.setRequestContext("CldsService: GET model details", getPrincipalName()); List cldsMonitoringDetailsList = cldsDao.getCLDSMonitoringDetails(); // audit log LoggingUtils.setTimeContext(startTime, new Date()); - LoggingUtils.setResponseContext("0", "Get cldsDetails success", this.getClass().getName()); auditLogger.info("GET cldsDetails completed"); + util.exiting("200", "Get cldsDetails success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); return cldsMonitoringDetailsList; } @@ -165,8 +172,8 @@ public class CldsService extends SecureServiceBase { * is currently installed from pom.xml file 3. User permissions */ public CldsInfo getCldsInfo() { + util.entering(request, "CldsService: GET cldsInfo"); Date startTime = new Date(); - LoggingUtils.setRequestContext("CldsService: GET cldsInfo", getPrincipalName()); LoggingUtils.setTimeContext(startTime, new Date()); CldsInfoProvider cldsInfoProvider = new CldsInfoProvider(this); @@ -174,8 +181,8 @@ public class CldsService extends SecureServiceBase { // audit log LoggingUtils.setTimeContext(startTime, new Date()); - LoggingUtils.setResponseContext("0", "Get cldsInfo success", this.getClass().getName()); securityLogger.info("GET cldsInfo completed"); + util.exiting("200", "Get cldsInfo success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); return cldsInfo; } @@ -188,15 +195,15 @@ public class CldsService extends SecureServiceBase { * @return bpmn xml text - content of bpmn given name */ public String getBpmnXml(String modelName) { + util.entering(request, "CldsService: GET model bpmn"); Date startTime = new Date(); - LoggingUtils.setRequestContext("CldsService: GET model bpmn", getPrincipalName()); isAuthorized(permissionReadCl); logger.info("GET bpmnText for modelName={}", modelName); CldsModel model = CldsModel.retrieve(cldsDao, modelName, false); // audit log LoggingUtils.setTimeContext(startTime, new Date()); - LoggingUtils.setResponseContext("0", "Get model bpmn success", this.getClass().getName()); auditLogger.info("GET model bpmn completed"); + util.exiting("200", "Get model bpmn success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); return model.getBpmnText(); } @@ -209,15 +216,15 @@ public class CldsService extends SecureServiceBase { * @return image xml text - content of image given name */ public String getImageXml(String modelName) { + util.entering(request, "CldsService: GET model image"); Date startTime = new Date(); - LoggingUtils.setRequestContext("CldsService: GET model image", getPrincipalName()); isAuthorized(permissionReadCl); logger.info("GET imageText for modelName={}", modelName); CldsModel model = CldsModel.retrieve(cldsDao, modelName, false); // audit log LoggingUtils.setTimeContext(startTime, new Date()); - LoggingUtils.setResponseContext("0", "Get model image success", this.getClass().getName()); auditLogger.info("GET model image completed"); + util.exiting("200", "Get model image success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); return model.getImageText(); } @@ -228,8 +235,8 @@ public class CldsService extends SecureServiceBase { * @return clds model - clds model for the given model name */ public CldsModel getModel(String modelName) { + util.entering(request, "CldsService: GET model"); Date startTime = new Date(); - LoggingUtils.setRequestContext("CldsService: GET model", getPrincipalName()); isAuthorized(permissionReadCl); logger.debug("GET model for modelName={}", modelName); CldsModel cldsModel = CldsModel.retrieve(cldsDao, modelName, false); @@ -246,8 +253,8 @@ public class CldsService extends SecureServiceBase { } // audit log LoggingUtils.setTimeContext(startTime, new Date()); - LoggingUtils.setResponseContext("0", "Get model success", this.getClass().getName()); auditLogger.info("GET model completed"); + util.exiting("200", "Get model success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); return cldsModel; } @@ -257,8 +264,8 @@ public class CldsService extends SecureServiceBase { * @param modelName */ public CldsModel putModel(String modelName, CldsModel cldsModel) { + util.entering(request, "CldsService: PUT model"); Date startTime = new Date(); - LoggingUtils.setRequestContext("CldsService: PUT model", getPrincipalName()); isAuthorized(permissionUpdateCl); isAuthorizedForVf(cldsModel); logger.info("PUT model for modelName={}", modelName); @@ -272,8 +279,8 @@ public class CldsService extends SecureServiceBase { cldsModel.save(cldsDao, getUserId()); // audit log LoggingUtils.setTimeContext(startTime, new Date()); - LoggingUtils.setResponseContext("0", "Put model success", this.getClass().getName()); auditLogger.info("PUT model completed"); + util.exiting("200", "Put model success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); return cldsModel; } @@ -283,15 +290,15 @@ public class CldsService extends SecureServiceBase { * @return model names in JSON */ public List getModelNames() { + util.entering(request, "CldsService: GET model names"); Date startTime = new Date(); - LoggingUtils.setRequestContext("CldsService: GET model names", getPrincipalName()); isAuthorized(permissionReadCl); logger.info("GET list of model names"); List names = cldsDao.getBpmnNames(); // audit log LoggingUtils.setTimeContext(startTime, new Date()); - LoggingUtils.setResponseContext("0", "Get model names success", this.getClass().getName()); auditLogger.info("GET model names completed"); + util.exiting("200", "Get model names success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); return names; } @@ -329,11 +336,11 @@ public class CldsService extends SecureServiceBase { public ResponseEntity putModelAndProcessAction(String action, String modelName,String test, CldsModel model) throws TransformerException, ParseException { + util.entering(request, "CldsService: Process model action"); Date startTime = new Date(); CldsModel retrievedModel = null; Boolean errorCase = false; try { - LoggingUtils.setRequestContext("CldsService: Process model action", getPrincipalName()); String actionCd = action.toUpperCase(); SecureServicePermission permisionManage = SecureServicePermission.create(cldsPermissionTypeClManage, cldsPermissionInstance, actionCd); @@ -416,10 +423,10 @@ public class CldsService extends SecureServiceBase { } // audit log LoggingUtils.setTimeContext(startTime, new Date()); - LoggingUtils.setResponseContext("0", "Process model action success", this.getClass().getName()); auditLogger.info("Process model action completed"); } else { logger.error("CldsModel not found in database with modelName: " + modelName); + util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), "CldsModel not found in database with modelName " + "modelName", Level.INFO, ONAPLogConstants.ResponseStatus.ERROR); return new ResponseEntity("CldsModel not found in database with modelName: \" + modelName", HttpStatus.INTERNAL_SERVER_ERROR); } } catch (Exception e) { @@ -427,8 +434,10 @@ public class CldsService extends SecureServiceBase { logger.error("Exception occured during putModelAndProcessAction", e); } if (errorCase) { + util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), "putModelAndProcessAction failed", Level.INFO, ONAPLogConstants.ResponseStatus.ERROR); return new ResponseEntity<>(retrievedModel, HttpStatus.INTERNAL_SERVER_ERROR); } + util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); return new ResponseEntity<>(retrievedModel, HttpStatus.OK); } @@ -439,8 +448,8 @@ public class CldsService extends SecureServiceBase { * @param dcaeEvent */ public String postDcaeEvent(String test, DcaeEvent dcaeEvent) { + util.entering(request, "CldsService: Post dcae event"); Date startTime = new Date(); - LoggingUtils.setRequestContext("CldsService: Post dcae event", getPrincipalName()); String userid = null; // TODO: allow auth checking to be turned off by removing the permission // type property @@ -473,8 +482,8 @@ public class CldsService extends SecureServiceBase { } // audit log LoggingUtils.setTimeContext(startTime, new Date()); - LoggingUtils.setResponseContext("0", "Post dcae event success", this.getClass().getName()); auditLogger.info("Post dcae event completed"); + util.exiting("200", "Post dcae event success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); return msgInfo; } @@ -487,8 +496,8 @@ public class CldsService extends SecureServiceBase { * In case of issues with the decoding of the Hex String */ public String getSdcServices() throws GeneralSecurityException, DecoderException { + util.entering(request, "CldsService: GET sdc services"); Date startTime = new Date(); - LoggingUtils.setRequestContext("CldsService: GET sdc services", getPrincipalName()); String retStr; try { retStr = createUiServiceFormatJson(sdcCatalogServices.getSdcServicesInformation(null)); @@ -499,8 +508,8 @@ public class CldsService extends SecureServiceBase { logger.info("value of sdcServices : {}", retStr); // audit log LoggingUtils.setTimeContext(startTime, new Date()); - LoggingUtils.setResponseContext("0", "Get sdc services success", this.getClass().getName()); auditLogger.info("GET sdc services completed"); + util.exiting("200", "Get sdc services success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); return retStr; } @@ -528,8 +537,8 @@ public class CldsService extends SecureServiceBase { public String getSdcPropertiesByServiceUUIDForRefresh( String serviceInvariantUUID, Boolean refresh) throws GeneralSecurityException, DecoderException, IOException { + util.entering(request, "CldsService: GET sdc properties by uuid"); Date startTime = new Date(); - LoggingUtils.setRequestContext("CldsService: GET sdc properties by uuid", getPrincipalName()); CldsServiceData cldsServiceData = new CldsServiceData(); cldsServiceData.setServiceInvariantUUID(serviceInvariantUUID); if (!Optional.ofNullable(refresh).orElse(false)) { @@ -545,8 +554,8 @@ public class CldsService extends SecureServiceBase { String sdcProperties = sdcCatalogServices.createPropertiesObjectByUUID(cldsServiceData); // audit log LoggingUtils.setTimeContext(startTime, new Date()); - LoggingUtils.setResponseContext("0", "Get sdc properties by uuid success", this.getClass().getName()); auditLogger.info("GET sdc properties by uuid completed"); + util.exiting("200", "Get sdc properties by uuid success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); return sdcProperties; } @@ -720,8 +729,8 @@ public class CldsService extends SecureServiceBase { } public ResponseEntity deployModel(String modelName, CldsModel model) { + util.entering(request, "CldsService: Deploy model"); Date startTime = new Date(); - LoggingUtils.setRequestContext("CldsService: Deploy model", getPrincipalName()); Boolean errorCase = false; try { fillInCldsModel(model); @@ -759,27 +768,29 @@ public class CldsService extends SecureServiceBase { model.save(cldsDao, getUserId()); } else { logger.info("Deploy model (" + modelName + ") failed...Operation Status is - " + operationStatus); + util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), "DeployModel failed", Level.INFO, ONAPLogConstants.ResponseStatus.ERROR); throw new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, "Deploy model (" + modelName + ") failed...Operation Status is - " + operationStatus); } logger.info("Deploy model (" + modelName + ") succeeded...Deployment Id is - " + deploymentId); // audit log LoggingUtils.setTimeContext(startTime, new Date()); - LoggingUtils.setResponseContext("0", "Deploy model success", this.getClass().getName()); auditLogger.info("Deploy model completed"); } catch (Exception e) { errorCase = true; logger.error("Exception occured during deployModel", e); } if (errorCase) { + util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), "DeployModel failed", Level.INFO, ONAPLogConstants.ResponseStatus.ERROR); return new ResponseEntity<>(model, HttpStatus.INTERNAL_SERVER_ERROR); } + util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); return new ResponseEntity<>(model, HttpStatus.OK); } public ResponseEntity unDeployModel(String modelName, CldsModel model) { + util.entering(request, "CldsService: Undeploy model"); Date startTime = new Date(); - LoggingUtils.setRequestContext("CldsService: Undeploy model", getPrincipalName()); Boolean errorCase = false; try { SecureServicePermission permisionManage = SecureServicePermission.create(cldsPermissionTypeClManage, @@ -804,21 +815,23 @@ public class CldsService extends SecureServiceBase { model.save(cldsDao, getUserId()); } else { logger.info("Undeploy model (" + modelName + ") failed...Operation Status is - " + operationStatus); + util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), "UndeployModel failed", Level.INFO, ONAPLogConstants.ResponseStatus.ERROR); throw new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, "Undeploy model (" + modelName + ") failed...Operation Status is - " + operationStatus); } logger.info("Undeploy model (" + modelName + ") succeeded."); // audit log LoggingUtils.setTimeContext(startTime, new Date()); - LoggingUtils.setResponseContext("0", "Undeploy model success", this.getClass().getName()); auditLogger.info("Undeploy model completed"); } catch (Exception e) { errorCase = true; logger.error("Exception occured during unDeployModel", e); } if (errorCase) { + util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), "UndeployModel failed", Level.INFO, ONAPLogConstants.ResponseStatus.ERROR); return new ResponseEntity<>(model, HttpStatus.INTERNAL_SERVER_ERROR); } + util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); return new ResponseEntity<>(model, HttpStatus.OK); } @@ -858,4 +871,9 @@ public class CldsService extends SecureServiceBase { cldsDao.insEvent(cldsModelName, cldsControlNamePrfx, null, newEvent); } } + + // Created for the integration test + public void setLoggingUtil (LoggingUtils utilP) { + util = utilP; + } } \ No newline at end of file diff --git a/src/main/java/org/onap/clamp/clds/service/CldsTemplateService.java b/src/main/java/org/onap/clamp/clds/service/CldsTemplateService.java index 276670e2b..cca0afded 100644 --- a/src/main/java/org/onap/clamp/clds/service/CldsTemplateService.java +++ b/src/main/java/org/onap/clamp/clds/service/CldsTemplateService.java @@ -27,11 +27,14 @@ import java.util.Date; import java.util.List; import javax.annotation.PostConstruct; +import javax.servlet.http.HttpServletRequest; import org.onap.clamp.clds.dao.CldsDao; import org.onap.clamp.clds.model.CldsTemplate; import org.onap.clamp.clds.model.ValueItem; import org.onap.clamp.clds.util.LoggingUtils; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.slf4j.event.Level; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @@ -48,6 +51,8 @@ public class CldsTemplateService extends SecureServiceBase { private String cldsPermissionInstance; private SecureServicePermission permissionReadTemplate; private SecureServicePermission permissionUpdateTemplate; + @Autowired + private HttpServletRequest request; @PostConstruct private final void afterConstruction() { @@ -59,6 +64,7 @@ public class CldsTemplateService extends SecureServiceBase { @Autowired private CldsDao cldsDao; + private LoggingUtils util = new LoggingUtils(logger); /** * REST service that retrieves BPMN for a CLDS template name from the @@ -69,15 +75,15 @@ public class CldsTemplateService extends SecureServiceBase { * @return bpmn xml text - content of bpmn given name */ public String getBpmnTemplate(String templateName) { + util.entering(request, "CldsTemplateService: GET template bpmn"); Date startTime = new Date(); - LoggingUtils.setRequestContext("CldsTemplateService: GET template bpmn", getPrincipalName()); isAuthorized(permissionReadTemplate); logger.info("GET bpmnText for templateName=" + templateName); CldsTemplate template = CldsTemplate.retrieve(cldsDao, templateName, false); // audit log LoggingUtils.setTimeContext(startTime, new Date()); - LoggingUtils.setResponseContext("0", "Get template bpmn success", this.getClass().getName()); auditLogger.info("GET template bpmn completed"); + util.exiting("200", "Get template bpmn success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); return template.getBpmnText(); } @@ -90,15 +96,15 @@ public class CldsTemplateService extends SecureServiceBase { * @return image xml text - content of image given name */ public String getImageXml(String templateName) { + util.entering(request, "CldsTemplateService: GET template image"); Date startTime = new Date(); - LoggingUtils.setRequestContext("CldsTemplateService: GET template image", getPrincipalName()); isAuthorized(permissionReadTemplate); logger.info("GET imageText for templateName=" + templateName); CldsTemplate template = CldsTemplate.retrieve(cldsDao, templateName, false); // audit log LoggingUtils.setTimeContext(startTime, new Date()); - LoggingUtils.setResponseContext("0", "Get template image success", this.getClass().getName()); auditLogger.info("GET template image completed"); + util.exiting("200", "Get template image success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); return template.getImageText(); } @@ -109,16 +115,16 @@ public class CldsTemplateService extends SecureServiceBase { * @return clds template - clds template for the given template name */ public CldsTemplate getTemplate(String templateName) { + util.entering(request, "CldsTemplateService: GET template"); Date startTime = new Date(); - LoggingUtils.setRequestContext("CldsTemplateService: GET template", getPrincipalName()); isAuthorized(permissionReadTemplate); logger.info("GET model for templateName=" + templateName); CldsTemplate template = CldsTemplate.retrieve(cldsDao, templateName, false); template.setUserAuthorizedToUpdate(isAuthorizedNoException(permissionUpdateTemplate)); // audit log LoggingUtils.setTimeContext(startTime, new Date()); - LoggingUtils.setResponseContext("0", "Get template success", this.getClass().getName()); auditLogger.info("GET template completed"); + util.exiting("200", "Get template success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); return template; } @@ -130,8 +136,8 @@ public class CldsTemplateService extends SecureServiceBase { * @return The CldsTemplate modified and saved in DB */ public CldsTemplate putTemplate(String templateName, CldsTemplate cldsTemplate) { + util.entering(request, "CldsTemplateService: PUT template"); Date startTime = new Date(); - LoggingUtils.setRequestContext("CldsTemplateService: PUT template", getPrincipalName()); isAuthorized(permissionUpdateTemplate); logger.info("PUT Template for templateName=" + templateName); logger.info("PUT bpmnText=" + cldsTemplate.getBpmnText()); @@ -141,8 +147,8 @@ public class CldsTemplateService extends SecureServiceBase { cldsTemplate.save(cldsDao, null); // audit log LoggingUtils.setTimeContext(startTime, new Date()); - LoggingUtils.setResponseContext("0", "Put template success", this.getClass().getName()); auditLogger.info("PUT template completed"); + util.exiting("200", "Put template success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); return cldsTemplate; } @@ -152,15 +158,20 @@ public class CldsTemplateService extends SecureServiceBase { * @return template names in JSON */ public List getTemplateNames() { + util.entering(request, "CldsTemplateService: GET template names"); Date startTime = new Date(); - LoggingUtils.setRequestContext("CldsTemplateService: GET template names", getPrincipalName()); isAuthorized(permissionReadTemplate); logger.info("GET list of template names"); List names = cldsDao.getTemplateNames(); // audit log LoggingUtils.setTimeContext(startTime, new Date()); - LoggingUtils.setResponseContext("0", "Get template names success", this.getClass().getName()); auditLogger.info("GET template names completed"); + util.exiting("200", "Get template names success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); return names; } + + // Created for the integration test + public void setLoggingUtil (LoggingUtils utilP) { + util = utilP; + } } diff --git a/src/main/java/org/onap/clamp/clds/util/LoggingUtils.java b/src/main/java/org/onap/clamp/clds/util/LoggingUtils.java index 71835fa10..a20a70040 100644 --- a/src/main/java/org/onap/clamp/clds/util/LoggingUtils.java +++ b/src/main/java/org/onap/clamp/clds/util/LoggingUtils.java @@ -23,6 +23,10 @@ package org.onap.clamp.clds.util; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import java.net.HttpURLConnection; import java.net.InetAddress; import java.net.UnknownHostException; import java.text.DateFormat; @@ -30,26 +34,42 @@ import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import java.util.UUID; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; import javax.validation.constraints.NotNull; +import javax.servlet.http.HttpServletRequest; + import org.slf4j.MDC; +import org.slf4j.event.Level; +import org.springframework.security.core.context.SecurityContextHolder; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; +import org.onap.clamp.clds.service.DefaultUserNameHandler; +import org.onap.logging.ref.slf4j.ONAPLogConstants; /** * This class handles the special info that appear in the log, like RequestID, * time context, ... */ -public final class LoggingUtils { - - protected static final EELFLogger logger = EELFManager.getInstance().getLogger(LoggingUtils.class); +public class LoggingUtils { + protected static final EELFLogger logger = EELFManager.getInstance().getLogger(LoggingUtils.class); private static final DateFormat DATE_FORMAT = createDateFormat(); + /** String constant for messages ENTERING, EXITING, etc. */ + private static final String EMPTY_MESSAGE = ""; + private static final String INVOCATIONID_OUT = "InvocationIDOut"; + private static final String TARGET_ENTITY = "TargetEngity"; + + /** Logger delegate. */ + private EELFLogger mLogger; + /** Automatic UUID, overrideable per adapter or per invocation. */ + private static UUID sInstanceUUID = UUID.randomUUID(); /** - * Private constructor to avoid creating instances of util class. + * Constructor */ - private LoggingUtils() { + public LoggingUtils(final EELFLogger loggerP) { + this.mLogger = checkNotNull(loggerP); } /** @@ -65,10 +85,10 @@ public final class LoggingUtils { //Defaulting to HTTP/1.1 protocol MDC.put("Protocol", "HTTP/1.1"); try { - MDC.put("ServerFQDN", InetAddress.getLocalHost().getCanonicalHostName()); - MDC.put("ServerIPAddress", InetAddress.getLocalHost().getHostAddress()); + MDC.put("ServerFQDN", InetAddress.getLocalHost().getCanonicalHostName()); + MDC.put("ServerIPAddress", InetAddress.getLocalHost().getHostAddress()); } catch (UnknownHostException e) { - logger.error("Failed to initiate setRequestContext", e); + logger.error("Failed to initiate setRequestContext", e); } } @@ -132,12 +152,10 @@ public final class LoggingUtils { * @return A string with the request ID */ public static String getRequestId() { - String requestId; - - requestId = (String) MDC.get("RequestID"); + String requestId = (String) MDC.get(ONAPLogConstants.MDCs.REQUEST_ID); if (requestId == null || requestId.isEmpty()) { requestId = UUID.randomUUID().toString(); - MDC.put("RequestId", requestId); + MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, requestId); } return requestId; } @@ -147,5 +165,169 @@ public final class LoggingUtils { dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); return dateFormat; } + + + + /********************************************************************************************* + * Method for ONAP Application Logging Specification v1.2 + ********************************************************************************************/ + + /** + * Report ENTERING marker. + * + * @param request non-null incoming request (wrapper). + * @return this. + */ + public void entering(HttpServletRequest request, String serviceName) { + checkNotNull(request); + // Extract MDC values from standard HTTP headers. + final String requestID = defaultToUUID(request.getHeader(ONAPLogConstants.Headers.REQUEST_ID)); + final String invocationID = defaultToUUID(request.getHeader(ONAPLogConstants.Headers.INVOCATION_ID)); + final String partnerName = defaultToEmpty(request.getHeader(ONAPLogConstants.Headers.PARTNER_NAME)); + + // Default the partner name to the user name used to login to clamp + if (partnerName.equalsIgnoreCase(EMPTY_MESSAGE)) { + MDC.put(ONAPLogConstants.MDCs.PARTNER_NAME, new DefaultUserNameHandler().retrieveUserName(SecurityContextHolder.getContext())); + } + + // Set standard MDCs. Override this entire method if you want to set + // others, OR set them BEFORE or AFTER the invocation of #entering, + // depending on where you need them to appear, OR extend the + // ServiceDescriptor to add them. + MDC.put(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP, + ZonedDateTime.now(ZoneOffset.UTC) + .format(DateTimeFormatter.ISO_INSTANT)); + MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, requestID); + MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, invocationID); + MDC.put(ONAPLogConstants.MDCs.CLIENT_IP_ADDRESS, defaultToEmpty(request.getRemoteAddr())); + MDC.put(ONAPLogConstants.MDCs.SERVER_FQDN, defaultToEmpty(request.getServerName())); + MDC.put(ONAPLogConstants.MDCs.INSTANCE_UUID, defaultToEmpty(sInstanceUUID)); + + // Default the service name to the requestURI, in the event that + // no value has been provided. + if (serviceName == null || + serviceName.equalsIgnoreCase(EMPTY_MESSAGE)) { + MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, request.getRequestURI()); + } + + this.mLogger.info("ENTRY"); + } + + /** + * Report EXITING marker. + * + * @return this. + */ + public void exiting(String code, String descrption, Level severity, ONAPLogConstants.ResponseStatus status) { + try { + MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE, defaultToEmpty(code)); + MDC.put(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION, defaultToEmpty(descrption)); + MDC.put(ONAPLogConstants.MDCs.RESPONSE_SEVERITY, defaultToEmpty(severity)); + MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, defaultToEmpty(status)); + this.mLogger.info("EXIT"); + } + finally { + MDC.clear(); + } + } + + /** + * Report pending invocation with INVOKE marker, + * setting standard ONAP logging headers automatically. + * + * @param builder request builder, for setting headers. + * @param sync whether synchronous, nullable. + * @return invocation ID to be passed with invocation. + */ + public HttpURLConnection invoke(final HttpURLConnection con, String targetEntity, String targetServiceName) { + final String invocationID = UUID.randomUUID().toString(); + + // Set standard HTTP headers on (southbound request) builder. + con.setRequestProperty(ONAPLogConstants.Headers.REQUEST_ID, + defaultToEmpty(MDC.get(ONAPLogConstants.MDCs.REQUEST_ID))); + con.setRequestProperty(ONAPLogConstants.Headers.INVOCATION_ID, + invocationID); + con.setRequestProperty(ONAPLogConstants.Headers.PARTNER_NAME, + defaultToEmpty(MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME))); + + invokeContext(targetEntity, targetServiceName, invocationID); + + // Log INVOKE*, with the invocationID as the message body. + // (We didn't really want this kind of behavior in the standard, + // but is it worse than new, single-message MDC?) + this.mLogger.info("INVOKE"); + this.mLogger.info("INVOKE-" + ONAPLogConstants.InvocationMode.SYNCHRONOUS.toString() + "{"+ invocationID +"}"); + return con; + } + public void invokeReturn() { + // Add the Invoke-return marker and clear the needed MDC + this.mLogger.info("INVOKE-RETURN"); + invokeReturnContext(); + } + + /** + * Dependency-free nullcheck. + * + * @param in to be checked. + * @param argument (and return) type. + * @return input arg. + */ + private static T checkNotNull(final T in) { + if (in == null) { + throw new NullPointerException(); + } + return in; + } + + /** + * Dependency-free string default. + * + * @param in to be filtered. + * @return input string or null. + */ + private static String defaultToEmpty(final Object in) { + if (in == null) { + return ""; + } + return in.toString(); + } + + /** + * Dependency-free string default. + * + * @param in to be filtered. + * @return input string or null. + */ + private static String defaultToUUID(final String in) { + if (in == null) { + return UUID.randomUUID().toString(); + } + return in; + } + + /** + * Set target related logging variables in thread local data via MDC + * + * @param targetEntity Target entity (an external/sub component, for ex. "sdc") + * @param targetServiceName Target service name (name of API invoked on target) + * @param invocationId The invocation ID + */ + private void invokeContext (String targetEntity, String targetServiceName, String invocationID) { + MDC.put(TARGET_ENTITY, defaultToEmpty(targetEntity)); + MDC.put(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME, defaultToEmpty(targetServiceName)); + MDC.put(INVOCATIONID_OUT, invocationID); + MDC.put(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP, + ZonedDateTime.now(ZoneOffset.UTC) + .format(DateTimeFormatter.ISO_INSTANT)); + } + /** + * Clear target related logging variables in thread local data via MDC + * + */ + private void invokeReturnContext () { + MDC.remove(TARGET_ENTITY); + MDC.remove(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME); + MDC.remove(INVOCATIONID_OUT); + } } -- cgit 1.2.3-korg