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;
26 * Tracks and logs audit information when a request is being processed. An instance of this class cannot be reused, and
27 * the pre- and post-request methods must be called only once.
32 public class AuditTracker implements Tracker {
34 private final Logger logger;
35 private volatile long started;
36 private volatile String clientIpAddress;
39 * Allows passing a class that will be used to log audit.
41 * @param resourceType audit will be logged through the logger of this class
43 public AuditTracker(Class<?> resourceType) {
44 this.logger = LoggerFactory.getLogger(resourceType);
48 * Allows passing a logger that will be used to log audit.
50 * @param logger audit will be logged through this logger, cannot be null
52 public AuditTracker(Logger logger) {
53 this.logger = Objects.requireNonNull(logger);
57 public synchronized void preRequest(HttpServletRequest request) {
59 if (this.started > 0) {
60 throw new IllegalStateException("Pre-request has been already called");
63 this.started = System.currentTimeMillis();
64 this.clientIpAddress = request.getRemoteAddr();
68 public synchronized void postRequest(RequestProcessingResult result) {
70 if (this.started == 0) {
71 throw new IllegalStateException("Pre-request must be called first");
74 if (!logger.isAuditEnabled()) {
78 long end = System.currentTimeMillis();
79 AuditData auditData = AuditData.builder().startTime(started).endTime(end).statusCode(result.getStatusCode())
80 .responseCode(Integer.toString(result.getStatus()))
81 .responseDescription(result.getStatusPhrase()).clientIpAddress(clientIpAddress)
83 logger.audit(auditData);