Celery:记录每个任务运行到它自己的文件?

时间:2014-08-13 08:34:59

标签: python logging celery

我希望每个作业都能在log /目录中记录它自己的文件,其中文件名是taskid。

logger = get_task_logger(__name__)

@app.task(base=CallbackTask)
def calc(syntax):
    some_func()
    logger.info('started')

在我的worker中,我使用-f参数设置日志文件以输出到。我想确保它将每个任务输出到它自己的日志文件。

2 个答案:

答案 0 :(得分:2)

好像我迟到了3年。尽管如此,我的解决方案受到@Mikko Ohtamaa想法的启发。我只是通过使用Celery Signals和python的内置日志框架来准备和清理日志记录句柄,使其变得与众不同。

from celery.signals import task_prerun, task_postrun
import logging

# to control the tasks that required logging mechanism
TASK_WITH_LOGGING = ['Proj.tasks.calc']
@task_prerun.connect(sender=TASK_WITH_LOGGING)
def prepare_logging(signal=None, sender=None, task_id=None, task=None, args=None, kwargs=None)
    logger = logging.getLogger(task_id)
    formatter = logging.Formatter('[%(asctime)s][%(levelname)s] %(message)s')
    # optionally logging on the Console as well as file
    stream_handler = logging.StreamHandler()
    stream_handler.setFormatter(formatter)
    stream_handler.setLevel(logging.INFO)
    # Adding File Handle with file path. Filename is task_id
    task_handler = logging.FileHandler(os.path.join('/tmp/', task_id+'.log'))
    task_handler.setFormatter(formatter)
    task_handler.setLevel(logging.INFO)
    logger.addHandler(stream_handler)
    logger.addHandler(task_handler)

@task_postrun.connect(sender=TASK_WITH_LOGGING)
def close_logging(signal=None, sender=None, task_id=None, task=None, args=None, kwargs=None, retval=None, state=None):
    # getting the same logger and closing all handles associated with it
    logger = logging.getLogger(task_id)
    for handler in logger.handlers:
        handler.flush()
        handler.close()
    logger.handlers = []

@app.task(base=CallbackTask, bind=True)
def calc(self, syntax):
    # getting logger with name Task ID. This is already
    # created and setup in prepare_logging
    logger = logging.getLogger(self.request.id)
    some_func()
    logger.info('started')

此处需要bind=True才能在任务中提供ID。每次执行任务<task_id>.log时,这将创建包含calc的单个日志文件。

答案 1 :(得分:1)

以下是我粗略的,未经考验的方法。将其视为指导而非生产级代码。

def get_or_create_task_logger(func):
    """ A helper function to create function specific logger lazily. """

    # https://docs.python.org/2/library/logging.html?highlight=logging#logging.getLogger
    # This will always result the same singleton logger
    # based on the task's function name (does not check cross-module name clash, 
    # for demo purposes only)
    logger = logging.getLogger(func.__name__)

    # Add our custom logging handler for this logger only
    # You could also peek into Celery task context variables here
    #  http://celery.readthedocs.org/en/latest/userguide/tasks.html#context
    if len(logger.handlers) == 0:
        # Log to output file based on the function name
        hdlr = logging.FileHandler('%s.log' % func.__name__)
        formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
        hdlr.setFormatter(formatter)
        logger.addHandler(hdlr) 
        logger.setLevel(logging.DEBUG)

    return logger

@app.task(base=CallbackTask)
def calc(syntax):
    logger = get_or_create_task_logger(calc)
    some_func()
    logger.info('started')