Created
March 8, 2012 01:25
-
-
Save tkaemming/1997845 to your computer and use it in GitHub Desktop.
python logging timer decorator
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
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) |
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
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