Last active
April 23, 2025 15:36
-
-
Save dceoy/3f5671fb6d33a99b7f440b4b409ddc0f to your computer and use it in GitHub Desktop.
[Python] Execution time logger
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
#!/usr/bin/env python | |
import logging | |
import time | |
from functools import wraps | |
from typing import Any, Callable | |
def log_execution_time(func: Callable[..., Any]) -> Callable[..., Any]: | |
@wraps(func) | |
def wrapper(*args: Any, **kwargs: Any) -> Any: | |
logger = logging.getLogger(log_execution_time.__name__) | |
start_time = time.time() | |
logger.info(f"`{func.__name__}` is executed." | |
try: | |
result = func(*args, **kwargs) | |
except Exception as e: | |
s = time.time() - start_time | |
logger.error(f"`{func.__name__}` failed after {s:.3f}s.") | |
raise e | |
else: | |
s = time.time() - start_time | |
logger.info(f"`{func.__name__}` succeeded in {s:.3f}s.") | |
return result | |
return wrapper | |
def set_logging_config(level_name: str) -> None: | |
logging.basicConfig( | |
level=getattr(logging, level_name), | |
format=( | |
"%(asctime)s [%(levelname)-8s]" | |
" <%(name)s (%(pathname)s:%(lineno)d)> %(message)s" | |
), | |
) | |
@log_execution_time | |
def function_to_log(sleep_sec: int, timeout_sec: int = 5) -> None: | |
print(f"Sleeping for {sleep_sec} seconds...") | |
time.sleep(min(sleep_sec, timeout_sec)) | |
if sleep_sec > timeout_sec: | |
raise RuntimeError(f"Timeout ({timeout_sec}s) exceeded!") | |
if __name__ == "__main__": | |
set_logging_config(level_name="DEBUG") | |
print("Starting the program...") | |
for i in [2, 4, 8]: | |
function_to_log(sleep_sec=i) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment