2 * Copyright © 2016-2018 European Support Limited
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package org.openecomp.sdc.logging.servlet;
19 import java.util.Objects;
20 import javax.servlet.http.HttpServletRequest;
21 import org.openecomp.sdc.logging.api.AuditData;
22 import org.openecomp.sdc.logging.api.Logger;
23 import org.openecomp.sdc.logging.api.LoggerFactory;
25 import static org.onap.logging.ref.slf4j.ONAPLogConstants.ResponseStatus.COMPLETE;
28 * Tracks and logs audit information when a request is being processed. An instance of this class cannot be reused, and
29 * the pre- and post-request methods must be called only once.
34 public class AuditTracker implements Tracker {
36 private final Logger logger;
37 private volatile long started;
38 private volatile String clientIpAddress;
41 * Allows passing a class that will be used to log audit.
43 * @param resourceType audit will be logged through the logger of this class
45 public AuditTracker(Class<?> resourceType) {
46 this.logger = LoggerFactory.getLogger(resourceType);
50 * Allows passing a logger that will be used to log audit.
52 * @param logger audit will be logged through this logger, cannot be null
54 public AuditTracker(Logger logger) {
55 this.logger = Objects.requireNonNull(logger);
59 public synchronized void preRequest(HttpServletRequest request) {
61 if (this.started > 0) {
62 throw new IllegalStateException("Pre-request has been already called");
65 this.started = System.currentTimeMillis();
66 this.clientIpAddress = request.getRemoteAddr();
67 AuditData auditData = AuditData.builder().startTime(started).endTime(started).statusCode(COMPLETE)
68 .clientIpAddress(clientIpAddress)
70 logger.auditEntry(auditData);
74 public synchronized void postRequest(RequestProcessingResult result) {
76 if (this.started == 0) {
77 throw new IllegalStateException("Pre-request must be called first");
80 if (!logger.isAuditEnabled()) {
84 long end = System.currentTimeMillis();
85 AuditData auditData = AuditData.builder().startTime(started).endTime(end).statusCode(result.getStatusCode())
86 .responseCode(Integer.toString(result.getStatus()))
87 .responseDescription(result.getStatusPhrase()).clientIpAddress(clientIpAddress)
89 logger.auditExit(auditData);