Cannot set or retrieve request_id and correlation_id on request
I am trying to handle the request_id and correlation_id on the logs to use them in other parts of the application.
If a user does not provide them in the request headers we cannot either inject the via META (as it only checks the existance of headers). We also cannot retrieve the values set.
one proposal could be to also check the value in get_request_header like
def get_request_header(request: "HttpRequest", header_key: str, meta_key: str) -> Any:
if hasattr(request, "headers") and request.headers.get(header_key):
return request.headers.get(header_key)
return request.META.get(meta_key)
another could be to store the context in the class variable so that it is accessible another could be to allow these values to be set on the init of the object
Have you considered using the signal bind_extra_request_metadata to do what you need to do?
from django.dispatch import receiver
from django_structlog import signals
import structlog
@receiver(signals.bind_extra_request_metadata)
def bind_correlation_id(request, logger, log_kwargs, **kwargs):
structlog.contextvars.bind_contextvars(correlation_id=request.META.get("SOMETHING"))
To retrieve the values you can do it this way:
import structlog
import logging
logger = logging.getLogger(__name__)
...
context = structlog.contextvars.get_merged_contextvars(logger)
if "correlation_id" in context:
... # do something
@konchristopoulos did that solve your issue?