OpenTelemetry gRPC Instrumentation

0.61b0 · active · verified Thu Apr 09

This library provides automatic instrumentation for gRPC clients and servers within the OpenTelemetry Python ecosystem. It's part of the `opentelemetry-python-contrib` repository, currently at version `0.61b0`. As a `contrib` package, its release cadence often aligns with the main OpenTelemetry Python project, receiving frequent updates to add features, fix bugs, and align with new OpenTelemetry specifications.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up and enable OpenTelemetry gRPC instrumentation. It configures a basic `TracerProvider` with a `ConsoleSpanExporter` (for printing spans to the console) and then initializes the `GrpcInstrumentor`. Once `instrument()` is called, all subsequent `grpc.insecure_channel`, `grpc.secure_channel`, and `grpc.server` creations will be automatically instrumented. No actual gRPC server is run here, but the channel creation demonstrates the patched behavior.

import grpc
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor
from opentelemetry.instrumentation.grpc import GrpcInstrumentor

# 1. Configure OpenTelemetry Tracer Provider
resource = Resource.create({"service.name": "my-grpc-app"})
tracer_provider = TracerProvider(resource=resource)
tracer_provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter()))
trace.set_tracer_provider(tracer_provider)

# 2. Initialize gRPC Instrumentation
GrpcInstrumentor().instrument()

# Now any gRPC client or server interactions will be automatically instrumented.
# Example (no actual gRPC server running, just showing the channel creation):
print("OpenTelemetry gRPC instrumentation initialized.")
print("Any grpc.insecure_channel or grpc.secure_channel calls from now on will be instrumented.")

try:
    # This part would typically be your actual gRPC client/server code
    channel = grpc.insecure_channel('localhost:50051')
    # Example: call a method (this would require a real gRPC setup)
    # stub = YourServiceStub(channel)
    # response = stub.YourMethod(YourRequest())
    print("Created a gRPC channel (if a server was running, it would be instrumented).")
    channel.close()
except Exception as e:
    print(f"An error occurred (expected if no gRPC server is running): {e}")

print("Check console for exported spans.")

view raw JSON →