使用Python和Celery进行多模块日志记录

时间:2013-01-24 22:53:32

标签: python celery celery-task

我已经实现了一个使用一些外部库的Celery任务。

假设任务代码是这样的:

# mypackage.tasks
import logging
from extpackage1 import module1
from extpackage2 import module2

from celery import Celery
from celery.utils.log import get_task_logger

celery = Celery('tasks', broker='amqp://user:pass@host/vhname')

logger = get_task_logger(__name__)

@celery.task
def my_task(my_job_id):
    logger.info('My task executed with my_job_id=%s' % my_job_id)
    module1.func1()
    module2.func2()

虽然我导入的2个模块基本上是:

# extpackage1.module1
import logging

logger = logging.getLogger(__name__)    

def func1():
    # let's do something here ...
    logger.info('Logging inside module1')

# extpackage2.module2
import logging

logger = logging.getLogger(__name__)    

def func2():
    # let's do something here ...
    logger.info('Logging inside module2')

我想获取一个日志文件,其中包含每行中my_job_id的正确值,具体取决于执行的任务。

这将是:

[1][...other info..] My task executed with my_job_id=1
[1][...other info..] Logging inside module1
[1][...other info..] Logging inside module2
[2][...other info..] My task executed with my_job_id=2
[2][...other info..] Logging inside module1
[2][...other info..] Logging inside module2

我可以轻松地将my_job_id的值包含到任务记录器中,正确获取我在任务函数中记录的行(如[1][...other info..] My task executed with my_job_id=1[2][...other info..] My task executed with my_job_id=2)。

但是外部库呢?是否有一种优雅的方法来“包装”外部脚本生成的日志并根据我的要求对其进行格式化?

0 个答案:

没有答案
相关问题