gpt4 book ai didi

python - 让 Celery 使用 Django 异常中间件

转载 作者:太空宇宙 更新时间:2023-11-03 18:55:47 29 4
gpt4 key购买 nike

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

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

最佳答案

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

关于python - 让 Celery 使用 Django 异常中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17300707/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com