django-structlog icon indicating copy to clipboard operation
django-structlog copied to clipboard

Cannot set or retrieve request_id and correlation_id on request

Open konchristopoulos opened this issue 11 months ago • 3 comments

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

konchristopoulos avatar Mar 20 '25 16:03 konchristopoulos

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"))

jrobichaud avatar Apr 05 '25 00:04 jrobichaud

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

jrobichaud avatar Apr 05 '25 00:04 jrobichaud

@konchristopoulos did that solve your issue?

jrobichaud avatar Apr 14 '25 20:04 jrobichaud