question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to pass correlation_id to tasks executed in a multithreaded environment?

See original GitHub issue

EDIT: 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:closed
  • Created a year ago
  • Comments:5 (3 by maintainers)

github_iconTop GitHub Comments

2reactions
philippefutureboycommented, Jul 20, 2022

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:

def run_all(
    tasks: Dict[str, TaskTuple],
    pass_contextvars: bool = False,
    max_workers: int = 20,
):
    exec_kwargs = {}
    if pass_contextvars:
        parent_context = contextvars.copy_context()
        exec_kwargs = {"initializer": _set_context, "initargs": (parent_context,)}

    with ThreadPoolExecutor(max_workers=max_workers, **exec_kwargs) as executor:
        jobs = {}
        for name, task in tasks.items():
            fn, args, kwargs = task
            kwargs = kwargs.copy()
            jobs[executor.submit(fn, *args, **kwargs)] = name

    return {
        name: future.result()
        for future, name in zip(as_completed(jobs.keys()), jobs.values())
    }


def _set_context(context):
    for var, value in context.items():
        var.set(value)

Closing the issue!

0reactions
JonasKscommented, Jul 20, 2022

Perfect😊

Read more comments on GitHub >

github_iconTop 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 >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found