Report Python application data using OpenTelemetry

Updated at:

Instrument your Python application with OpenTelemetry and report trace data to Cloud Monitor 2.0. You can then view application topology, call traces, abnormal transactions, slow transactions, and SQL analysis. OpenTelemetry supports both automatic and manual instrumentation through its Python agent and SDK.

Important

We recommend using the Alibaba Cloud proprietary Python probe.

Compared to open-source implementations, the Alibaba Cloud Python probe provides observability into common large language model (LLM) frameworks, such as llama-index, dify, langchain, openai, and Qwen. It also provides richer metrics, traces, and continuous profiling data. For more information, see Manually install the Python probe.

Prerequisites

Python 3.7 or later.

Background information

OpenTelemetry provides automatic instrumentation plugins that create spans for common frameworks. The following table lists the supported frameworks. For a complete list, see the official OpenTelemetry documentation.

Note

Version ~= V.N means ≥ V.N and == V.*. For example, aiohttp ~= 3.0 requires the aiohttp version to be aiohttp ≥ 3.0 and aiohttp == 3.*.

Supported Python frameworks

OpenTelemetry plugin

Supported packages and versions

opentelemetry-instrumentation-aio-pika

aio_pika - [7.2.0, 10.0.0)

opentelemetry-instrumentation-aiohttp-client

aiohttp ~= 3.0

opentelemetry-instrumentation-aiohttp-server

aiohttp ~= 3.0

opentelemetry-instrumentation-aiopg

aiopg - [0.13.0, 2.0.0)

opentelemetry-instrumentation-asgi

asgiref ~= 3.0

opentelemetry-instrumentation-asyncpg

asyncpg ≥ 0.12.0

opentelemetry-instrumentation-aws-lambda

aws_lambda

opentelemetry-instrumentation-boto

boto ~= 2.0

opentelemetry-instrumentation-boto3sqs

boto3 ~= 1.0

opentelemetry-instrumentation-botocore

botocore ~= 1.0

opentelemetry-instrumentation-cassandra

  • cassandra-driver ~= 3.25

  • scylla-driver ~= 3.25

opentelemetry-instrumentation-celery

celery - [4.0, 6.0)

opentelemetry-instrumentation-confluent-kafka

confluent-kafka - [1.8.2, 2.2.0]

opentelemetry-instrumentation-dbapi

dbapi

opentelemetry-instrumentation-django

django ≥ 1.10

opentelemetry-instrumentation-elasticsearch

elasticsearch ≥ 2.0

opentelemetry-instrumentation-falcon

falcon - [1.4.1, 4.0.0)

opentelemetry-instrumentation-fastapi

fastapi ~= 0.58

opentelemetry-instrumentation-flask

flask - [1.0, 3.0)

opentelemetry-instrumentation-grpc

grpcio ~= 1.27

opentelemetry-instrumentation-httpx

httpx ≥ 0.18.0

opentelemetry-instrumentation-jinja2

jinja2 - [2.7, 4.0)

opentelemetry-instrumentation-kafka-python

kafka-python ≥ 2.0

opentelemetry-instrumentation-logging

logging

opentelemetry-instrumentation-mysql

mysql-connector-python ~= 8.0

opentelemetry-instrumentation-mysqlclient

mysqlclient < 3

opentelemetry-instrumentation-pika

pika ≥ 0.12.0

opentelemetry-instrumentation-psycopg2

psycopg2 ≥ 2.7.3.1

opentelemetry-instrumentation-pymemcache

pymemcache - [1.3.5, 5)

opentelemetry-instrumentation-pymongo

pymongo - [3.1, 5.0)

opentelemetry-instrumentation-pymysql

PyMySQL < 2

opentelemetry-instrumentation-pyramid

pyramid ≥ 1.7

opentelemetry-instrumentation-redis

redis ≥ 2.6

opentelemetry-instrumentation-remoulade

remoulade ≥ 0.50

opentelemetry-instrumentation-requests

requests ~= 2.0

opentelemetry-instrumentation-sqlalchemy

sqlalchemy

opentelemetry-instrumentation-sqlite3

sqlite3

opentelemetry-instrumentation-starlette

starlette ~= 0.13.0

opentelemetry-instrumentation-system-metrics

psutil ≥ 5

opentelemetry-instrumentation-tornado

tornado ≥ 5.1.1

opentelemetry-instrumentation-tortoiseorm

tortoise-orm ≥ 0.17.0

opentelemetry-instrumentation-urllib

urllib

opentelemetry-instrumentation-urllib3

urllib3 - [1.0.0, 3.0.0)

opentelemetry-instrumentation-wsgi

wsgi

Step 1: Get endpoint information

  1. Log on to the Cloud Monitor 2.0 console, and select a workspace. In the left navigation pane, click Integration Center.

  2. In the Server Applications section, click the Python card, and set Integration Protocol Type to OpenTelemetry.

  3. In the Parameter Settings section, click Get to the right of LicenseKey. Then, select the Instrumentation Method, Connection Method, and Reporting Method, and enter the Application Name, Version, and Deployment Environment.

    The corresponding integration code is generated at the bottom of the page based on your configuration, including the endpoint and LicenseKey.

    The Set up dependencies section at the bottom of the page displays the prerequisites (Python 3.7 or later), pip installation commands (pip install opentelemetry-distro opentelemetry-exporter-otlp and opentelemetry-bootstrap -a install), and the export commands for required environment variables. The values for OTEL_EXPORTER_OTLP_TRACES_ENDPOINT, OTEL_EXPORTER_OTLP_METRICS_ENDPOINT, and OTEL_EXPORTER_OTLP_HEADERS are automatically generated based on your configuration. Copy these variables into your application's startup script.

