将来自 Celery 任务的日志记录信息存储在 Django 数据库中

Storing logging information from a Celery task in Django database

假设我想在 Celery 中定期执行以下函数:

import logging
import requests

log = logging.getLogger(__name__)


def spam():
    data = fetch_some_data()
    log.info(f'Fetched {len(data)} data')

    stuff = []
    for item in data:
        try:
            response = requests.get(url + item)
            response.raise_for_status()
        except RequestException as exc:
            log.error(f'Error when requesting {item}: {exc}')
            continue

        stuff.append(response.text)

    for item in stuff:
        do_something(item)
    log.info(f'Processed {len(stuff)} items')

伴随任务执行时:

from hello import spam

@app.task
def run():
    spam()

我想查看与记录的消息一起存储的任务结果。 Flower for example is able to show the task progress and history but I would like to add the logging information as separate fields (e.g. "Info Messages" and "Error Messages"). Similarly, if using django-celery-results,它可以在 Django Admin 视图中显示相同的信息。

实现此目标的最佳方法是什么?

只需利用 after_setup_logger 装饰器。您可以在芹菜启动时注册您的记录器,以便您可以在芹菜任务中使用它。

@after_setup_logger.connect
def setup_loggers(logger, *args, **kwargs):
    import logging

    fh = logging.FileHandler('/path/to/file')
    logger = logging.getLogger("test-logger")
    logger.addHandler(fh)

现在,您可以在任务中使用 "test-logger" 记录器并将日志重定向到文件中。