OpenTelemetry Kubernetes Resource Detector

0.3.0 · active · verified Sat Apr 11

This OpenTelemetry package is designed to automatically populate resource attributes for Kubernetes pods. It enriches telemetry data (traces, metrics, and logs) with essential metadata about the Kubernetes environment, such as pod names, namespaces, and container IDs, providing crucial context for observability. The current version is 0.3.0.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to instantiate and use the `KubernetesResourceDetector` to gather Kubernetes-specific resource attributes. The detected attributes are then printed. In a full OpenTelemetry setup, this `resource` object would be passed to a `TracerProvider`, `MeterProvider`, or `LoggerProvider` to enrich all emitted telemetry.

import os
from opentelemetry.sdk.resources import get_aggregated_resources, Resource
from opentelemetry_resourcedetector_kubernetes import KubernetesResourceDetector

# Create a base resource (optional, but good practice for service name)
base_resource = Resource.create({
    "service.name": os.environ.get("OTEL_SERVICE_NAME", "my-kubernetes-app"),
    "service.version": "0.1.0"
})

# Aggregate resources from the Kubernetes detector and other potential detectors
# In a real Kubernetes environment, this will detect k8s.pod.uid, container.id, etc.
resource = get_aggregated_resources([
    KubernetesResourceDetector(),
    # Add other detectors here if needed, e.g., HostDetector(), OSDetector()
], initial_resource=base_resource)

print("Detected Resource Attributes:")
for key, value in resource.attributes.items():
    print(f"  {key}: {value}")

# The 'resource' object is then passed to a TracerProvider, MeterProvider, or LoggerProvider
# Example (conceptual, requires OpenTelemetry SDK tracing/metrics packages):
# from opentelemetry.sdk.trace import TracerProvider
# tracer_provider = TracerProvider(resource=resource)

view raw JSON →