我正在使用apscheduler在后台处理一些事情。
我想捕获并报告Sentry可能的例外情况。我的代码如下所示:
sentry = Client(dsn=SENTRY_DSN)
def sample_method():
# some processing..
raise ConnectionError
def listen_to_exceptions(event):
if event.exception:
# I was hoping raven will capture the exception using sys.exc_info(), but it's not
sentry.captureException()
scheduler = BlockingScheduler()
scheduler.add_listener(listen_to_exceptions, EVENT_JOB_EXECUTED | EVENT_JOB_ERROR)
scheduler.add_job(sample_method, 'interval', minutes=5, max_instances=1)
# run forever!!!
scheduler.start()
但是,相反,捕获异常会产生更多异常,试图将其报告给Sentry。
ConnectionError
Error notifying listener
Traceback (most recent call last):
File "/.../venv/lib/python3.6/site-packages/apscheduler/schedulers/base.py", line 825, in _dispatch_event
cb(event)
File "app.py", line 114, in listen_to_exceptions
sentry.captureException(event.exception)
File "/.../venv/lib/python3.6/site-packages/raven/base.py", line 814, in captureException
'raven.events.Exception', exc_info=exc_info, **kwargs)
File "/.../venv/lib/python3.6/site-packages/raven/base.py", line 623, in capture
if self.skip_error_for_logging(exc_info):
File "/.../venv/lib/python3.6/site-packages/raven/base.py", line 358, in skip_error_for_logging
key = self._get_exception_key(exc_info)
File "/.../venv/lib/python3.6/site-packages/raven/base.py", line 345, in _get_exception_key
code_id = id(exc_info[2] and exc_info[2].tb_frame.f_code)
TypeError: 'ConnectionError' object is not subscriptable
我正在尝试根据docs使用事件监听器。 是否有其他方法可以捕获已执行作业中的异常?
当然我可以为每个工作职能添加try除了块。我只是想了解是否有办法用apscedular做,因为我有20多个工作,并且每个地方都添加sentry.captureException()
似乎是重复。
答案 0 :(得分:3)
您只需要捕获EVENT_JOB_ERROR
。此外,sentry.captureException()
需要一个exc_info元组作为其参数,而不是异常对象。以下内容适用于Python 3:
def listen_to_exceptions(event):
exc_info = type(event.exception), event.exception, event.exception.__traceback__
sentry.captureException(exc_info)
scheduler.add_listener(listen_to_exceptions, EVENT_JOB_ERROR)
答案 1 :(得分:0)
文档为updated。因此,您必须按照以下方式进行操作:
from sentry_sdk import capture_exception
....
def sentry_listener(event):
if event.exception:
capture_exception(event.exception)
scheduler.add_listener(sentry_listener, EVENT_JOB_ERROR)