summaryrefslogtreecommitdiff
path: root/django/tasks/signals.py
blob: 919dae02222156d6264c20c3a210ab969f26fe69 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import logging
import sys

from asgiref.local import Local

from django.core.signals import setting_changed
from django.dispatch import Signal, receiver

from .base import TaskResultStatus

logger = logging.getLogger("django.tasks")

task_enqueued = Signal()
task_finished = Signal()
task_started = Signal()


@receiver(setting_changed)
def clear_tasks_handlers(*, setting, **kwargs):
    """Reset the connection handler whenever the settings change."""
    if setting == "TASKS":
        from . import task_backends

        task_backends._settings = task_backends.settings = (
            task_backends.configure_settings(None)
        )
        task_backends._connections = Local()


@receiver(task_enqueued)
def log_task_enqueued(sender, task_result, **kwargs):
    logger.debug(
        "Task id=%s path=%s enqueued backend=%s",
        task_result.id,
        task_result.task.module_path,
        task_result.backend,
    )


@receiver(task_started)
def log_task_started(sender, task_result, **kwargs):
    logger.info(
        "Task id=%s path=%s state=%s",
        task_result.id,
        task_result.task.module_path,
        task_result.status,
    )


@receiver(task_finished)
def log_task_finished(sender, task_result, **kwargs):
    # Signal is sent inside exception handlers, so exc_info() is available.
    exc_info = sys.exc_info()
    logger.log(
        (
            logging.ERROR
            if task_result.status == TaskResultStatus.FAILED
            else logging.INFO
        ),
        "Task id=%s path=%s state=%s",
        task_result.id,
        task_result.task.module_path,
        task_result.status,
        exc_info=exc_info if exc_info[0] else None,
    )