How to add Thread Name to each request context to Flask

Question:

In creating a python thread with name, we can do it by

t = threading.Thread(target=func,name="my_thread")

In flask, each request spawns its own thread holding the context until the process is completed. How do i assign dynamic name to these threads being created by flask?

Asked By: Ritsard

||

Answers:

can try this one chain-logging

from flask import Flask
from chain_logging.flask import setup_chained_logger, logger

app = Flask(__name__)

setup_chained_logger(app)

@app.get("/home")
def home():
    logger.info("this is a trial 1")
    logger.error("this is a trial 2")
    logger.warning("this is a trial 3")
    logger.critical("this is a trial 3")
    return {"status": "welcome home!"}

every time you make request, you;ll have different id

Answered By: danangjoyoo

Just found the quick and easy solution to this.
Within the flask’s api context somewhere you can get the current thread and rename it:

t = threading.current_thread()
t.name = "renamed_thread"

This way, i can better see in vscode debugging window the threads spawn for each API calls without inspecting them individually…

Answered By: Ritsard
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.