让Celery使用Django异常中间件

时间:2013-06-25 14:55:15

标签: python django celery django-celery

如何强制Celery使用自定义中间件来添加额外的调试信息并控制用于发送错误电子邮件的电子邮件帐户?

我正在使用自定义Django middlewareexceptions添加额外的调试信息并发送错误电子邮件。它适用于标准Django 500错误,但Celery似乎忽略了所有Django中间件。结果是,Celery中发生的任何错误都只报告非常有限的回溯并使用默认的电子邮件连接,而不是用于报告错误的特殊连接。

2 个答案:

答案 0 :(得分:1)

Celery并没有真正使用django中间件,但这将完成我认为你想要的。

代码中的某处放置以下信号处理程序:

from celery.signals import task_failure
from django.core.mail import mail_admins

from django.views.debug import ExceptionReporter


@task_failure.connect
def task_failure_handler(task_id, exception, traceback, einfo, *args, **kwargs):
    exc_info = (einfo.type, exception, traceback)
    reporter = ExceptionReporter(None, *exc_info)
    debug_html = reporter.get_traceback_html()
    debug_text = reporter.get_traceback_text()

    subject = u'Exception - %s' % exception.message
    subject = subject.replace("\n", " ")[:250]

    mail_admins(subject, debug_text, html_message=debug_html)

settings.py中添加以下内容

# disable default celery error emails
CELERY_SEND_TASK_ERROR_EMAILS = False

答案 1 :(得分:0)

您应该将mail_admins处理程序添加到芹菜记录器中,如下所示:

LOGGING = {

...

'loggers': {
    'django.request': {
        'handlers': ['mail_admins'],
        'level': 'ERROR',
        'propagate': False,
    },
    'celery': {
        'level': 'INFO',
        'handlers': ['mail_admins'],
        'propagate': True (or False :) ),
    },
...
不过,我正在使用Sentry来记录错误(Django和Celery),这真是太棒了!

相关问题