Sobes.tech
Junior — Middle

How is the trace ID passed and displayed in system logs?

sobes.tech AI

Answer from AI

A unique trace ID is usually passed through the execution context and included in logs to correlate events in distributed systems.

In Python, this can be implemented as follows:

  1. Generate a unique trace ID (e.g., UUID) at the start of request processing.
  2. Pass this ID through the context (e.g., using contextvars or function parameters).
  3. Use a formatter in logs that adds the trace ID to each record.

Example using the standard logging module and contextvars:

import logging
import uuid
import contextvars

trace_id_var = contextvars.ContextVar('trace_id')

class TraceIdFilter(logging.Filter):
    def filter(self, record):
        record.trace_id = trace_id_var.get('no-trace-id')
        return True

logger = logging.getLogger()
handler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(trace_id)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.addFilter(TraceIdFilter())
logger.setLevel(logging.INFO)

# At the beginning of request processing
trace_id_var.set(str(uuid.uuid4()))

logger.info('Start of request processing')

# In logs, it will look like:
# 2024-06-01 12:00:00,000 - 123e4567-e89b-12d3-a456-426614174000 - INFO - Start of request processing

Thus, the trace ID is passed through the context and displayed in logs for easier tracing and debugging.