Created
July 1, 2015 14:04
-
-
Save RobertFischer/818037df2ee320573874 to your computer and use it in GitHub Desktop.
TimingLogger
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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