Splunk OpenTelemetry Python

2.9.0 · active · verified Thu Apr 16

The `splunk-opentelemetry` Python distribution provides automatic and manual instrumentation for Python applications, collecting traces, metrics, and logs using OpenTelemetry. It bundles OpenTelemetry SDK and API components, along with exporters and instrumentations specifically configured for Splunk Observability Cloud. The current version is 2.9.0, with regular releases tied to upstream OpenTelemetry Python component updates.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates programmatic initialization of the Splunk OpenTelemetry Python SDK and a simple traced operation. Ensure that `OTEL_EXPORTER_OTLP_ENDPOINT`, `OTEL_SERVICE_NAME`, and optionally `SPLUNK_ACCESS_TOKEN` environment variables are set before running, pointing to your OpenTelemetry Collector or Splunk HEC endpoint.

import os
from opentelemetry import trace
from splunk_opentelemetry.instrumentation import SplunkOpenTelemetryConfigurator

# Set required environment variables for the Splunk OTLP exporter
# In a real application, these would typically be set in the shell or deployment config.
# For a local OpenTelemetry Collector (e.g., Splunk Distribution of OpenTelemetry Collector),
# the endpoint might be http://localhost:4318 for HTTP or http://localhost:4317 for gRPC.
os.environ['OTEL_SERVICE_NAME'] = os.environ.get('OTEL_SERVICE_NAME', 'my-python-app')
os.environ['OTEL_EXPORTER_OTLP_ENDPOINT'] = os.environ.get('OTEL_EXPORTER_OTLP_ENDPOINT', 'http://localhost:4318')
os.environ['SPLUNK_ACCESS_TOKEN'] = os.environ.get('SPLUNK_ACCESS_TOKEN', 'YOUR_SPLUNK_ACCESS_TOKEN') # Only required if sending directly to Splunk HEC

# Configure the OpenTelemetry SDK for Splunk Observability Cloud
# This initializes the TracerProvider, MeterProvider, and sets up
# the OTLP exporter with Splunk-specific resource attributes.
# It reads configuration from environment variables.
SplunkOpenTelemetryConfigurator().configure()

# Get a tracer configured by the Splunk OpenTelemetry SDK
tracer = trace.get_tracer(__name__)

# Perform a simple operation within a trace
with tracer.start_as_current_span("my-quickstart-operation") as span:
    print(f"Starting span: {span.name}")
    # Add an attribute to the span
    span.set_attribute("http.method", "GET")
    span.set_attribute("http.url", "/api/data")

    # Simulate some work
    import time
    time.sleep(0.1)

    with tracer.start_as_current_span("inner-work") as inner_span:
        print(f"  Starting inner span: {inner_span.name}")
        inner_span.set_attribute("data.size", 1024)
        time.sleep(0.05)
        print(f"  Finishing inner span: {inner_span.name}")

    print(f"Finishing span: {span.name}")

print("\nTracing complete. Data should be sent to the configured OTLP endpoint.")
print("Ensure an OpenTelemetry Collector or Splunk HEC is listening at the endpoint.")

view raw JSON →