借助Github和stackoverflow,我编写了日志装饰器来测量函数的执行时间,并在函数不执行时引发异常。代码是:
def log(logger):
def log_decorator(function):
def wrapper(*args, **kwargs):
try:
start_time = time.time()
logger.info('Starting function -' + function.__name__)
return function(*args, **kwargs)
except Exception as err:
logger.exception(err)
raise
finally:
end_time = time.time()
logger.info('End function - ' + function.__name__)
logger.info('Execution time %s milliseconds', (end_time-start_time)*1000)
return wrapper
return log_decorator
我有几个问题:
答案 0 :(得分:0)
start_time
设置为全局。如果要在包装器外部访问它,则在包装器外部声明它。