OpenTelemetry Logging Instrumentation

0.61b0 · active · verified Wed Apr 01

The `opentelemetry-instrumentation-logging` library provides automatic instrumentation for Python's standard `logging` module. It converts native Python log messages into OpenTelemetry logs, enabling correlation with traces and metrics, and facilitates their export to an observability backend. Part of the `opentelemetry-python-contrib` project, this library is currently in beta (version 0.61b0) and undergoes regular releases as part of the broader OpenTelemetry Python ecosystem.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up `opentelemetry-instrumentation-logging` to capture standard Python log messages and export them. It configures a `LoggerProvider` with a `ConsoleLogRecordExporter` for easy viewing, enables the `LoggingInstrumentor` to inject trace context, and shows a log message emitted within an active span for correlation.

import logging
from opentelemetry import trace
from opentelemetry._logs import set_logger_provider
from opentelemetry.sdk._logs import LoggerProvider
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor, ConsoleLogRecordExporter
from opentelemetry.sdk.resources import Resource
from opentelemetry.instrumentation.logging import LoggingInstrumentor

# Configure a basic logger
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 1. Configure OpenTelemetry Resource
resource = Resource.create({
    "service.name": "my-python-logging-app",
    "service.instance.id": "instance-1"
})

# 2. Configure LoggerProvider with a processor and exporter
# For demonstration, using ConsoleLogRecordExporter to print to stdout
# In a real application, you'd use OTLPLogExporter or another backend exporter.
log_exporter = ConsoleLogRecordExporter()
log_processor = BatchLogRecordProcessor(log_exporter)
logger_provider = LoggerProvider(resource=resource)
logger_provider.add_log_record_processor(log_processor)
set_logger_provider(logger_provider)

# 3. Instrument the standard logging module
# set_logging_format=True enables trace context injection into log format
LoggingInstrumentor().instrument(set_logging_format=True)

# 4. Use standard logging, which will now be captured by OpenTelemetry
logger.info("This is a regular Python log message.")

# 5. Demonstrate log correlation with an active trace span
tracer = trace.get_tracer("my-tracer")
with tracer.start_as_current_span("my-operation") as span:
    span.set_attribute("operation.id", "xyz123")
    logger.warning("This log message is inside a span, so it should be correlated.")

# 6. Shut down the logger provider to ensure all logs are exported
logger_provider.shutdown()
print("Logs sent to console (or configured exporter).")

view raw JSON →