Workable / flask-log-request-id

Flask extension to track and log Request-ID headers produced by PaaS like Heroku and load balancers like Amazon ELB
MIT License
113 stars 23 forks source link

Flask in Celery context #56

Open POD666 opened 2 years ago

POD666 commented 2 years ago

Hi, I have tried to use enable_request_id_propagation with celery but during debugging found this:

image

I have a lot of things bound to my flask app (e.g. flask-sqlalchemy) so in celery, I just create an instance of my flask app to interact with DB and much more.

Since both flask and celery contexts are available, MultiContextRequestIdFetcher seems to handle it in the wrong way. I guess this code should be changed to iterate until a first non-empty value is returned instead of returning on a first non-exception result:

class MultiContextRequestIdFetcher(object):
    ...

    def __call__(self):
        for ctx_fetcher in self.ctx_fetchers:
            try:
                return ctx_fetcher()
            except ExecutedOutsideContext:
                continue
        return None

For now, I fixed it by reversing handlers in current_request_id during celery worker startup:

enable_request_id_propagation(celery)
current_request_id.ctx_fetchers = current_request_id.ctx_fetchers[::-1]