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
and body:
Task ID: 89e4bfb3-3cd3-4d6f-8693-68874caf21ec
Args: (123,)
Kwargs: {}
Exception: division by zero
which is pretty slick but... questions:
- 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? - Is there a way to print the exception's
exc
traceback?
P.S. I tried setting it up via Django project logging, but this approach offers finer-grained control, so I'm satisfied with it.
Update
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)