Skip to content

Instantly share code, notes, and snippets.

@ptaylor
Last active December 20, 2017 17:14
Show Gist options
  • Save ptaylor/4a21018a55e963c49b323d396c7c8136 to your computer and use it in GitHub Desktop.
Save ptaylor/4a21018a55e963c49b323d396c7c8136 to your computer and use it in GitHub Desktop.
Java 8 elapsed time logger
package org.example.utils;
import lombok.extern.slf4j.Slf4j;
import java.util.function.Supplier;
/**
* Log elapsed time for a function.
*
* Usage:
*
* import static org.example.utils.ElapsedTimeLogger.logElapsedTime;
*
* ResponseType response = logElapsedTime(() -> myFunction(....), "op.name");
*
*/
@Slf4j
public class ElapsedTimeLogger {
public static <T> T logElapsedTime(Supplier<T> r, String name) {
long before = System.currentTimeMillis();
T result = null;
try {
log.debug("timing operation {}", name);
result = r.get();
log.info("elapsedTime: {}, operation: {}, status: ok", System.currentTimeMillis() - before, name);
} catch (Throwable t) {
log.info("elapsedTime: {}, operation: {}, status: failed, exception: {}", System.currentTimeMillis() - before, name, t);
throw t;
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment