python 上下文处理错误,记录日志
之前发过了装饰器版本的异常记录日志,但是需要装饰在函数或方法上。此篇用上下文管理,用一个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() with ExceptionContextManager() as ec: run()
print('finish')
计算整形和字符串相加,运行结果是这样:
可以传verbose参数来控制记录错误的深度,默认写了100
反对极端面向过程编程思维方式,喜欢面向对象和设计模式的解读,喜欢对比极端面向过程编程和oop编程消耗代码代码行数的区别和原因。致力于使用oop和36种设计模式写出最高可复用的框架级代码和使用最少的代码行数完成任务,致力于使用oop和设计模式来使部分代码减少90%行,使绝大部分py文件最低减少50%-80%行的写法。