2

我已经实现了一个 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)。

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

4

0 回答 0