Path: blob/master/python/decorators/log_timing.py
2577 views
import time1import logging2from functools import wraps3from importlib import reload45# http://stackoverflow.com/questions/18786912/get-output-from-the-logging-module-in-ipython-notebook6# ipython notebook already call basicConfig somewhere, thus reload the logging7reload(logging)89def logger(func):10"""11create logging for the function,12re-define the format to add specific logging time13"""14@wraps(func)15def wrapper( *args, **kwargs ):16logging.basicConfig( filename = '{}.log'.format( func.__name__ ),17format = '%(asctime)s -- %(levelname)s:%(name)s: %(message)s',18datefmt = '%Y/%m/%d-%H:%M:%S',19level = logging.INFO )2021# custom the logging information22logging.info( 'Ran with args: {} and kwargs: {}'.format( args, kwargs ) )23return func( *args, **kwargs )2425return wrapper262728def timer(func):29"""time the running time of the passed in function"""30@wraps(func)31def wrapper( *args, **kwargs ):32t1 = time.time()33result = func( *args, **kwargs )34t2 = time.time() - t135print( '{} ran in: {} sec'.format( func.__name__, t2 ) )3637return wrapper3839404142