From 00fd66d0e738d6396527ae8c0eb1d8a8fe5c88a4 Mon Sep 17 00:00:00 2001 From: xg353y Date: Fri, 10 Aug 2018 09:28:01 +0200 Subject: [PATCH] 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 --- extra/docker/clamp/config/org.onap.clamp.keyfile | 32 ---- extra/docker/clamp/config/org.onap.clamp.p12 | Bin 2611 -> 0 bytes extra/docker/clamp/config/truststoreONAPall.jks | Bin 2223 -> 0 bytes pom.xml | 6 + .../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 +++++++++++++++++++-- src/main/resources/application-noaaf.properties | 2 +- src/main/resources/application.properties | 2 +- src/main/resources/logback-default.xml | 125 ++++++------ .../org/onap/clamp/clds/it/CldsServiceItCase.java | 12 +- .../clamp/clds/it/CldsTemplateServiceItCase.java | 14 +- 14 files changed, 372 insertions(+), 157 deletions(-) delete mode 100644 extra/docker/clamp/config/org.onap.clamp.keyfile delete mode 100644 extra/docker/clamp/config/org.onap.clamp.p12 delete mode 100644 extra/docker/clamp/config/truststoreONAPall.jks diff --git a/extra/docker/clamp/config/org.onap.clamp.keyfile b/extra/docker/clamp/config/org.onap.clamp.keyfile deleted file mode 100644 index 3e131ee7..00000000 --- a/extra/docker/clamp/config/org.onap.clamp.keyfile +++ /dev/null @@ -1,32 +0,0 @@ -Bag Attributes - friendlyName: clamp@clamp.onap.org - localKeyID: 54 69 6D 65 20 31 35 33 30 36 32 36 36 37 38 32 30 31 -Key Attributes: ------BEGIN PRIVATE KEY----- -MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDHXy3ZbC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ZQKzwxu6yI2izEB7HO/UMYLy8KM5 -CyeusPv4/p4ORzQrRGM8dTpKdagqETTnxORZYvL9chqFfTY1GbqCmErJ4mlJOzny -uIDQnhmm2kn/3Ydy1QLgGc9InaPpcAB6vGqHvT4h1zbj14/WouW4D9EXTQKBgDpA -xW79UmlbKp8vSyDVd1NZghfillzZpLY83TjHpstJxycDXXdbF1oUSk5Hde6aNGz3 -szLqA997AmWiX65Wh3yaBvJbW+dYIwgs/L3R+HYPfSw2ZBO4bFs9KRGlN5LMnjKu -cYhe539DzmP0x7R1S1Gz9tY1uRGB1lswRAtUa9q5AoGAb7bNvexDAmiHAKe96j0A -tjHAYInJvvont5vdUZipsoY+RbWitsDwv5UsjuRcMkZlMydzQpU0Glc1JcnuJGCf -AEFex2V9xru1CFJQtWxD7qeIqYlYUPLZuoLVNbgtAXBAFyUjcUeXIAEg4Ti2tlvc -86nrgb7/kSLXqHV4/Ykg15s= ------END PRIVATE KEY----- diff --git a/extra/docker/clamp/config/org.onap.clamp.p12 b/extra/docker/clamp/config/org.onap.clamp.p12 deleted file mode 100644 index fd151a94ea3382d8b7944bfbdb48557a8d55ab3f..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2611 zcmY+EX*d*&7RP7CjC~1Xmn?6+#-JHxE&JH_H6kJVG8khWk{N{TvJ;9-gY3jesH~9; zLPD18TL>Z7d!KvX_udcZIp_KP&p97|2t55&5ReLir(33`6N}M~IbZ_P0E_T+6JR{u z=sEs`z(b<{FMeZ_EOek})Pof3bQAKRL`b`Rlu$tO2@L%akoCweF!_c8yt%LVu1_44m@PD? zSy}*Xf^T`#EQ=TqEJ&HmEALso>TA@7ajbz=@_sd`c{*Iin}6LiZ~o#7e&e0<4L~TU z2zbtKqY+n3r9_{u@(Hpu56V}2<2er?J)UTrq!DCbOdBl|z2mI_UF}wUDjNuo?Rm?! z*_xoJqLY-DCd|Js)m3(8Sg)M1`$5#AASFD8b0a;hX_$1&gd$QhzjUdVJ1nd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P#Q_G|UjfxBAD`oA41A6nx({D-Ezs!cXEBp;PL0HPLnQiPW8Ir-k(P|urd2F?UtCKdd}4_Wq;U1g zh91Y{cf#8+_pYs+TLOM1R(RC{27#VcOA0|kUXDN>f({r@=@(Ttri~K$0=`|$=kLD3 zq+GtLa%M+lr3~R~tXdXgG-6nS7Xq*Uz?jk7prA4IAun*1ZM5&J>g2qea^kvQ%t%1^ zuvwTNQI$;}K2ff?HTOh1Aa`9^-TH99m{myVrNSv9V)xK@ diff --git a/extra/docker/clamp/config/truststoreONAPall.jks b/extra/docker/clamp/config/truststoreONAPall.jks deleted file mode 100644 index 910f9b1eae8193d9ff03322452da744a8ed8bbc7..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2223 zcmcJQ`8U*y8^>p}W@H`bM8Oz{o(zb^E%IS&U2pSJkK6$j|BpOAO`~fl8|Shdr-*9 zUsjbI>>i>@4)Zy1dbv>okRT8n7@)y+0bX`)Wp*$OtOVf)gV{hZ8f<=%##=;~;jM;Y z9oU}hNAP{#iki(BJT~XypfZR>Oy~}Fe>xkkZyr$D^McYhvMEUF@;FZz!=SqYrM9a6 zO4iR$YBbffa>BIqhF8XXa7qQmt}glVZ#(x*aY^PRr!^As3NfTrpNcL^V#6BF&YgTJ z>Vm>*x2T*>9OEuuE_q@Pp8dxCnYGa#Q%>VgFRmG_LR6`H`B{Pxvs|jSB{go6Qn5D1 zjd0a1W(Fowqxl7GAP?v(Ku^6|(Z|7~wy*E--?K=y!^W;Ss*O4|Z2d3YE%knQTQ5td zdcmgR`QsDuyJ9a3AF}2R?{V8JEcpkmXFZXmT;(laSj|8v%sbo1I4dF)mDyjqm@~uZ zQt27;Lh(KvS=VAZ%|B`B6{Y2EOIEq9X*piXO9Vyd%`C3Ltu?gU?e3IuURVBdQ#c3P zv==_a((~O4P7G4~UYW4}p%IEM71N5Vid~2O(YxI-Q*{OI*<{?{Z0~UlD2fBYktR^sWSt>(BUDCUHk<5m+tbl$eph7~Z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9K1q z3Lh=19p-RINKo-B=D6!tlwcFx`_3oE!q!9CVdcJg^v5-0sDi(rWeDHW91@PPJ^2Nl zYwLpmF7DtrU3rF$WVeaOT-~SsYUE#_N%U;rm$OFTWGZSDZnfv+i=z@aI!zvz=X`F) zjwWOD986$;_mX&PmU?#9$_a0Zas*rH3fB}|L^?k|eW^GZy>_`I0_b5WFT9+pt#_DF z8MeivzUXT2P-ZdNmy=IUdug%<8ygjazU{XOOh$9-U}P#w+j7IFI|$B!bVZ_e*nHgzwZD5 diff --git a/pom.xml b/pom.xml index 026eb5cb..6c37666d 100644 --- a/pom.xml +++ b/pom.xml @@ -68,6 +68,7 @@ 1.8 1.0.0 + 1.2.2-SNAPSHOT 2.22.0 2.0.2.RELEASE @@ -224,6 +225,11 @@ eelf-core ${eelf.core.version} + + org.onap.logging-analytics + logging-library + ${logging.analytics.version} + org.codehaus.janino janino 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 918a267d..bebb6703 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 240094e6..4422c92f 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 74c78aee..2139b3d3 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 276670e2..cca0afde 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 71835fa1..a20a7004 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); + } } diff --git a/src/main/resources/application-noaaf.properties b/src/main/resources/application-noaaf.properties index db817a0e..35895539 100644 --- a/src/main/resources/application-noaaf.properties +++ b/src/main/resources/application-noaaf.properties @@ -104,7 +104,7 @@ async.queue.capacity=500 #com.att.eelf.logging.path= com.att.eelf.logging.file=logback-default.xml #The log folder that will be used in logback.xml file -clamp.config.log.path=/var/log/onap +clamp.config.log.path=/var/log/ONAP/clamp clamp.config.files.systemProperties=classpath:/system.properties clamp.config.files.cldsUsers=classpath:/clds/clds-users.json clamp.config.files.globalProperties=classpath:/clds/templates/globalProperties.json diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 24ecc4f9..552efbc7 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -117,7 +117,7 @@ async.queue.capacity=500 #com.att.eelf.logging.path= com.att.eelf.logging.file=logback-default.xml #The log folder that will be used in logback.xml file -clamp.config.log.path=/var/log/onap +clamp.config.log.path=/var/log/ONAP/clamp clamp.config.files.systemProperties=classpath:/system.properties clamp.config.files.cldsUsers=classpath:/clds/clds-users.json clamp.config.files.globalProperties=classpath:/clds/templates/globalProperties.json diff --git a/src/main/resources/logback-default.xml b/src/main/resources/logback-default.xml index 801e4e47..7e8eba5d 100644 --- a/src/main/resources/logback-default.xml +++ b/src/main/resources/logback-default.xml @@ -1,67 +1,70 @@ - - - - - INFO - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{1024} - %msg%n - - - + + + + + + + + + - - - INFO - - ${logDirectory}/clamp/error.log - true - - %date{"yyyy-MM-dd'T'HH:mm:ss,SSSXXX", - UTC}|%X{RequestId}|%.20thread|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%.-5level|%X{ErrorCode}|%X{ErrorDescription}|%msg%n - - - - 10 - ${logDirectory}/clamp/error.%i.log.zip - - - - 10MB - - + + + + + + INFO + + + ${defaultPattern} + + + + + + INFO + + ${logDirectory}/error.log + true + + ${defaultPattern} + + + ${outputDirectory}/clamp/error.%d{yyyy-MM-dd}.%i.log.zip + 50MB + 30 + 10GB + + + 10MB + + + + + ${logDirectory}/debug.log + true + + ${defaultPattern} + + + ${outputDirectory}/clamp/debug.%d{yyyy-MM-dd}.%i.log.zip + 50MB + 30 + 10GB + + - - ${logDirectory}/clamp/debug.log - true - - %date{"yyyy-MM-dd'T'HH:mm:ss,SSSXXX",UTC}|%X{RequestId}|%.20thread|%.-5level|%logger{36}|%msg%n - - - - ${logDirectory}/clamp/debug.%d{yyyy-MM-dd}.%i.log.zip - - - 10MB - - 5 - - - ${logDirectory}/clamp/audit.log + ${logDirectory}/audit.log true %X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%.20thread|%X{VirtualServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}|%X{Unused}|%X{ProcessKey}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n @@ -70,7 +73,7 @@ 10 - ${logDirectory}/clamp/audit.%i.log.zip + ${logDirectory}/audit.%i.log.zip - ${logDirectory}/clamp/metric.log + ${logDirectory}/metric.log true %X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%.20thread|%X{VirtualServerName}|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}|%X{Unused}|%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}| @@ -95,7 +98,7 @@ 10 - ${logDirectory}/clamp/metric.%i.log.zip + ${logDirectory}/metric.%i.log.zip - ${logDirectory}/clamp/security.log + ${logDirectory}/security.log true %X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%.20thread|%X{VirtualServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}|%X{Unused}|%X{ProcessKey}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n @@ -121,7 +124,7 @@ 10 - ${logDirectory}/clamp/security.%i.log.zip + ${logDirectory}/security.%i.log.zip authList = new LinkedList(); - + private LoggingUtils util; /** * Setup the variable before the tests execution. * @@ -102,6 +105,10 @@ public class CldsServiceItCase { authList.add(new SimpleGrantedAuthority("permission-type-template|dev|update")); authList.add(new SimpleGrantedAuthority("permission-type-filter-vf|dev|*")); authentication = new UsernamePasswordAuthenticationToken(new User("admin", "", authList), "", authList); + + util = Mockito.mock(LoggingUtils.class); + Mockito.doNothing().when(util).entering(Matchers.any(HttpServletRequest.class), Matchers.any(String.class)); + cldsService.setLoggingUtil(util); } @Test @@ -144,6 +151,7 @@ public class CldsServiceItCase { public void testPutModel() { SecurityContext securityContext = Mockito.mock(SecurityContext.class); Mockito.when(securityContext.getAuthentication()).thenReturn(authentication); + cldsService.setSecurityContext(securityContext); // Add the template first CldsTemplate newTemplate = new CldsTemplate(); diff --git a/src/test/java/org/onap/clamp/clds/it/CldsTemplateServiceItCase.java b/src/test/java/org/onap/clamp/clds/it/CldsTemplateServiceItCase.java index 913e49a4..ba8b0b79 100644 --- a/src/test/java/org/onap/clamp/clds/it/CldsTemplateServiceItCase.java +++ b/src/test/java/org/onap/clamp/clds/it/CldsTemplateServiceItCase.java @@ -35,14 +35,18 @@ import java.security.Principal; import java.util.LinkedList; import java.util.List; +import javax.servlet.http.HttpServletRequest; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.Matchers; import org.mockito.Mockito; 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.service.CldsTemplateService; +import org.onap.clamp.clds.util.LoggingUtils; import org.onap.clamp.clds.util.ResourceFileUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @@ -74,6 +78,7 @@ public class CldsTemplateServiceItCase { private CldsTemplate cldsTemplate; private Authentication authentication; private List authList = new LinkedList(); + private LoggingUtils util; /** * Setup the variable before the tests execution. @@ -89,11 +94,14 @@ public class CldsTemplateServiceItCase { authList.add(new SimpleGrantedAuthority("permission-type-template|dev|update")); authList.add(new SimpleGrantedAuthority("permission-type-filter-vf|dev|*")); authentication = new UsernamePasswordAuthenticationToken(new User("admin", "", authList), "", authList); - + SecurityContext securityContext = Mockito.mock(SecurityContext.class); Mockito.when(securityContext.getAuthentication()).thenReturn(authentication); - - + + util = Mockito.mock(LoggingUtils.class); + Mockito.doNothing().when(util).entering(Matchers.any(HttpServletRequest.class), Matchers.any(String.class)); + cldsTemplateService.setLoggingUtil(util); + cldsTemplateService.setSecurityContext(securityContext); bpmnText = ResourceFileUtil.getResourceAsString("example/dao/bpmn-template.xml"); imageText = ResourceFileUtil.getResourceAsString("example/dao/image-template.xml"); -- 2.16.6