1 def wrapper_log(func): 2 """ 3 无参装饰器,也可以写成有参装饰器,True或Flase标记是否调用日志模块 4 功能一:执行失败,打印并记录错误日志信息,定位bug 5 功能二:记录用例执行时间 6 """ 7 8 from loguru import logger 9 from functools import wraps 10 import time 11 12 @wraps(func) # wraps使inner装的更像一个func 13 def inner(*args, **kwargs): 14 logger.info(f'{func.__name__}开始执行') 15 now1 = time.time() 16 17 try: 18 func(*args, **kwargs) 19 except Exception as e: 20 logger.error(f'执行失败,失败原因:{e}') 21 # logger.exception(e) 22 raise e 23 24 now2 = time.time() 25 logger.success(f'{func.__name__}执行成功!!!,执行用时:{now2 - now1}ms') 26 return func 27 28 return inner 29 30 31 @wrapper_log 32 def test_a(): 33 print(1 / 0) 34 35 36 if __name__ == '__main__': 37 test_a()
标签:__,wraps,name,示例,python,func,time,logger,装饰 From: https://www.cnblogs.com/BillBie/p/17138373.html