1 package org.naftulin.timespan;
2
3
4 import org.naftulin.logwrapper.LogAdapter;
5 import org.naftulin.logwrapper.LogLevelAdaptor;
6
7 /***
8 * Reports the time passed between starting and finishing an action.
9 * Could be extended later to gather statiscics for starting/stopping
10 * events with the same name.<br>
11 * Usage:
12 * <pre>
13 * TimeSpan readEvent = new TimeSpan("reading values from db for xyz");
14 * readEvent.start();
15 * .. call to db ..
16 * readEvent.stop();
17 * readEvent.log(logger, LogLevelAdaptor.DEBUG);
18 * </pre>
19 * @author henry naftulin
20 * @version 1.0
21 */
22 public class TimeSpan {
23 private long startTime;
24 private long endTime;
25 private final String name;
26
27 /***
28 * Creates times span class with a particular name for the task
29 * @param name name of the task
30 */
31 public TimeSpan(String name) { this.name = name; }
32 /***
33 * Records start time.
34 */
35 public void start() { startTime = System.currentTimeMillis(); }
36 /***
37 * Records stop time.
38 */
39 public void stop() { endTime = System.currentTimeMillis() ; }
40 /***
41 * Prints a message: 'It took < timedif > miliseconds to finish the task < name >' to log
42 * @param log logger to print the message to
43 * @param level log level
44 */
45 public void log(LogAdapter log, LogLevelAdaptor level) {
46 StringBuffer message = new StringBuffer(30);
47 message.append("It took ").append(endTime - startTime).append(" miliseconds to finish task ").append(name);
48 log.log(level, message.toString());
49 }
50 }