Last active
December 20, 2017 17:14
-
-
Save ptaylor/4a21018a55e963c49b323d396c7c8136 to your computer and use it in GitHub Desktop.
Java 8 elapsed time logger
This file contains 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
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