Skip to content

Instantly share code, notes, and snippets.

@mattseymour
Created December 30, 2019 10:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattseymour/0fe8b67262c91a340ebaf7256db9a437 to your computer and use it in GitHub Desktop.
Save mattseymour/0fe8b67262c91a340ebaf7256db9a437 to your computer and use it in GitHub Desktop.
Python timed logger decorator
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