Step 2: Set up dependencies

Automatic instrumentation (recommended)

  1. Install the required packages.

    pip install opentelemetry-distro opentelemetry-exporter-otlp
    opentelemetry-bootstrap -a install
    Note

    The opentelemetry-bootstrap -a install command scans the site-packages folder of the current Python environment. If a framework that supports OpenTelemetry automatic instrumentation is found, the corresponding plugin is automatically installed. For example, if Django is already installed, the opentelemetry-instrumentation-django package is downloaded automatically.

  2. Configure the following environment variables, and then start your application.

    export OTEL_SERVICE_NAME=<service name>
    export OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
    export OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=<traces.endpoint>
    export OTEL_EXPORTER_OTLP_METRICS_ENDPOINT=<metrics.endpoint>
    export OTEL_EXPORTER_OTLP_HEADERS="x-arms-license-key=<license-key>,x-arms-project=<arms-project>,x-cms-workspace=<workspace>"
    export OTEL_RESOURCE_ATTRIBUTES=service.name=<service name>,acs.cms.workspace=<workspace>,service.version=<service version>,deployment.environment=<environment>
    opentelemetry-instrument <your_run_command>

    Replace the placeholders with the endpoint information obtained in Step 1. Replace <your_run_command> with the startup command for your Python application. Examples:

    • Standard application: python app.py

    • Flask application: flask run -p 8000

    • Django application: python manage.py runserver --noreload

    • uWSGI application: uwsgi --http :8000 --module app.wsgi

    • Gunicorn application: gunicorn app:app --bind=127.0.0.1:8000 or gunicorn app:app --workers 2 --worker-class uvicorn.workers.UvicornWorker --bind 127.0.0.1:8000 (multi-worker mode)

    • Uvicorn application: uvicorn app:app --host localhost --port 8000

    Note

    Do not enable hot reloading (such as --reload or reload=True) with automatic instrumentation, as it causes OpenTelemetry instrumentation to fail. Django enables hot reloading by default in the development environment, so you must specify --noreload explicitly. Automatic instrumentation does not currently support multi-worker mode for Uvicorn applications.

Manual instrumentation

  1. Install the required packages.

    pip install opentelemetry-api
    pip install opentelemetry-sdk
    pip install opentelemetry-exporter-otlp
  2. Create a Python demo application.

    Create a file named main.py and add the following code:

    from opentelemetry import trace, baggage
    from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter as OTLPSpanHttpExporter
    from opentelemetry.sdk.resources import DEPLOYMENT_ENVIRONMENT, HOST_NAME, Resource, SERVICE_NAME, SERVICE_VERSION
    from opentelemetry.sdk.trace import TracerProvider
    from opentelemetry.sdk.trace.export import BatchSpanProcessor
    def inner_method():
        tracer = trace.get_tracer(__name__)
        with tracer.start_as_current_span("child_span") as child_span:
            print("hello world")
    def outer_method():
        tracer = trace.get_tracer(__name__)
        with tracer.start_as_current_span("parent_span") as parent_span:
            inner_method()
    # Initialize OpenTelemetry.
    def init_opentelemetry():
        # Set the service name and hostname.
        resource = Resource(attributes={
            SERVICE_NAME: "<service name>",  # Application name.
            SERVICE_VERSION: "<service version>",  # Version.
            DEPLOYMENT_ENVIRONMENT: "<environment>", # Deployment environment.
            HOST_NAME: "${hostName}", # Replace ${hostName} with your hostname.
            "acs.cms.workspace": "<workspace>"  # Replace  with your workspace name.
        })
        headers = {
            "x-arms-license-key": "<license-key>",  # Replace <license-key> with the endpoint information obtained in Step 1.
            "x-arms-project": "<arms-project>",  # Replace <arms-project> with the endpoint information obtained in Step 1.
            "x-cms-workspace": "<workspace>"  # Replace <workspace> with your workspace name.
        }
        # Report data over HTTP.
        span_processor = BatchSpanProcessor(OTLPSpanHttpExporter(
            endpoint="<endpoint>",  # Replace <endpoint> with the endpoint from Step 1.
            headers=headers
        ))
        trace_provider = TracerProvider(resource=resource, active_span_processor=span_processor)
        trace.set_tracer_provider(trace_provider)
    if __name__ == '__main__':
        init_opentelemetry()
        outer_method()
  3. Start the application.

    python main.py

View monitoring data

  1. Log on to the Cloud Monitor 2.0 console, and select a workspace. In the left navigation pane, choose All Features > Application Observability > Application Monitoring.

  2. On the Application List page, click the target Application Name to view its monitoring details. For more information, see Application Monitoring.