Get the name of celery worker from inside a celery task?

imichaeldotorg picture imichaeldotorg · May 25, 2014 · Viewed 7.8k times · Source

I'd like a celery task to be able to get the name of the worker executing it, for logging purposes. I need to handle this from within the task, rather than querying the broker directly. Is there a way to do this? I'm using celery with RabbitMQ, if that matters.

Answer

Roy Iacob picture Roy Iacob · May 25, 2014

You need to utilize billiard which holds the workers:

from celery import task
from billiard import current_process

@task
def getName():
    p = current_process()
    return p.index

Then make a global dictionary that maps ids->names on process creation.