在 Python 应用程序中为功能标志启用遥测

在本教程中,你将在 Python 应用程序中使用遥测来跟踪功能标志评估和自定义事件。 遥测允许你对功能管理策略做出明智的决策。 你在概述中创建了启用遥测的特性标志,并使用这些特性标志来启用遥测功能。 在继续作之前,请确保在配置存储中创建一个名为 Greeting 的功能标志,并启用遥测。 本教程基于在 Python 应用程序中使用变体功能标志的教程为基础。

先决条件

将遥测添加到 Python 应用程序

  1. 使用 pip 安装所需的包:

    pip install azure-appconfiguration-provider
    pip install featuremanagement["AzureMonitor"]
    pip install azure-monitor-opentelemetry
    
  2. 打开 app.py 并配置代码以连接到 Application Insights 以发布遥测数据。

    import os
    from azure.monitor.opentelemetry import configure_azure_monitor
    
    # Configure Azure Monitor
    configure_azure_monitor(connection_string=os.getenv("APPLICATIONINSIGHTS_CONNECTION_STRING"))
    
  3. 另外,在 app.py 中从应用程序配置加载功能标志并将其加载到功能管理中。 FeatureManager publish_telemetry使用回调函数将遥测数据发布到 Azure Monitor。

    from featuremanagement.azuremonitor import publish_telemetry
    
    feature_manager = FeatureManager(config, on_feature_evaluated=publish_telemetry)
    
  4. 打开 routes.py 并更新代码以跟踪应用程序中自己的事件。 调用 track_event 时,会将自定义事件与提供的用户一起发布到 Azure Monitor。

    from featuremanagement import track_event
    
    @bp.route("/heart", methods=["POST"])
    def heart():
        if current_user.is_authenticated:
            user = current_user.username
    
            # Track the appropriate event based on the action
            track_event("Liked", user)
        return jsonify({"status": "success"})
    
  5. 打开 index.html 并更新代码以实现类似按钮。 单击后,like 按钮会将 POST 请求发送到 /heart 终结点。

    <script>
        function heartClicked(button) {
            var icon = button.querySelector('i');
    
            // Toggle the heart icon appearance
            icon.classList.toggle('far');
            icon.classList.toggle('fas');
    
            // Only send a request to the dedicated heart endpoint when it's a like action
            if (icon.classList.contains('fas')) {
                fetch('/heart', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    }
                });
            }
        }
    </script>
    

生成并运行应用

  1. Application Insights 需要连接字符串才能连接到 Application Insights 资源。 将 APPLICATIONINSIGHTS_CONNECTION_STRING 环境变量设置为 Application Insights 资源的连接字符串。

    setx APPLICATIONINSIGHTS_CONNECTION_STRING "applicationinsights-connection-string"
    

    如果使用 PowerShell,请运行以下命令:

    $Env:APPLICATIONINSIGHTS_CONNECTION_STRING = "applicationinsights-connection-string"
    

    如果使用 macOS 或 Linux,则请运行以下命令:

    export APPLICATIONINSIGHTS_CONNECTION_STRING='applicationinsights-connection-string'
    

收集遥测数据

部署应用程序以开始从用户收集遥测数据。 若要测试其功能,可以通过创建多个测试用户来模拟用户活动。 每个用户将体验不同的问候消息变体,他们可以通过单击心脏按钮来与应用程序交互,以像报价一样。 随着用户群的增长,可以监视 Azure 应用配置中收集的遥测数据量增加。 此外,还可以向下钻取到数据,以分析功能标志的每个变体如何影响用户行为。

其他资源