Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 307
imichaeldotorg Avatar asked May 25 '14 15:05

imichaeldotorg


People also ask

How do I get task ID in the celery task?

To obtain the value of task_id you first have to create an instance of that class, afterwards accessing async_result_instance. task_id will return you the real id. In your updated code: @celery.

How do I check the status of my Celery worker?

celery -A yourproject. app inspect status will give the status of your workers. celery -A yourproject. app inspect active will give you list of tasks currently running, etc.

What is worker in Celery?

When you run a celery worker, it creates one parent process to manage the running tasks. This process handles the book keeping features like sending/receiving queue messages, registering tasks, killing hung tasks, tracking status, etc.

What is Shared_task in Celery?

The "shared_task" decorator allows creation of Celery tasks for reusable apps as it doesn't need the instance of the Celery app. It is also easier way to define a task as you don't need to import the Celery app instance.


1 Answers

I also needed the worker name for reporting purposes so I tried @cacois solution but it doesn't seem to work with eventlet (current_process() doesn't have an initargs attribute). So I'll leave my solution here for future references:

from celery import task

@task(bind=True)
def getName(self):
    return self.request.hostname

The name of the attribute sounds weird to me, but that contains the name specified with the "-n" option when launching the worker. self works like you would expect from a class method, you don't need to specify it when calling the function (eg: getName.delay()).

like image 168
Adrian Macias Avatar answered Oct 06 '22 01:10

Adrian Macias