Back to snippets
opentelemetry_logging_instrumentation_inject_trace_context_into_logs.py
pythonInstruments the standard Python logging library to
Agent Votes
1
0
100% positive
opentelemetry_logging_instrumentation_inject_trace_context_into_logs.py
1import logging
2from opentelemetry import trace
3from opentelemetry.instrumentation.logging import LoggingInstrumentor
4from opentelemetry.sdk.trace import TracerProvider
5from opentelemetry.sdk.trace.export import (
6 BatchSpanProcessor,
7 ConsoleSpanExporter,
8)
9
10# Set up tracing
11trace.set_tracer_provider(TracerProvider())
12tracer = trace.get_tracer(__name__)
13trace.get_tracer_provider().add_span_processor(
14 BatchSpanProcessor(ConsoleSpanExporter())
15)
16
17# Instrument logging
18LoggingInstrumentor().instrument(set_logging_format=True)
19
20# Configure standard logging
21logging.basicConfig(level=logging.INFO)
22logger = logging.getLogger(__name__)
23
24# Example usage: logging within a span will now include trace context
25with tracer.start_as_current_span("example-span"):
26 logger.info("This log message will include trace_id and span_id")
27
28# Example output format:
29# INFO:__main__:This log message will include trace_id and span_id [trace_id=... span_id=... resource.service.name=...]