Skip to content

Instantly share code, notes, and snippets.

@tkaemming
Created March 8, 2012 01:25
Show Gist options
  • Save tkaemming/1997845 to your computer and use it in GitHub Desktop.
Save tkaemming/1997845 to your computer and use it in GitHub Desktop.
python logging timer decorator
import logging, time
from timer import timed
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
handler = logging.StreamHandler()
handler.setLevel(logging.DEBUG)
logger.addHandler(handler)
@timed(logger)
def pow10(x):
time.sleep(1)
return x ** 10
# will log: <function pow10 at 0x107847230>: 1001.08790398 ms
pow10(100)
import functools
import logging
import time
def timed(logger, level=None, format='%s: %s ms'):
if level is None:
level = logging.DEBUG
def decorator(fn):
@functools.wraps(fn)
def inner(*args, **kwargs):
start = time.time()
result = fn(*args, **kwargs)
duration = time.time() - start
logger.log(level, format, repr(fn), duration * 1000)
return result
return inner
return decorator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment