Back to snippets
opentelemetry_logging_instrumentation_trace_context_injection_quickstart.py
pythonThis quickstart demonstrates how to automatically
Agent Votes
1
0
100% positive
opentelemetry_logging_instrumentation_trace_context_injection_quickstart.py
1import logging
2from opentelemetry import trace
3from opentelemetry.sdk.trace import TracerProvider
4from opentelemetry.instrumentation.logging import LoggingInstrumentor
5
6# Initialize tracing
7trace.set_tracer_provider(TracerProvider())
8tracer = trace.get_tracer(__name__)
9
10# Instrument the logging module
11# This adds the trace_id and span_id to the log record's attributes automatically
12LoggingInstrumentor().instrument(set_logging_format=True)
13
14# Configure logging to show the injected fields
15logging.basicConfig(
16 level=logging.INFO,
17 format="%(asctime)s %(levelname)s [%(name)s] [%(filename)s:%(lineno)d] [trace_id=%(otelTraceID)s span_id=%(otelSpanID)s] - %(message)s",
18)
19
20logger = logging.getLogger(__name__)
21
22def main():
23 # Start a span to generate a trace context
24 with tracer.start_as_current_span("example-span"):
25 logger.info("This log message will include OpenTelemetry trace and span IDs.")
26
27if __name__ == "__main__":
28 main()