标签:管理器 sel except str roc add ini error pytho
之前发过了装饰器版本的异常记录日志,但是需要装饰在函数或方法上。此篇用上下文管理,用一个with就能记录错误了,不需要写成函数。
import traceback
# pip install multiprocessing_log_manager from multiprocessing_log_manager import LogManager class ExceptionContextManager(): """ 用上下文管理器计时,可对代码片段进行错误捕捉,比装饰器更细腻 """ def __init__(self, logger_name=‘ExceptionContextManager‘, verbose=100, donot_raise__exception=True, ): """ :param _verbose: 打印错误的深度,对应traceback对象的limit,为正整数 :param donot_raise__exception:是否不重新抛出错误,为Fasle则抛出,为True则不抛出 """ self.logger = LogManager(logger_name).get_logger_and_add_handlers() self._verbose = verbose self._donot_raise__exception = donot_raise__exception def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): # print(exc_val) # print(traceback.format_exc()) exc_str = str(exc_type) + ‘ : ‘ + str(exc_val) exc_str_color = ‘\033[0;30;45m%s\033[0m‘ % exc_str if self._donot_raise__exception: self.logger.error(‘\n‘.join(traceback.format_tb(exc_tb)[:self._verbose]) + exc_str_color) return self._donot_raise__exception # __exit__方法必须retuen True才会不重新抛出错误 if __name__ == ‘__main__‘: def f1(): 1 + ‘2‘ def f2(): f1() def f3(): f2() def f4(): f3() def run(): f4()
运行结果是这样:
标签:管理器 sel except str roc add ini error pytho
原文地址:https://www.cnblogs.com/ydf0509/p/9350945.html