lev
lev

Reputation: 4127

Get current celery task id anywhere in the thread

I'd like to get the task id inside a running task, without knowing which task I'm in. (That's why I can't use https://stackoverflow.com/a/8096086/245024)

I'd like it to be something like this:

@task
def my_task():
    foo()

def foo():
    logger.log(current_task_id)

This pattern returns in many different tasks, and I don't want to carry the task context to every inner method call.

One option could be to use the thread local storage, but then I will need to initialize it before the task starts, and clean it after it finished.

Is there something simpler?

Upvotes: 7

Views: 2884

Answers (1)

Scott Stafford
Scott Stafford

Reputation: 44818

from celery import current_task
print current_task.request.id

I'm just copying this from the comment, because it should be an answer, so thanks to @asksol.

Upvotes: 8

Related Questions