OpenTelemetry Docker Resource Detector

0.4.0 · active · verified Sat Apr 11

opentelemetry-resourcedetector-docker is a Python package for OpenTelemetry that automatically enriches telemetry data with resource attributes derived from the Docker container environment where the application is running. Currently at version 0.4.0, it is actively maintained with releases as needed to align with OpenTelemetry Python SDK and address Docker-related detection specifics.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the OpenTelemetry SDK with the `DockerResourceDetector` to automatically gather Docker-related resource attributes. The collected attributes are then used by a `TracerProvider` and printed to the console via a `ConsoleSpanExporter`. Ensure Docker is running and the application has permissions to access the Docker socket for successful detection.

import os
from opentelemetry.sdk.resources import get_aggregated_resources
from opentelemetry_resourcedetector_docker import DockerResourceDetector
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor

# Configure the resource detector. DockerResourceDetector requires access to the Docker socket.
# Ensure your application has read access to /var/run/docker.sock (Linux) or similar.
# For demonstration, we'll try to detect, but actual attributes depend on Docker environment.
resource = get_aggregated_resources([
    DockerResourceDetector()
])

# Optional: Add a service name if not detected by environment variables or other detectors
if not resource.attributes.get('service.name'):
    resource = resource.merge(Resource({'service.name': 'my-docker-app'}))

# Set up a TracerProvider with the detected resource
provider = TracerProvider(resource=resource)

# Configure a simple console exporter for demonstration
span_processor = SimpleSpanProcessor(ConsoleSpanExporter())
provider.add_span_processor(span_processor)

# Set the global tracer provider
from opentelemetry import trace
trace.set_tracer_provider(provider)

# Get a tracer and create a span
tracer = trace.get_tracer(__name__)

with tracer.start_as_current_span("my-docker-operation") as span:
    span.set_attribute("environment", os.environ.get('APP_ENV', 'development'))
    print(f"Span created with resource attributes: {resource.attributes}")
    print("Look for 'container.id' or other Docker-related attributes in the output.")

view raw JSON →