简体   繁体   中英

How do I get the request id from RequestIDLogFilter in python flask?

So, in my main app.py , I have:

app = create_app()

...
app.run()

In __init__.py I have:

def create_app():
  ...
  app = Flask(__name__)
  setup_logging(app)
  return app

def setup_logging(app):
  RequestID(app)
  handler = logging.FileHandler(app.container.config.get("app.LOG_FILE"))
  handler.setFormatter(logging.Formatter("%(asctime)s : %(levelname)s : %(request_id)s - %(message)s"))
  handler.addFilter(RequestIDLogFilter())  # << Add request id contextual filter
  logging.getLogger().addHandler(handler)
  logging.getLogger().setLevel(level="DEBUG")

And in my routes.py , I have: (This wiring/linking is done with the help of dependency injection)

def configure(app):
    app.add_url_rule("/", "check", check)
    ...

def check():
    logging.info("You hit /")
     # Here I want to return the Request UUID that's generated by RequestLogIDFilter
    return make_response(jsonify(dict(ok=True)), 200)

How do I access the Request UUID generated by the RequestLogIDFilter ? In my log file I correctly see the log messages as:

2022-08-15 07:00:18,030 : INFO : 27b437fd-98be-4bc9-a609-912043e3a38e - Log message test memberId=9876

I want to take this value 27b437fd-98be-4bc9-a609-912043e3a38e and include it in the response headers as X-REQUEST-UUID: 27b437fd-98be-4bc9-a609-912043e3a38e


An alternative was to rip out RequestLogIDFilter and only work with flask-request-id-header except, there's no way to write it to log file ( logging.FileHandler does not have a write() method so it fails)


This is something trivial I'm sure but the official docs nowhere mention how to access these request ids for logging to file or sending back as a response header.

If you are using flask_log_request_id then you probably want this as given in their github repo

Code copied here in case link does not work

from flask_log_request_id import current_request_id

@app.after_request
def append_request_id(response):
    response.headers.add('X-REQUEST-ID', current_request_id())
    return response

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM