Flexible Python context manager to log elapsed time
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
# Based on this: https://stackoverflow.com/a/62956469/145349 | |
import logging | |
import time | |
from contextlib import contextmanager | |
@contextmanager | |
def log_time(logger, log_message="Took %.4f secs", log_level=logging.INFO): | |
start = time.perf_counter() | |
yield | |
elapsed = time.perf_counter() - start | |
logger.log(log_level, log_message, elapsed) | |
# Usage: | |
logging.basicConfig() | |
logger = logging.getLogger(__name__) | |
logger.setLevel(logging.INFO) | |
with log_time(logger=logger): | |
time.sleep(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment