7
votes

I run multiple gunicorn workers with workers=4 setting. So as I understand I have 5 different processes: one gunicorn master process and 4 other worker processes. Can I get information about which worker is serving request at the moment? So can I get any worker id from inside worker itself like for each request send back a response with content: this request was served by worker:worker_id?

2
Were you able to solve it? If yes, can you provide the example. - neel
@neel, so inside your worker code just simply call import os; print(os.getpid()) - Most Wanted
@MostWanted Please make this an answer - jtlz2

2 Answers

10
votes

Within a worker code just use

import os
print(os.getpid())

Process id is a good enough identifier for such a case. Another option which is overkill obviously is to create a worker-id-file for each worker at this point https://docs.gunicorn.org/en/stable/settings.html?highlight=hooks#post-worker-init and read from it when needed. Do not forget to remove this file on exit https://docs.gunicorn.org/en/stable/settings.html?highlight=hooks#worker-exit

0
votes

For debugging purpose, you may use post_request hook to log the worker pid

def post_response(worker, req, environ, resp):
    worker.log.debug("%s", worker.pid)