我有一个通用函数,可以将有关异常的信息发送到应用程序日志。
我用exception_handler
来自类中方法的函数。传入并由应用程序调用的应用程序日志处理程序exception_handler
创建一个 JSON 字符串,该字符串是实际发送到日志文件的内容。这一切都很好。
def exception_handler(log, terminate=False):
exc_type, exc_value, exc_tb = sys.exc_info()
filename, line_num, func_name, text = traceback.extract_tb(exc_tb)[-1]
log.error('{0} Thrown from module: {1} in {2} at line: {3} ({4})'.format(exc_value, filename, func_name, line_num, text))
del (filename, line_num, func_name, text)
if terminate:
sys.exit()
我按如下方式使用它:(一个超简化的示例)
from utils import exception_handler
class Demo1(object):
def __init__(self):
self.log = {a class that implements the application log}
def demo(self, name):
try:
print(name)
except Exception:
exception_handler(self.log, True)
我想改变exception_handler
用作大量方法的装饰器,即:
@handle_exceptions
def func1(self, name)
{some code that gets wrapped in a try / except by the decorator}
我看过很多关于装饰器的文章,但我还没有弄清楚如何实现我想要做的事情。我需要传递对活动日志对象的引用,并将 0 个或多个参数传递给包装函数。我很乐意转换exception_handler
类中的方法(如果这能让事情变得更容易)。