Skip to content

Instantly share code, notes, and snippets.

@tobert
Last active September 2, 2021 17:50
Show Gist options
  • Save tobert/dec078629c6c966b7b6759e78a9915bc to your computer and use it in GitHub Desktop.
Save tobert/dec078629c6c966b7b6759e78a9915bc to your computer and use it in GitHub Desktop.
custom traceparent propragation in python
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry import context
from opentelemetry.instrumentation.requests import RequestsInstrumentor
from opentelemetry.instrumentation.grpc import GrpcInstrumentorClient
from opentelemetry import propagate
trace.set_tracer_provider(TracerProvider())
tracer = trace.get_tracer_provider().get_tracer(__name__)
# opentelemetry-python does not support OTEL_EXPORTER_OTLP_INSECURE so do it here
# https://opentelemetry-python.readthedocs.io/en/latest/exporter/otlp/otlp.html
otel_insecure = os.getenv("OTEL_EXPORTER_OTLP_INSECURE", "false").lower() in ("1", "true")
trace.get_tracer_provider().add_span_processor(BatchSpanProcessor(OTLPSpanExporter(insecure=otel_insecure)))
RequestsInstrumentor().instrument()
GrpcInstrumentorClient().instrument()
def load_otel_traceparent(kernel_tp):
"""
Sets up OpenTelemetry after loading traceparent from either the kernel
cmdline or the TRACEPARENT environment variable.
"""
traceparent = None
if kernel_tp is None:
traceparent = os.getenv("TRACEPARENT")
if traceparent is None or not traceparent.strip():
return
else:
traceparent = kernel_tp
if traceparent is not None:
# use the otel code to "extract" the traceparent from the given hash
# which is a fancy way of saying it wants a map with a key called
# "traceparent" that it will parse and then return a loaded context
ctx = propagate.extract({"traceparent": [traceparent]})
# this is what sets the context for everything else tha happens in the program
context.attach(ctx)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment