Django框架中,使用celery可以实现异步任务的目的。对于web中费时的任务,可以加到celery中,防止阻塞界面,提高用户体验。
然而,使用celery的过程中,如果存在多种类型的任务时,所有任务的日志记录是个头疼的问题,如果直接使用python的logging模块,会出现日志文件为空,日志没有写入指定日志文件的情况。
celery提供了自己封装好的logging模块,如果设置正确,其效果还是挺好的。
# core/tasks.py
from celery import Task
from celery.utils.log import get_task_logger
def register_task_logger(module_name):
"""Instantiate a logger at the decorated class instance level."""
def wrapper(cls):
cls.log = get_task_logger('%s.%s' % (module_name, cls.__name__))
return cls
return wrapper
@register_task_log(__name__)
class AddTask(Task):
def run(self, x, y):
self.log.info("Calling task add(%d, %d)" % (x, y))
return x - y
@register_task_log(__name__)
class SubTask(Task):
def run(self, x, y):
sel