Updated on 2026-01-30 GMT+08:00

Reporting Python Application Data Using OpenTelemetry

Huawei Cloud APM is compatible with OpenTelemetry and can directly receive the trace data reported using the OpenTelemetry SDK or Agent. This section describes how to use OpenTelemetry to connect a Python application to APM and report trace data.

Constraint

Python 3.9 or later must be used.

Environment Preparation

  1. Install Python:
    sudo apt update 
    sudo apt install python3 python3-pip python3-venv
  2. Verify the environment:
    python3 --version
    pip3 --version

Demo

Implement a simple dice roller application using the Flask framework.

  1. Create a running environment:
    mkdir demo 
    cd demo 
    python3 -m venv demo 
    source ./demo/bin/activate
  2. Download dependencies:
    pip install flask
  3. Compile the service code. Create an app.py file:
    from random import randint
    from flask import Flask, request
    import logging
    
    app = Flask(__name__)
    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger(__name__)
    
    @app.route("/rolldice")
    def roll_dice():
        player = request.args.get('player', default=None, type=str)
        result = str(roll())
        if player:
            logger.warning("%s is rolling the dice: %s", player, result)
        else:
            logger.warning("Anonymous player is rolling the dice: %s", result)
        return result
    
    def roll():
        return randint(1, 6)
  4. Run the startup command:
    flask run -p 8080 &
    curl http://localhost:8080/rolldice

Auto Tracking

  1. Download dependencies:

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

  2. Start the Python application:

    opentelemetry-instrument  \
    --traces_exporter otlp  \
    --metrics_exporter none \
    --service_name Application name.Component name.Environment name  \  
    --resource_attributes host.name=hostName  \
    --exporter_otlp_endpoint Reporting address  \
    --exporter_otlp_headers Authentication=Authentication information    \
    flask run -p 8080  &
    
    curl  http://localhost:8080/rolldice

  3. Trigger a request:

    curl http://localhost:8080/rolldice

  4. Log in to the APM console.
  5. Click on the left and choose Management & Governance > Application Performance Management.
  6. In the navigation pane, choose Link Trace > Metrics.
  7. In the tree on the left, locate an environment and then go to the URL tab page to view the URL calling data.
  8. In the navigation pane, choose Link Trace > Tracing.