> ## Documentation Index
> Fetch the complete documentation index at: https://www.truefoundry.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Example: Python OpenTelemetrySDK Instrumentation

> Instrument Python applications using the OpenTelemetry SDK directly to send traces to TrueFoundry.

This guide demonstrates how to use OpenTelemetry SDK to instrument Python code and send traces to TrueFoundry's OtelCollector.

In this example, we'll show how to instrument a simple Python application with nested function calls using OpenTelemetry's context managers.

<Steps>
  <Step title="Create Tracing Project, API Key and copy tracing code">
    Follow the instructions in [Getting Started](/docs/tracing/tracing-getting-started) to create a tracing project, generate API key and copy the
    tracing code.
  </Step>

  <Step title="Install Dependencies">
    First, you need to install the following packages:

    ```shell lines theme={"dark"}
    pip install opentelemetry-api opentelemetry-sdk opentelemetry-exporter-otlp-proto-http python-dotenv
    ```
  </Step>

  <Step title="Add tracing code to Python application">
    To enable tracing, you'll need to configure opentelemetry sdk and intialize it.
    This section shows how to instrument your Python code using OpenTelemetry’s context managers. The example demonstrates nested function calls with proper tracing.

    <CodeGroup>
      ```python Python code {1-4,10-30,34-37,43} lines theme={"dark"}
      from opentelemetry import trace
      from opentelemetry.sdk.trace import TracerProvider
      from opentelemetry.sdk.trace.export import BatchSpanProcessor
      from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
      from dotenv import load_dotenv
      import os
      # Load environment variables from .env file
      load_dotenv()

      # Setup tracer provider
      provider = TracerProvider()
      trace.set_tracer_provider(provider)


      TFY_API_KEY = os.environ.get("TFY_API_KEY")
      # OTLP exporter (HTTP)
      otlp_exporter = OTLPSpanExporter(
          endpoint="{enter_your_api_endpoint}/v1/traces",
          headers={
              "Authorization": f"Bearer {TFY_API_KEY}",
              "TFY-Tracing-Project": "<enter_your_tracing_project_fqn>",
          }
      )

      # Span processor using batch (recommended for production)
      span_processor = BatchSpanProcessor(otlp_exporter)
      provider.add_span_processor(span_processor)

      # Get tracer
      tracer = trace.get_tracer(__name__)

      # Child function — will create its own span
      def greet_user(name):
          with tracer.start_as_current_span("greet_user_task") as span:
              # Add attributes to the span
              span.set_attribute("user.name", name)
              span.set_attribute("greeting.type", "welcome")

              print(f"Hello, {name}!")

      # Parent function — also creates a span and calls the child
      def main():
          with tracer.start_as_current_span("main_task"):
              user_name = "Sateesh"
              greet_user(user_name)
              print("Main task finished.")

      # Run the main function
      main()
      ```
    </CodeGroup>
  </Step>

  <Step title="Run your application and view logged trace">
    <Frame caption="">
      <img src="https://mintcdn.com/truefoundry/2MMcllD7kMlpnaWX/images/tracing_python_with_opentelemetry.png?fit=max&auto=format&n=2MMcllD7kMlpnaWX&q=85&s=f934cd37d195cbef0c8279ff6b0e0933" width="3024" height="1714" data-path="images/tracing_python_with_opentelemetry.png" />
    </Frame>
  </Step>
</Steps>
