Middleware correlating project logs to individual requests
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Context variables for storing and accessing correlation IDs throughout async request and task execution, providing thread-safe access to tracking identifiers across the entire application lifecycle.
Context variable that stores the correlation ID for the current HTTP request, making it accessible throughout the request processing lifecycle.
correlation_id: ContextVar[Optional[str]]This context variable:
NoneThe correlation_id is automatically set by CorrelationIdMiddleware and remains available throughout the entire request processing, including:
Context variable that tracks the correlation ID of the parent process that spawned the current Celery task, enabling hierarchical tracing across distributed task processing.
celery_parent_id: ContextVar[Optional[str]]This context variable:
NoneUse cases for parent ID tracking:
Context variable that stores a unique identifier for the current Celery task process, providing task-specific correlation tracking.
celery_current_id: ContextVar[Optional[str]]This context variable:
NoneThe current ID can be:
use_internal_celery_task_id=True)from asgi_correlation_id import correlation_id
import logging
logger = logging.getLogger(__name__)
async def process_data(data):
# Get current correlation ID
current_id = correlation_id.get()
if current_id:
logger.info(f"Processing data for request {current_id}")
else:
logger.info("Processing data outside request context")
# Process data...
return resultfrom asgi_correlation_id import correlation_id
async def background_task():
# Set correlation ID for background processing
correlation_id.set("background-task-123")
# Process task...
logger.info("Background task processing") # Will include correlation ID
# Clear when done (optional, context will be cleaned up automatically)
correlation_id.set(None)from asgi_correlation_id import celery_current_id, celery_parent_id
from celery import Celery
app = Celery('tasks')
@app.task
def process_task(data):
current = celery_current_id.get()
parent = celery_parent_id.get()
logger.info(f"Task {current} spawned by {parent}")
# Process task...
return resultContext variables are automatically managed:
All context variables use Python's contextvars module, providing:
Context variables are inherited by:
contextlib.copy_context()from contextvars import ContextVar
from typing import Optional
# Context variable type definitions
CorrelationIdVar = ContextVar[Optional[str]]
CeleryParentIdVar = ContextVar[Optional[str]]
CeleryCurrentIdVar = ContextVar[Optional[str]]Install with Tessl CLI
npx tessl i tessl/pypi-asgi-correlation-id