Examples: Send OpenTelemetry Logs with the OpenTelemetry Python SDK

Note
Logs support in the OpenTelemetry Python SDK is currently experimental and is subject to change. Refer to the status for each language.

Send OpenTelemetry Logs from a Python Application to Honeycomb or an OpenTelemetry Collector 

This example uses the OpenTelemetry Python SDK’s logger provider to create log entries, and send them to Honeycomb or an OpenTelemetry Collector.

Acquire Dependencies 

First, install the OpenTelemetry API, SDK, and OTLP exporter packages:

pip install opentelemetry-api
pip install opentelemetry-sdk
pip install opentelemetry-exporter-otlp

Configure 

Next, create and configure the logger providers during application setup.

import logging

from opentelemetry._logs import set_logger_provider
from opentelemetry.exporter.otlp.proto.grpc._log_exporter import OTLPLogExporter
from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
from opentelemetry.sdk.resources import Resource

# Create and set the logger provider
logger_provider = LoggerProvider()
set_logger_provider(logger_provider)

# Create the OTLP log exporter that sends logs to configured destination
exporter = OTLPLogExporter()
logger_provider.add_log_record_processor(BatchLogRecordProcessor(exporter))

# Attach OTLP handler to root logger
handler = LoggingHandler(logger_provider=logger_provider)
logging.getLogger().addHandler(handler)

# You can use logging directly anywhere in your app now
logging.warning("Something interesting happened")

# Ensure the logger is shutdown before exiting so all pending logs are exported
logger_provider.shutdown()

Run 

Finally, to send logs to Honeycomb, run your application with some environment variables to set the service name and configure the exporter:

OTEL_SERVICE_NAME="my-service" \
  OTEL_EXPORTER_OTLP_ENDPOINT="https://api.honeycomb.io" \
  OTEL_EXPORTER_OTLP_HEADERS="x-honeycomb-team=<your-api-key>" \
  python app.py

Alternatively, to send logs to an OpenTelemetry collector, use these environment variables:

OTEL_SERVICE_NAME="my-service" \
  OTEL_EXPORTER_OTLP_ENDPOINT="my-collector:4317" \
  OTEL_EXPORTER_OTLP_INSECURE=true \
  python app.py