How to pass correlation_id to tasks executed in a multithreaded environment?
See original GitHub issueEDIT: Changed the name of the issue for better searchability; you can find the solution to the question here
Hey there!
I feel pretty stupid asking this question, but can you explain to me how I should create my logger instance to have a correlation_id?
Currently I create my logger at the top of the a router file:
import logging
from fastapi import APIRouter, HTTPException
LOG = logging.getLogger(__name__)
router = APIRouter(prefix="/my/route", responses={404: {"description": "Not found"}})
@router.get("/")
def handler():
LOG.info("Hello!")
And I get
[2022-07-19T20:37:48] INFO [None] path.to.module | Hello
when my logging configuration is as follows:
"formatters": {
"default": {
"format": "[%(asctime)s] %(levelname)s [%(correlation_id)s] %(name)s | %(message)s",
"datefmt": "%Y-%m-%dT%H:%M:%S",
}
},
app.add_middleware(
CorrelationIdMiddleware,
header_name='X-Request-ID',
generator=lambda: uuid4().hex,
validator=is_valid_uuid4,
transformer=lambda a: a,
)
– I would like to have my correlation_id show up in my log like so:
[2022-07-19T20:37:48] INFO [8fe9728a] path.to.module | Hello
I can’t get anything about it in both the Starlette and FastAPI documentation. It’s like everybody knows this and it’s not worth mentionning 🤔
Can you give me an example of how I should get a logger instance to have the request id show up?
Thanks for your help!
Issue Analytics
- State:
- Created a year ago
- Comments:5 (3 by maintainers)
Top Results From Across the Web
Correlation ID in multi-threaded and multi-process application
Generate a UUID and pass it as a header into the request. ... Your thread doing the task should just be aware of...
Read more >Logging in a multithreaded environment and with ... - Medium
Basically, it stores the current MDC context and sets it up just before the task is about to get executed by Executor E2....
Read more >Passing correlation id across requests - Hi, I'm Ankit
The code – Passing correlation id to logs. The CorrelationIdContext class below helps us to set and get the correlation id for a...
Read more >Tasks and Parallelism: The New Wave of Multithreading
The first task will execute on a background thread and when it is complete, its callback as defined in its ContinueWith method will...
Read more >Correlation IDs in Scala using Monix by Adam Warski
Read more and become a Correlation ID expert! ... This is useful for threading Locals through execution contexts. ... -Dmonix.environment.
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Thanks for the additional info Jonas! That was enough to solve the issue 👌
I took the solution presented in this medium article as a way to transfer the contextvars.
Here’s my final impl for the run_all ThreadPoolExecutor function:
Closing the issue!
Perfect😊