Search code examples
pythoncelerycelery-task

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.


Solution

  • Use the celeryd_after_setup signal to capture the worker name like this:

    from celery.signals import celeryd_after_setup
    
    @celeryd_after_setup.connect
    def capture_worker_name(sender, instance, **kwargs):
        os.environ["WORKER_NAME"] = '{0}'.format(sender)