【发布时间】:2014-06-06 18:59:35
【问题描述】:
我有一个通用功能,可以将有关异常的信息发送到应用程序日志。
我在类的方法中使用exception_handler 函数。传递给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 转换为类中的方法,如果这样可以让事情变得更容易。
【问题讨论】:
标签: python python-2.7 decorator python-decorators