0

I have a Flask Service and I want to log a correlationID for all log messages. I found this blog post which makes use of threading.local().

My Flask service uses gunicorn and gevent:

gunicorn --worker-class=gevent \
         --worker-connections=1000 \
         --bind 0.0.0.0:5000 myapp.app:app
         --workers=4 --timeout 120 --keep-alive 120

Can threading.local() be used for a request?

I guess ...

  1. each worker is a different process and
  2. each connection is a different thread and
  3. each request is on exactly one thread, if I don't explicitly start another thread?

But when I start another thread, I would need to pass the correlationId explicitly, right?

(In case it matters: I use Python 3.7)

Martin Thoma
  • 124,992
  • 159
  • 614
  • 958

1 Answers1

0

If you are asking if you can use threading locals to pass request objects around, that is what flask does internally already.

# context locals
_request_ctx_stack = LocalStack()
_app_ctx_stack = LocalStack()
current_app = LocalProxy(_find_app)
request = LocalProxy(partial(_lookup_req_object, 'request')) # Here
session = LocalProxy(partial(_lookup_req_object, 'session'))
g = LocalProxy(partial(_lookup_app_object, 'g'))

If you are asking if you can pass your own object around from the thread locals, you can do that as well since that's basically what flask does.

But apparently flask recommends werkzeug.local

https://werkzeug.palletsprojects.com/en/0.15.x/local/

Işık Kaplan
  • 2,815
  • 2
  • 13
  • 28