Queue处理错误仅在上一次重试时

Queue处理错误仅在上一次重试时

本文介绍了Huey Task Queue处理错误仅在上一次重试时&检索异常回溯的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前在我的 tasks.py 中设置了此代码段,以便每当任务失败时, huey 就会将电子邮件发送给Django项目的管理员:

Currently have this snippet set up in my tasks.py so that an email is sent to the Django project's admins by huey whenever a task fails:

from django.core.mail import mail_admins

from huey import signals
from huey.contrib import djhuey as huey


@huey.signal(signals.SIGNAL_ERROR)
def task_error(signal, task, exc):
    subject = f'Task [{task.name}] failed
    message = f"""Task ID: {task.id}'
Args: {task.args}
Kwargs: {task.kwargs}
Exception: {exc}"""
    mail_admins(subject, message)

这将导致以下(示例)电子邮件主题

This results in the following (example) email subject

[Django] Task [test_task] failed

和身体:

Task ID: 89e4bfb3-3cd3-4d6f-8693-68874caf21ec
Args: (123,)
Kwargs: {}
Exception: division by zero

这很漂亮,但是...问题:

which is pretty slick but... questions:

  1. 现在,只要任务失败(包括重试),就会触发此事件.我希望仅在所有重试均失败的情况下发送.因此,如果任务有 retries = 2 ,现在我会收到3封电子邮件(原始错误+ 2次重试).如何让它仅在上次重试时发送电子邮件?
  2. 是否可以打印异常的 exc 追溯?
  1. Right now, this is triggered whenever a task fails, including retries. I would like it to be sent only in the case all retries failed. So if a task has retries=2, right now I receive 3 emails (original error + 2 retries). How to have it send the email only on the last retry?
  2. Is there a way to print the exception's exc traceback?

P.S.我尝试通过Django项目日志进行设置,但是这种方法提供了更细粒度的控制,因此我对此感到满意.

P.S. I tried setting it up via Django project logging, but this approach offers finer-grained control, so I'm satisfied with it.

基于@Adam Chainz&的更新模块@coleifer的答案(均为正确)现在看起来像:

The module with updates based on @Adam Chainz & @coleifer's answers (both correct), now looks like:

import traceback

from django.core.mail import mail_admins

from huey import signals
from huey.contrib import djhuey as huey


@huey.signal(signals.SIGNAL_ERROR)
def task_error(signal, task, exc):
    if task.retries > 0:
        return
    subject = f'Task [{task.name}] failed'
    message = f"""Task ID: {task.id}
Args: {task.args}
Kwargs: {task.kwargs}
Exception: {exc}
{traceback.format_exc()}"""
    mail_admins(subject, message)

推荐答案

在1.我认为您可以检查 task.retries ?

On 1. I think you can check task.retries?

在2.使用 traceback.format_exception 吗?

这篇关于Huey Task Queue处理错误仅在上一次重试时&检索异常回溯的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 07:27