Created
December 30, 2019 10:59
-
-
Save mattseymour/0fe8b67262c91a340ebaf7256db9a437 to your computer and use it in GitHub Desktop.
Python timed logger decorator
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
import logging | |
import time | |
from functools import wraps | |
from typing import ( | |
Callable, | |
Optional, | |
) | |
def timed_logger(logger: Optional[Callable] = None): | |
""" | |
Decorator for logging the time taken to run a function, if no logger | |
is set then default to logger.info. | |
""" | |
# logger is optional. If it is just use a default (logger.info) | |
if not callable(logger): | |
logger = logging.info | |
def decorator(func: Callable): | |
@wraps(func) | |
def wrapper(*args, **kwargs): | |
start = time.time() | |
result = func(*args, **kwargs) | |
taken = round(time.time() - start, 2) | |
logger(f'{func.__name__} ran in {taken}(seconds)') | |
return result | |
return wrapper | |
return decorator |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment