Skip to content

Instantly share code, notes, and snippets.

@RobertFischer
Created July 1, 2015 14:04
Show Gist options
  • Select an option

  • Save RobertFischer/818037df2ee320573874 to your computer and use it in GitHub Desktop.

Select an option

Save RobertFischer/818037df2ee320573874 to your computer and use it in GitHub Desktop.
TimingLogger
/**
* Use this in a try-with-resources block to automatically implement logging timing.
*/
public class TimingLogger implements AutoCloseable {
private final Logger logger;
private final String description;
private final long startTime;
private final AtomicBoolean closed = new AtomicBoolean(false);
public class TimingLogger(Logger logger, String description) {
Objects.requireNonNull(logger, "Logger to write to");
this.logger = logger;
Objects.requireNonNull(description, "Description of the event we are timing");
if(description.isEmpty()) {
throw new IllegalArgumentException("Description may not be empty");
}
this.description = description;
this.startTime = System.currentTimeMillis();
logger.info(description + " STARTTIME=" + startTime);
}
public void close() {
if(!closed.compareAndSet(false, true)) {
long endTime = System.currentTimeMillis();
long duration = endTime - startTime;
logger.info(description + " ENDTIME=" + endTime + " DURATION=" + duration);
} else {
throw new IllegalStateException("TimingLogger for " + description + " is already closed");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment