-
First Check
Commit to Help
Example Codeimport logging
import uuid
from typing import Callable, Awaitable
import structlog
from fastapi import Depends, FastAPI, Request, Response
app = FastAPI()
Middleware = Callable[[Request], Awaitable[Response]]
logger = structlog.get_logger(__name__)
@app.middleware("http")
async def request_middleware(request: Request, call_next: Middleware) -> Response:
structlog.contextvars.clear_contextvars()
request_id = str(uuid.uuid4())
structlog.contextvars.bind_contextvars(request_id=request_id)
logger.info(
"request received (in middlware)",
method=request.method,
path=request.url.path,
client=request.client and request.client.host,
ua=request.headers.get("User-Agent"),
)
response = await call_next(request)
# THIS LINE WON'T INCLUDE in_dep="true"
logger.info("request finished (in middleware)")
response.headers["Request-ID"] = request_id
return response
def setup_logging() -> None:
"""Configure logging."""
logging.basicConfig(format="%(message)s", level="INFO")
processors = [
structlog.contextvars.merge_contextvars,
structlog.stdlib.add_logger_name,
structlog.stdlib.add_log_level,
structlog.stdlib.PositionalArgumentsFormatter(),
structlog.processors.TimeStamper(fmt="%Y-%m-%d %H:%M.%S"),
structlog.processors.StackInfoRenderer(),
structlog.processors.format_exc_info,
structlog.dev.ConsoleRenderer(),
]
structlog.configure(
processors=processors, # type: ignore
wrapper_class=structlog.stdlib.BoundLogger,
logger_factory=structlog.stdlib.LoggerFactory(),
cache_logger_on_first_use=True,
)
async def dep():
logger.info("dep start")
structlog.contextvars.bind_contextvars(in_dep="true")
logger.info("dep end")
return "foo"
@app.get("/")
async def home(value: str = Depends(dep)):
logger.info("hello")
return value
setup_logging() Descriptioncurl http://127.0.0.1:8001 The included code lets you reproduce the issue. This is what's logged:
In the last "request finished" line, I was expected It might be coming from Operating SystemmacOS Operating System DetailsNo response FastAPI Version0.75.0 Python Version3.9.10 Additional ContextTickets that seem relevant to this issue:
I have read the following pages: In the meantime I might be using https://github.com/snok/asgi-correlation-id |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
I have a similar case and for me it's not even related to |
Beta Was this translation helpful? Give feedback.
-
Experiencing the same thing here on 0.78.0. Just to add it seems like the context returned from contextvars.copy_context in structlog does not contain the updated/added vars. The global variable _CONTEXT_VARS in structlog does contain the added variables so it seems to not be a structlog issue. |
Beta Was this translation helpful? Give feedback.
-
same here, cannot seem to come up with a fix that would allow me to use structlog with fastapi. Because of concurrency, cannot use threadlocal, but contextvars don't seem to work either |
Beta Was this translation helpful? Give feedback.
FYI, for anyone searching for an answer, I was eventually able to solve the issue with starlette-context