enhance AbstractMetricLogFilter
[logging-analytics.git] / reference / logging-filter / logging-filter-base / src / main / java / org / onap / logging / filter / base / AbstractMetricLogFilter.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - Logging
4  * ================================================================================
5  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.logging.filter.base;
22
23 import java.time.ZoneOffset;
24 import java.time.ZonedDateTime;
25 import java.time.format.DateTimeFormatter;
26 import java.util.UUID;
27 import org.onap.logging.ref.slf4j.ONAPLogConstants;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30 import org.slf4j.MDC;
31 import org.slf4j.Marker;
32 import org.slf4j.MarkerFactory;
33
34 public abstract class AbstractMetricLogFilter<Request, Response, RequestHeaders> extends MDCSetup {
35     protected static final Logger logger = LoggerFactory.getLogger(AbstractMetricLogFilter.class);
36     private final String partnerName;
37     private static final Marker INVOKE_RETURN = MarkerFactory.getMarker("INVOKE-RETURN");
38
39     public AbstractMetricLogFilter() {
40         partnerName = getPartnerName();
41     }
42
43     protected abstract void addHeader(RequestHeaders requestHeaders, String headerName, String headerValue);
44
45     protected abstract String getTargetServiceName(Request request);
46
47     protected abstract String getServiceName(Request request);
48
49     protected abstract int getHttpStatusCode(Response response);
50
51     protected abstract String getResponseCode(Response response);
52
53     protected abstract String getTargetEntity(Request request);
54
55     protected void pre(Request request, RequestHeaders requestHeaders) {
56         try {
57             setupMDC(request);
58             setupHeaders(request, requestHeaders);
59             additionalPre(request, requestHeaders);
60             logger.info(ONAPLogConstants.Markers.INVOKE, "Invoke");
61         } catch (Exception e) {
62             logger.warn("Error in AbstractMetricLogFilter pre", e);
63         }
64     }
65
66     protected void additionalPre(Request request, RequestHeaders requestHeaders) {
67         // override to add application specific logic
68     }
69
70     protected void setupHeaders(Request clientRequest, RequestHeaders requestHeaders) {
71         String requestId = extractRequestID();
72         addHeader(requestHeaders, ONAPLogConstants.Headers.REQUEST_ID, requestId);
73         addHeader(requestHeaders, Constants.HttpHeaders.HEADER_REQUEST_ID, requestId);
74         addHeader(requestHeaders, Constants.HttpHeaders.TRANSACTION_ID, requestId);
75         addHeader(requestHeaders, Constants.HttpHeaders.ECOMP_REQUEST_ID, requestId);
76         addHeader(requestHeaders, ONAPLogConstants.Headers.INVOCATION_ID, MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID));
77         addHeader(requestHeaders, ONAPLogConstants.Headers.PARTNER_NAME, partnerName);
78     }
79
80     protected void setupMDC(Request request) {
81         MDC.put(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP,
82                 ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT));
83         MDC.put(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME, getTargetServiceName(request));
84         MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, ONAPLogConstants.ResponseStatus.INPROGRESS.toString());
85         setInvocationIdFromMDC();
86
87         if (MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY) == null) {
88             String targetEntity = getTargetEntity(request);
89             if (targetEntity != null) {
90                 MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY, targetEntity);
91             } else {
92                 MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY, Constants.DefaultValues.UNKNOWN_TARGET_ENTITY);
93             }
94         }
95
96         if (MDC.get(ONAPLogConstants.MDCs.SERVICE_NAME) == null) {
97             MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, getServiceName(request));
98         }
99         setServerFQDN();
100     }
101
102     protected String extractRequestID() {
103         String requestId = MDC.get(ONAPLogConstants.MDCs.REQUEST_ID);
104         if (requestId == null || requestId.isEmpty()) {
105             requestId = UUID.randomUUID().toString();
106             setLogTimestamp();
107             setElapsedTimeInvokeTimestamp();
108             logger.warn("No value found in MDC when checking key {} value will be set to {}",
109                     ONAPLogConstants.MDCs.REQUEST_ID, requestId);
110             MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, requestId);
111         }
112         return requestId;
113     }
114
115     protected void post(Request request, Response response) {
116         try {
117             setLogTimestamp();
118             setElapsedTimeInvokeTimestamp();
119             setResponseStatusCode(getHttpStatusCode(response));
120             setResponseDescription(getHttpStatusCode(response));
121             MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE, getResponseCode(response));
122             additionalPost(request, response);
123             logger.info(INVOKE_RETURN, "InvokeReturn");
124             clearClientMDCs();
125         } catch (Exception e) {
126             logger.warn("Error in AbstractMetricLogFilter post", e);
127         }
128     }
129
130     protected void additionalPost(Request request, Response response) {
131         // override to add application specific logic
132     }
133
134     protected String getPartnerName() {
135         return getProperty(Constants.Property.PARTNER_NAME);
136     }
137
138 }