2334f373bc803c7d8ffa67c211d0522497762351
[sdc.git] /
1 /*
2  * Copyright © 2016-2018 European Support Limited
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.openecomp.sdc.logging.servlet;
18
19 import java.util.Objects;
20 import java.util.UUID;
21 import javax.servlet.http.HttpServletRequest;
22 import org.openecomp.sdc.logging.api.ContextData;
23 import org.openecomp.sdc.logging.api.LoggingContext;
24
25 /**
26  * Populates the context before a request is processed, and cleans it after the request has been processed.
27  *
28  * @author evitaliy
29  * @since 31 Jul 2018
30  */
31 public class ContextTracker implements Tracker {
32
33     private final HttpHeader partnerNameHeaders;
34     private final HttpHeader requestIdHeaders;
35
36     /**
37      * Constructs tracker to handle required logging context in Servlet-based applications. Refer to ONAP logging
38      * guidelines for fields required to be put on logging context.
39      *
40      * @param partnerNameHeaders HTTP headers to check for a partner name, cannot be null
41      * @param requestIdHeaders   HTTP headers to check for a request ID, cannot be null
42      */
43     public ContextTracker(HttpHeader partnerNameHeaders, HttpHeader requestIdHeaders) {
44         this.partnerNameHeaders = Objects.requireNonNull(partnerNameHeaders);
45         this.requestIdHeaders = Objects.requireNonNull(requestIdHeaders);
46     }
47
48     @Override
49     public void preRequest(HttpServletRequest request) {
50
51         LoggingContext.clear();
52
53         String serviceName = ServiceNameFormatter.format(request);
54         String requestId = requestIdHeaders.getAny(request::getHeader).orElse(UUID.randomUUID().toString());
55         ContextData.ContextDataBuilder contextBuilder =
56                 ContextData.builder().serviceName(serviceName).requestId(requestId);
57
58         partnerNameHeaders.getAny(request::getHeader).ifPresent(contextBuilder::partnerName);
59         LoggingContext.put(contextBuilder.build());
60     }
61
62     @Override
63     public void postRequest(RequestProcessingResult result) {
64         LoggingContext.clear();
65     }
66 }