Refactoring Consolidation Service
[sdc.git] / common-app-api / src / main / java / org / openecomp / sdc / common / ecomplog / Stopwatch.java
1 package org.openecomp.sdc.common.ecomplog;
2
3 import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_BEGIN_TIMESTAMP;
4 import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_ELAPSED_TIME;
5 import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_END_TIMESTAMP;
6
7 import java.time.Clock;
8 import java.time.Duration;
9 import java.time.LocalDateTime;
10
11 import org.openecomp.sdc.common.ecomplog.api.IStopWatch;
12 import org.slf4j.Logger;
13 import org.slf4j.LoggerFactory;
14 import org.slf4j.MDC;
15
16 /**
17  * Created by dd4296 on 12/13/2017.
18  * this is local implementation of the stopwatch class from EELF standard with the same interface
19  * can be replaced if needed with EELF lib
20  */
21 public class Stopwatch implements IStopWatch {
22
23     private static Logger log = LoggerFactory.getLogger(Stopwatch.class.getName());
24
25     public Stopwatch() {
26     }
27
28     public void start() {
29         if (MDC.get(MDC_BEGIN_TIMESTAMP) == null || MDC.get(MDC_BEGIN_TIMESTAMP).trim().length() == 0)
30             MDC.put(MDC_BEGIN_TIMESTAMP, generatedTimeNow());
31     }
32
33     public void stop() {
34         if (MDC.get(MDC_BEGIN_TIMESTAMP) == null) {
35             log.error("call to stop without calling start first, this is not compliant with EELF format");
36         }
37         MDC.put(MDC_END_TIMESTAMP, generatedTimeNow());
38         setElapsedTime();
39     }
40
41     private void setElapsedTime() {
42
43         try {
44
45             final LocalDateTime startTime = LocalDateTime.parse(MDC.get(MDC_BEGIN_TIMESTAMP));
46             final LocalDateTime endTime = LocalDateTime.parse(MDC.get(MDC_END_TIMESTAMP));
47
48             final Duration timeDifference = Duration.between(startTime, endTime);
49
50             MDC.put(MDC_ELAPSED_TIME, String.valueOf(timeDifference.toMillis()));
51
52         } catch(Exception ex) {
53             log.error("failed to calculate elapsed time",ex);
54         }
55     }
56
57     private String generatedTimeNow() {
58         return String.valueOf(LocalDateTime.now(Clock.systemUTC()));
59     }
60
61 }